content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Calculate negative log posterior #' #' @param theta Correlation parameters #' @param CGGP CGGP object #' @param y Measured values of CGGP$design #' @param ... Forces you to name remaining arguments #' @param Xs Supplementary input data #' @param ys Supplementary output data #' @param HandlingSuppData How should supplementary data be handled? #' * Correct: full likelihood with grid and supplemental data #' * Only: only use supplemental data #' * Ignore: ignore supplemental data #' @md #' #' @return Likelihood #' @export #' @useDynLib CGGP #' #' @examples #' cg <- CGGPcreate(d=3, batchsize=20) #' Y <- apply(cg$design, 1, function(x){x[1]+x[2]^2}) #' cg <- CGGPfit(cg, Y) #' CGGP_internal_neglogpost(cg$thetaMAP, CGGP=cg, y=cg$y) CGGP_internal_neglogpost <- function(theta, CGGP, y, ..., ys=NULL, Xs=NULL, HandlingSuppData = "Correct") { # Return Inf if theta is too large if (max(theta) >= 1 || min(theta) <= -1) { return(Inf) } # ================================ # Check that inputs are acceptable # ================================ if (!(HandlingSuppData %in% c("Correct", "Only", "Ignore"))) { stop(paste("HandlingSuppData in CGGP_internal_neglogpost must be one of", "Correct, Only, Ignore")) } if(!(is.null(ys) || length(ys)==0) && (is.null(y) || length(y)==0)){ HandlingSuppData = "Only" }else if((is.null(ys) || length(ys)==0) && !(is.null(y) || length(y)==0)){ HandlingSuppData = "Ignore" }else if((is.null(ys) || length(ys)==0) && (is.null(y) || length(y)==0)){ stop(paste("You have given no y or ys to CGGP_internal_neglogpost")) } # ======================= # Calculate neglogpost # ======================= if(HandlingSuppData == "Only" || HandlingSuppData == "Correct"){ Sigma_t = matrix(0,dim(Xs)[1],dim(Xs)[1]) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(Xs[,dimlcv], Xs[,dimlcv], theta[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara], returnlogs=TRUE) Sigma_t = Sigma_t+V } Sigma_t = exp(Sigma_t) Sigma_t = (1-CGGP$nugget)*Sigma_t+diag(dim(Sigma_t)[1])*CGGP$nugget } if(HandlingSuppData == "Only"){ try.chol <- try({Sigma_chol = chol(Sigma_t)}, silent = TRUE) if (inherits(try.chol, "try-error")) { return(Inf) }; rm(try.chol) Sti_resid = backsolve(Sigma_chol,backsolve(Sigma_chol,ys,transpose=TRUE)) sigma2_hat_supp = colSums(as.matrix(ys*Sti_resid))/dim(Xs)[1] lDet_supp = 2*sum(log(diag(Sigma_chol))) } if(HandlingSuppData == "Ignore"){ sigma2anddsigma2 <- CGGP_internal_calcsigma2(CGGP=CGGP, y=y, theta=theta, return_lS=TRUE) lS <- sigma2anddsigma2$lS sigma2_hat_grid = sigma2anddsigma2$sigma2 lDet_grid = 0 for (blocklcv in 1:CGGP$uoCOUNT) { nv = CGGP$gridsize[blocklcv]/CGGP$gridsizes[blocklcv,] uonow = CGGP$uo[blocklcv,] for (dimlcv in which(uonow>1.5)) { lDet_grid = lDet_grid + ( lS[uonow[dimlcv], dimlcv] - lS[uonow[dimlcv] - 1, dimlcv] )*nv[dimlcv] } } } if(HandlingSuppData == "Correct"){ lik_stuff <- CGGP_internal_calc_cholS_lS_sigma2_pw(CGGP=CGGP, y=y, theta=theta) cholS = lik_stuff$cholS lS <- lik_stuff$lS sigma2_hat_grid = lik_stuff$sigma2 pw = lik_stuff$pw lDet_grid = 0 # Not needed for glik, only for lik for (blocklcv in 1:CGGP$uoCOUNT) { nv = CGGP$gridsize[blocklcv]/CGGP$gridsizes[blocklcv,] uonow = CGGP$uo[blocklcv,] for (dimlcv in which(uonow>1.5)) { lDet_grid = lDet_grid + (lS[uonow[dimlcv], dimlcv] - lS[uonow[dimlcv] - 1, dimlcv])*nv[dimlcv] } } #For these three, I need Cs,pw,allChols Cs = (matrix(0,dim(Xs)[1],CGGP$ss)) GGGG = list(matrix(1,dim(Xs)[1],length(CGGP$xb)),CGGP$d) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(Xs[,dimlcv], CGGP$xb[1:CGGP$sizest[max(CGGP$uo[,dimlcv])]], theta[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara], returnlogs=TRUE) GGGG[[dimlcv]] = exp(V) Cs = Cs+V[,CGGP$designindex[,dimlcv]] } Cs = exp(Cs) yhats = Cs%*%pw } if(HandlingSuppData == "Correct" ){ Sigma_t = matrix(0,dim(Xs)[1],dim(Xs)[1]) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(Xs[,dimlcv], Xs[,dimlcv], theta[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara], returnlogs=TRUE) Sigma_t = Sigma_t+V } Sigma_t = exp(Sigma_t) MSE_s = matrix(NaN,nrow=dim(Xs)[1]*dim(Xs)[1], ncol=(CGGP$d)*(CGGP$maxlevel)) Q = max(CGGP$uo[1:CGGP$uoCOUNT,]) for (dimlcv in 1:CGGP$d) { gg = (dimlcv-1)*Q TT1 = GGGG[[dimlcv]] for (levellcv in 1:max(CGGP$uo[1:CGGP$uoCOUNT,dimlcv])) { INDSN = 1:CGGP$sizest[levellcv] INDSN = INDSN[sort(CGGP$xb[1:CGGP$sizest[levellcv]], index.return = TRUE)$ix] REEALL = CGGP_internal_postvarmatcalc_fromGMat( TT1, c(), as.matrix(cholS[[gg+levellcv]]), c(), INDSN, CGGP$numpara) MSE_s[,(dimlcv-1)*CGGP$maxlevel+levellcv] = as.vector(REEALL) } } Sigma_t2 = as.vector(Sigma_t) rcpp_fastmatclcr(CGGP$uo[1:CGGP$uoCOUNT,], CGGP$w[1:CGGP$uoCOUNT], MSE_s,Sigma_t2,CGGP$maxlevel) Sigma_t = matrix(Sigma_t2,nrow=dim(Xs)[1] , byrow = FALSE) Sigma_t = (1-CGGP$nugget)*Sigma_t+diag(dim(Sigma_t)[1])*CGGP$nugget try.chol <- try({Sigma_chol = chol(Sigma_t)}, silent = TRUE) if (inherits(try.chol, "try-error")) { return(Inf) }; rm(try.chol) Sti_resid = backsolve(Sigma_chol,backsolve(Sigma_chol,ys-yhats, transpose = TRUE)) sigma2_hat_supp = colSums((ys-yhats)*Sti_resid)/dim(Xs)[1] lDet_supp = 2*sum(log(diag(Sigma_chol))) } if(HandlingSuppData == "Ignore"){ sigma2_hat = sigma2_hat_grid lDet = lDet_grid if(!is.matrix(y)){ nsamples = length(y) }else{ nsamples = dim(y)[1] } } if(HandlingSuppData == "Only"){ sigma2_hat = sigma2_hat_supp lDet = lDet_supp if(!is.matrix(ys)){ nsamples = length(ys) }else{ nsamples = dim(ys)[1] } } if(HandlingSuppData =="Correct"){ sigma2_hat = sigma2_hat_grid*dim(CGGP$design)[1] / ( dim(Xs)[1]+dim(CGGP$design)[1])+sigma2_hat_supp*dim(Xs)[1]/( dim(Xs)[1]+dim(CGGP$design)[1]) lDet = lDet_grid+lDet_supp if(!is.matrix(y)){ nsamples = length(y)+length(ys) }else{ nsamples = dim(y)[1]+dim(ys)[1] } } neglogpost = 0.1*sum((log(1-theta)-log(theta+1))^2) #start out with prior neglogpost = neglogpost+0.1*sum((log(1-theta)-log(theta+1))^4) #start out with prior output_is_1D <- if (!is.null(y)) {!is.matrix(y)} else {!is.matrix(ys)} if(output_is_1D){ neglogpost = neglogpost+1/2*(nsamples*log(sigma2_hat[1])+lDet) }else{ neglogpost = neglogpost+1/2*(nsamples*mean(log(c(sigma2_hat)))+lDet) } return(neglogpost) }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/CGGP_neglogpost.R
#' Heatmap of SG design depth #' #' The values on the diagonal are largest design depth for that dimension. #' The off-diagonal values are the largest design depth that both dimensions #' have been measured at simultaneously. #' A greater depth means that more points have been measured along that #' dimension or two-dimensional subspace. #' #' @param CGGP CGGP object #' #' @return A heat map made from ggplot2 #' @export #' @family CGGP plot functions #' @references https://stackoverflow.com/questions/14290364/heatmap-with-values-ggplot2 #' #' @examples #' \donttest{ #' # All dimensions should look similar #' d <- 8 #' SG = CGGPcreate(d,201) #' CGGPplotheat(SG) #' #' # The first and fourth dimensions are most active and will have greater depth #' SG <- CGGPcreate(d=5, batchsize=50) #' f <- function(x) {cos(2*pi*x[1]*3) + exp(4*x[4])} #' for (i in 1:1) { #' SG <- CGGPfit(SG, Y=apply(SG$design, 1, f)) #' SG <- CGGPappend(CGGP=SG, batchsize=200) #' } #' # SG <- CGGPfit(SG, Y=apply(SG$design, 1, f)) #' CGGPplotheat(SG) #' } CGGPplotheat <- function(CGGP) { skinny <- NULL for (i in 1:CGGP$d) { skinny <- rbind(skinny, c(i, i, max(CGGP$uo[,i]))) } for (i in 1:(CGGP$d-1)) { for (j in (i+1):CGGP$d) { skinny <- rbind(skinny, c(i, j, max(apply(CGGP$uo[,c(i,j)], 1, min))), c(j, i, max(apply(CGGP$uo[,c(i,j)], 1, min))) ) } } skdf <- data.frame(skinny) names(skdf) <- c('Var1', 'Var2', 'value') ggplot2::ggplot(skdf, ggplot2::aes_string('Var1', 'Var2')) + ggplot2::geom_tile(ggplot2::aes_string(fill = 'value')) + ggplot2::geom_text(ggplot2::aes_string(label = 'round(value, 1)')) + ggplot2::scale_fill_gradient(low = "white", high = "red") + # ggplot2::scale_fill_gradient(low = "yellow", high = "red") + ggplot2::scale_x_continuous(breaks = 1:CGGP$d) + ggplot2::scale_y_continuous(breaks = 1:CGGP$d) # labels=c() to set names } #' Histogram of measurements at each design depth of each input dimension #' #' A greater design depth signifies a more important dimension. #' Thus a larger right tail on the histogram are more important variables. #' #' @param CGGP CGGP object #' @param ylog Should the y axis be put on a log scale? #' #' @return Histogram plot made using ggplot2 #' @export #' @family CGGP plot functions #' #' @examples #' \donttest{ #' # All dimensions should look similar #' d <- 8 #' SG = CGGPcreate(d,201) #' CGGPplothist(SG) #' CGGPplothist(SG, ylog=FALSE) #' #' # The first dimension is more active and will have greater depth #' f <- function(x) {sin(x[1]^.6*5)} #' SG <- CGGPcreate(d=5, batchsize=100) #' SG <- CGGPfit(SG, apply(SG$design, 1, f)) #' SG <- CGGPappend(CGGP=SG, batchsize=1000) #' CGGPplothist(SG) #' } CGGPplothist <- function(CGGP, ylog=TRUE) { p <- ggplot2::ggplot(reshape2::melt(data.frame(CGGP$uo), id.vars=NULL), ggplot2::aes_string(x='value')) p <- p +ggplot2::geom_histogram(binwidth = 1) + ggplot2::facet_grid(variable ~ .) if (ylog) { p <- p + ggplot2::scale_y_log10() #limits=c(.9999, NA)) } p <- p + ggplot2::theme(strip.text.y = ggplot2::element_text(angle = 0)) # rotates labels from vert to hor p } #' CGGP block plot #' #' Plot the 2D projections of the blocks of an CGGP object. #' #' @param CGGP CGGP object #' @param singleplot If only two dimensions, should a single plot be made? #' #' @return ggplot2 plot #' @export #' @family CGGP plot functions #' #' @examples #' \donttest{ #' # The first and fourth dimensions are most active and will have greater depth #' ss <- CGGPcreate(d=5, batchsize=50) #' f <- function(x) {cos(2*pi*x[1]*3) + x[3]*exp(4*x[4])} #' ss <- CGGPfit(ss, Y=apply(ss$design, 1, f)) #' ss <- CGGPappend(CGGP=ss, batchsize=100) #' CGGPplotblocks(ss) #' #' mat <- matrix(c(1,1,1,2,2,1,2,2,1,3), ncol=2, byrow=TRUE) #' CGGPplotblocks(mat) #' } CGGPplotblocks <- function(CGGP, singleplot=TRUE) { if (inherits(CGGP, "CGGP")) { d <- CGGP$d uo <- CGGP$uo[1:CGGP$uoCOUNT,] } else if (is.matrix(CGGP)) { d <- ncol(CGGP) uo <- CGGP } else {stop("CGGPplotblocks only works on CGGP or matrix")} if (d>2) {singleplot <- FALSE} # Can only use singleplot in 2D alldf <- NULL # ds <- c(1,2) d1set <- if (singleplot) {1} else {1:d} for (d1 in d1set) { d2set <- setdiff(1:d, d1) for (d2 in d2set) { ds <- c(d1, d2) uods <- uo[,ds] uodsdf <- data.frame(uods) uods.unique <- plyr::ddply(uodsdf, c("X1", "X2"), function(x) data.frame(count=nrow(x))) gdf <- uods.unique gdf$xmin <- gdf$X1-1 gdf$xmax <- gdf$X1 gdf$ymin <- gdf$X2-1 gdf$ymax <- gdf$X2 gdf$d1 <- d1 gdf$d2 <- d2 alldf <- if (is.null(alldf)) gdf else rbind(alldf, gdf) } } p <- ggplot2::ggplot(alldf) + ggplot2::geom_rect(ggplot2::aes_string(xmin="xmin", xmax="xmax", ymin="ymin", ymax="ymax", fill="count"), color="black")+ ggplot2::scale_fill_gradient(low = "yellow", high = "red") if (!singleplot) {p <- p + ggplot2::facet_grid(d1 ~ d2)} else {p <- p+ggplot2::xlab("X1") + ggplot2::ylab("X2")} p } #' Plot validation prediction errors #' #' @param predmean Predicted mean #' @param predvar Predicted variance #' @param Yval Y validation data #' @param d If output is multivariate, which column to use. Will do all if #' left as NULL. #' #' @return None, makes a plot #' @export #' @importFrom graphics plot points polygon #' #' @examples #' x <- matrix(runif(100*3), ncol=3) #' f1 <- function(x){x[1]+x[2]^2} #' y <- apply(x, 1, f1) #' # Create a linear model on the data #' mod <- lm(y ~ ., data.frame(x)) #' # Predict at validation data #' Xval <- matrix(runif(3*100), ncol=3) #' mod.pred <- predict.lm(mod, data.frame(Xval), se.fit=TRUE) #' # Compare to true results #' Yval <- apply(Xval, 1, f1) #' valplot(mod.pred$fit, mod.pred$se.fit^2, Yval=Yval) valplot <- function(predmean, predvar, Yval, d=NULL) { if (!is.null(d)) { predmean <- predmean[,d] predvar <- predvar[,d] Yval <- Yval[,d] } errmax <- max(sqrt(predvar), abs(predmean - Yval)) errs <- unname(predmean-Yval) psds <- unname(sqrt(predvar)) if (!is.matrix(errs) || ncol(errs)==1) { # vector, single output tdf <- data.frame(err=errs, psd=psds) } else { # multiple outputs, need to melt tdf <- cbind(reshape2::melt(errs), reshape2::melt(psds))[,c(3,6,2)] tdf <- data.frame(tdf) names(tdf) <- c("err", "psd", "outputdim") } # ggplot(tdf, aes(x=err, y=psd)) + geom_point() values <- data.frame(id=factor(c(2,1)), Error=factor(c('68%','95%'))) positions <- data.frame(id=rep(values$id, each=3), x=1.1*c(0,errmax*2,-errmax*2, 0,errmax,-errmax), y=1.1*c(0,errmax,errmax,0,errmax,errmax)) # Currently we need to manually merge the two together datapoly <- merge(values, positions, by = c("id")) # ggplot(datapoly, aes(x = x, y = y)) + # geom_polygon(aes(fill = value, group = id)) # ggplot(tdf, aes(x=err, y=psd)) + geom_polygon(aes(fill = value, group = id, x=x, y=y), # datapoly, alpha=.2) + geom_point() + # xlab("Predicted - Actual") + ylab("Predicted error") + # coord_cartesian(xlim=c(-errmax,errmax), ylim=c(0,errmax)) p <- ggplot2::ggplot(tdf, ggplot2::aes_string(x='err', y='psd')) + ggplot2::geom_polygon(ggplot2::aes_string(fill = 'Error', group = 'id', x='x', y='y'), datapoly[datapoly$id==2,], alpha=.2) + # Separate these so it does the right order ggplot2::geom_polygon(ggplot2::aes_string(fill = 'Error', group = 'id', x='x', y='y'), datapoly[datapoly$id==1,], alpha=.2) + ggplot2::geom_point() + ggplot2::xlab("Predicted - Actual") + ggplot2::ylab("Predicted error") + ggplot2::coord_cartesian(xlim=c(-errmax,errmax), ylim=c(0,max(psds))) #errmax)) if (is.matrix(errs) && ncol(errs) > 1) { p <- p + ggplot2::facet_wrap("outputdim") } p } #' Plot validation prediction errors for CGGP object #' #' @param CGGP CGGP object that has been fitted #' @param Xval X validation data #' @param Yval Y validation data #' @param d If output is multivariate, which column to use. Will do all if #' left as NULL. #' #' @return None, makes a plot #' @export #' @family CGGP plot functions #' @importFrom graphics plot points polygon #' #' @examples #' SG <- CGGPcreate(d=3, batchsize=100) #' f1 <- function(x){x[1]+x[2]^2} #' y <- apply(SG$design, 1, f1) #' SG <- CGGPfit(SG, y) #' Xval <- matrix(runif(3*100), ncol=3) #' Yval <- apply(Xval, 1, f1) #' CGGPvalplot(CGGP=SG, Xval=Xval, Yval=Yval) CGGPvalplot <- function(CGGP, Xval, Yval, d=NULL) { ypred <- CGGPpred(CGGP=CGGP, xp=Xval) valplot(ypred$mean, ypred$var, Yval, d=d) } #' Calculate stats for prediction on validation data #' #' @param predmean Predicted mean #' @param predvar Predicted variance #' @param Yval Y validation data #' @param bydim If multiple outputs, should it be done separately by dimension? #' @param metrics Optional additional metrics to be calculated. Should have #' same first three parameters as this function. #' @param min_var Minimum value of the predicted variance. #' Negative or zero variances can cause errors. #' @param RMSE Should root mean squared error (RMSE) be included? #' @param score Should score be included? #' @param CRPscore Should CRP score be included? #' @param coverage Should coverage be included? #' @param R2 Should R^2 be included? #' @param corr Should correlation between predicted and true mean be included? #' @param MAE Should mean absolute error (MAE) be included? #' @param MIS90 Should mean interval score for 90\% confidence be included? #' See Gneiting and Raftery (2007). #' #' @return data frame #' @export #' @importFrom stats pnorm dnorm cor #' @references Gneiting, Tilmann, and Adrian E. Raftery. #' "Strictly proper scoring rules, prediction, and estimation." #' Journal of the American Statistical Association 102.477 (2007): 359-378. #' #' @examples #' valstats(c(0,1,2), c(.01,.01,.01), c(0,1.1,1.9)) #' valstats(cbind(c(0,1,2), c(1,2,3)), #' cbind(c(.01,.01,.01),c(.1,.1,.1)), #' cbind(c(0,1.1,1.9),c(1,2,3))) #' valstats(cbind(c(0,1,2), c(8,12,34)), #' cbind(c(.01,.01,.01),c(1.1,.81,1.1)), #' cbind(c(0,1.1,1.9),c(10,20,30)), bydim=FALSE) #' valstats(cbind(c(.8,1.2,3.4), c(8,12,34)), #' cbind(c(.01,.01,.01),c(1.1,.81,1.1)), #' cbind(c(1,2,3),c(10,20,30)), bydim=FALSE) valstats <- function(predmean, predvar, Yval, bydim=TRUE, RMSE=TRUE, score=TRUE, CRPscore=TRUE, coverage=TRUE, corr=TRUE, R2=TRUE, MAE=FALSE, MIS90=FALSE, metrics, min_var=.Machine$double.eps) { if (missing(predvar) || is.null(predvar)) { predvar <- NaN * predmean } # Boost up all variances to at least min_var, should be tiny number if (is.numeric(min_var) && !is.na(min_var) && min_var>=0) { predvar <- pmax(predvar, min_var) } if ((is.matrix(predmean) && (any(dim(predmean)!=dim(predvar)) || any(dim(predmean)!=dim(Yval))) ) || (length(predmean)!=length(predvar) || length(predmean)!=length(Yval)) ) { stop("Shape of predmean, predvar, and Yval must match in valstats") } if (bydim && is.matrix(predmean) && ncol(predmean) > 1) { return(do.call("rbind", lapply(1:ncol(predmean), function(i) { valstats(predmean=predmean[,i], predvar=predvar[,i], Yval=Yval[,i]) }))) } m <- predmean v <- pmax(predvar, 0) s <- sqrt(v) z <- (Yval - m) / s # Create out df, add desired elements out <- data.frame(DELETETHISELEMENT=NaN) if (RMSE) out$RMSE <- sqrt(mean((predmean - Yval)^2)) if (score) out$score <- mean((Yval-predmean)^2/predvar+log(predvar)) if (CRPscore) out$CRPscore <- - mean(s * (1/sqrt(pi) - 2*dnorm(z) - z * (2*pnorm(z) - 1))) if (coverage) out$coverage <- mean((Yval<= predmean+1.96*sqrt(predvar)) & (Yval>= predmean-1.96*sqrt(predvar))) if (corr) out$corr <- cor(c(predmean), c(Yval)) if (R2) out$R2 <- 1 - (sum((Yval - predmean)^2) / sum((Yval - mean(Yval))^2)) if (MAE) out$MAE <- mean(abs(predmean - Yval)) if (MIS90) { out$MIS90 <- mean(3.28 * s + 20 * pmax(0, m - Yval - 1.64 * s) + 20 * pmax(0, -m + Yval - 1.64 * s)) } # Remove initial element out$DELETETHISELEMENT <- NULL # Add normalized RMSE, dividing MSE in each dimension by variance if (is.matrix(predmean) && ncol(predmean) > 1) { # out$RMSEnorm <- sqrt(mean(sweep((predmean - Yval)^2, 2, apply(Yval, 2, var), "/"))) out$RMSEnorm <- sqrt(mean(colMeans((predmean - Yval)^2) / apply(Yval, 2, var))) } # Check if user wants more metrics if (!missing(metrics)) { if (is.function(metrics)) { out$metric <- metrics(predmean, predvar, Yval) } else if (is.list(metrics)) { metrics.names <- names(metrics) if (is.null(metrics.names)) { metrics.names <- paste0("metrics", 1:length(metrics)) } for (iii in 1:length(metrics)) { out[[metrics.names[iii]]] <- metrics[[iii]](predmean, predvar, Yval) } } } out } #' Calculate stats for CGGP prediction on validation data #' #' @param CGGP CGGP object #' @param Xval X validation matrix #' @param Yval Y validation data #' @param bydim If multiple outputs, should it be done separately by dimension? #' @param ... Passed to valstats, such as which stats to calculate. #' #' @return data frame #' @export #' #' @examples #' \donttest{ #' SG <- CGGPcreate(d=3, batchsize=100) #' f1 <- function(x){x[1]+x[2]^2} #' y <- apply(SG$design, 1, f1) #' SG <- CGGPfit(SG, y) #' Xval <- matrix(runif(3*100), ncol=3) #' Yval <- apply(Xval, 1, f1) #' CGGPvalstats(CGGP=SG, Xval=Xval, Yval=Yval) #' #' # Multiple outputs #' SG <- CGGPcreate(d=3, batchsize=100) #' f1 <- function(x){x[1]+x[2]^2} #' f2 <- function(x){x[1]^1.3+.4*sin(6*x[2])+10} #' y1 <- apply(SG$design, 1, f1)#+rnorm(1,0,.01) #' y2 <- apply(SG$design, 1, f2)#+rnorm(1,0,.01) #' y <- cbind(y1, y2) #' SG <- CGGPfit(SG, Y=y) #' Xval <- matrix(runif(3*100), ncol=3) #' Yval <- cbind(apply(Xval, 1, f1), #' apply(Xval, 1, f2)) #' CGGPvalstats(SG, Xval, Yval) #' CGGPvalstats(SG, Xval, Yval, bydim=FALSE) #' } CGGPvalstats <- function(CGGP, Xval, Yval, bydim=TRUE, ...) { # Make predictions ypred <- CGGPpred(CGGP=CGGP, xp=Xval) # Use valstats to get df with values valstats(ypred$mean, ypred$var, Yval=Yval, bydim=bydim, ...) } #' Plot correlation samples #' #' Plot samples for a given correlation function and parameters. #' Useful for getting an idea of what the correlation parameters mean #' in terms of smoothness. #' #' @param Corr Correlation function or CGGP object. #' If CGGP object, it will make plots for thetaMAP, #' the max a posteriori theta. #' @param theta Parameters for Corr #' @param numlines Number of sample paths to draw #' @param zero Should the sample paths start at y=0? #' @param outdims Which output dimensions should be used? #' #' @return Plot #' @export #' @family CGGP plot functions #' @importFrom graphics par #' #' @examples #' \donttest{ #' CGGPplotcorr() #' CGGPplotcorr(theta=c(-2,-1,0,1)) #' #' SG <- CGGPcreate(d=3, batchsize=100) #' f <- function(x){x[1]^1.2+sin(2*pi*x[2]*3)} #' y <- apply(SG$design, 1, f) #' SG <- CGGPfit(SG, Y=y) #' CGGPplotcorr(SG) #' } CGGPplotcorr <- function(Corr=CGGP_internal_CorrMatGaussian, theta=NULL, numlines=20, outdims=NULL, zero=TRUE) { # Points along x axis n <- 100 xl <- seq(0,1,l=n) if (inherits(Corr, "CGGP")) { if (is.null(theta)) {theta <- Corr$thetaMAP} Corr <- Corr$CorrMat } nparam <- Corr(return_numpara=TRUE) if (is.null(theta)) {theta <- rep(0, nparam)} thetadims <- if (is.matrix(theta)) {ncol(theta)} else {1} if (is.null(outdims)) { outdims <- 1:thetadims } else { theta <- theta[,outdims, drop=FALSE] } numoutdims <- length(outdims) thetadims <- if (is.matrix(theta)) {ncol(theta)} else {1} numindims <- length(theta) / nparam / numoutdims indims <- 1:numindims ggdf <- NULL for (indim in indims) { for (outdim in outdims) { theta.thisloop <- if (thetadims>1) {theta[1:nparam + nparam*(indim-1), outdim]} else {theta[1:nparam + nparam*(indim-1)]} # Can change px.mean and px.cov to be conditional on other data px.mean <- rep(0,n) px.cov <- Corr(xl, xl, theta=theta.thisloop) # Generate sample paths samplepaths <- newy <- MASS::mvrnorm(n=numlines, mu=px.mean, Sigma=px.cov) # Set so all start at 0. if (zero) { samplepathsplot <- sweep(samplepaths, 1, samplepaths[,1]) } # Make data correct shape and add newdf <- cbind(reshape2::melt(data.frame(t(samplepathsplot)), id.vars=c()), x=rep(xl, numlines), d=paste0("X",indim), outdim=paste0("Y",outdim)) if (is.null(ggdf)) {ggdf <- newdf} else {ggdf <- rbind(ggdf, newdf)} } } # Return plot p <- ggplot2::ggplot(ggdf, ggplot2::aes_string(x="x", y="value", color="variable")) + ggplot2::geom_line() + ggplot2::theme(legend.position="none") if (numindims > 1 && numoutdims==1) { p <- p + ggplot2::facet_grid(d ~ .) } else if (numindims > 1 && numoutdims > 1) { p <- p + ggplot2::facet_grid(d ~ outdim) } p } #' CGGP slice plot #' #' Show prediction plots when varying over only one dimension. #' Most useful when setting all values to 0.5 because it will #' have the most points. #' #' @param CGGP CGGP object #' @param proj Point to project onto #' @param np Number of points to use along each dimension #' @param color Color to make error region #' @param outdims If multiple outputs, which of them should be plotted? #' @param scales Parameter passed to ggplot2::facet_grid() #' @param facet If "grid", will use ggplot2::facet_grid(), if "wrap" will #' use ggplot2::facet_wrap(). Only applicable for a single output dimension. #' #' @return ggplot2 object #' @export #' @family CGGP plot functions #' #' @examples #' \donttest{ #' d <- 5 #' f1 <- function(x){x[1]+x[2]^2 + cos(x[3]^2*2*pi*4) - 3.3} #' s1 <- CGGPcreate(d, 200) #' s1 <- CGGPfit(s1, apply(s1$design, 1, f1)) #' #s1 <- CGGPappend(s1, 200) #' #s1 <- CGGPfit(s1, apply(s1$design, 1, f1)) #' CGGPplotslice(s1) #' CGGPplotslice(s1, 0.) #' CGGPplotslice(s1, s1$design[nrow(s1$design),]) #' } CGGPplotslice <- function(CGGP, proj=.5, np=300, color="pink", outdims, scales="free_y", facet="grid") { if (!is.null(CGGP$design_unevaluated)) {stop("CGGP must be updated with all data")} if (length(proj) == 1) {proj <- rep(proj, CGGP$d)} if (length(proj) != CGGP$d) {stop("proj should be of length CGGP$d or 1")} d <- CGGP$d tdfall <- NULL pointdfall <- NULL Y <- as.matrix(CGGP$Y) if (missing(outdims)) { numoutdims <- ncol(Y) outdims <- 1:numoutdims } else { numoutdims <- length(outdims) } for (d5 in 1:d) { xl <- seq(0,1,l=np) m <- matrix(proj,np,d, byrow=T) m[,d5] <- xl # Won't work if it used PCA or shared parameters p5 <- try(CGGPpred(CGGP, m, outdims=outdims), silent = TRUE) if (inherits(p5, "try-error")) { p5 <- CGGPpred(CGGP, m) } # p5 %>% str # poly <- cbind(c(rep(xl,each=2))[-c(1,2*np)]) # If multiple outputs, get all of them for (outdim in outdims) { if (is.matrix(p5$mean)) { #numoutdims > 1) { tdf <- data.frame(mean=p5$mean[,outdim], var=p5$var[,outdim]) } else { # Single out dim tdf <- as.data.frame(p5) } tdf$outdim <- outdim tdf$var <- pmax(0, tdf$var) # No negative values tdf$sd <- sqrt(tdf$var) tdf$meanp2sd <- tdf$mean + 2*tdf$sd tdf$meanm2sd <- tdf$mean - 2*tdf$sd tdf$x <- xl tdf$d <- d5 tdfall <- rbind(tdfall, tdf) } w2.5 <- apply(CGGP$design[,-d5, drop=FALSE], 1, function(x) all(abs(x - proj[-d5]) < 1e-8)) x2.5 <- CGGP$design[w2.5,, drop=FALSE] y2.5 <- Y[w2.5,, drop=FALSE] # plot(x2.5[,d5], y2.5) pointdf <- NULL if (length(y2.5) > 0) { for (outdim in outdims) { pointdf <- rbind(pointdf, data.frame(x=x2.5[,d5], y=y2.5[,outdim], d=d5, outdim=outdim)) } } pointdfall <- rbind(pointdfall, pointdf) } tdfall$d <- paste0("X", tdfall$d) tdfall$outdim <- paste0("Y", tdfall$outdim) if (!is.null(pointdfall)) { pointdfall$d <- paste0("X", pointdfall$d) pointdfall$outdim <- paste0("Y", pointdfall$outdim) } p <- ggplot2::ggplot(tdfall, ggplot2::aes_string(x='x')) + ggplot2::geom_ribbon(ggplot2::aes_string(ymin='meanm2sd', ymax='meanp2sd'), color=color, fill=color) + ggplot2::geom_line(ggplot2::aes_string(y='mean')) if (!is.null(pointdfall)) { p <- p + ggplot2::geom_point(ggplot2::aes_string(x='x', y='y'), data=pointdfall) } if (numoutdims == 1) { if (facet == "grid") { p <- p + ggplot2::facet_grid(d ~ .) } else if (facet == "wrap") { p <- p + ggplot2::facet_wrap(d ~ .) } else { stop("Not valid facet argument in CGGPplotslice") } } else { p <- p +ggplot2::facet_grid(outdim ~ d, scales=scales) #"free_y") } p } #' Plot something similar to a semivariogram #' #' It's not actually a variogram or semivariogram. #' It shows how the correlation function falls off as distance increases. #' #' @param CGGP CGGP object #' @param facet How should the plots be faceted? If 1, in a row, #' if 2, in a column, if 3, wrapped around. #' @param outdims Which output dimensions should be shown. #' #' @return ggplot2 object #' @export #' @family CGGP plot functions #' #' @examples #' SG <- CGGPcreate(d=3, batchsize=100) #' f <- function(x){x[1]^1.2+x[3]^.4*sin(2*pi*x[2]^2*3) + .1*exp(3*x[3])} #' y <- apply(SG$design, 1, f) #' SG <- CGGPfit(SG, Y=y) #' CGGPplotvariogram(SG) CGGPplotvariogram <- function(CGGP, facet=1, outdims=NULL) { vdf <- NULL xl <- seq(0,1,l=101) if (is.null(outdims)) { outdims <- if (is.matrix(CGGP$Y)) {1:ncol(CGGP$Y)} else {1} } for (di in 1:CGGP$d) { for (outdim in outdims) { theta.thisiter <- if (is.matrix(CGGP$thetaMAP)) {CGGP$thetaMAP[1:CGGP$numpara + (di-1)*CGGP$numpara, outdim] } else { CGGP$thetaMAP[1:CGGP$numpara + (di-1)*CGGP$numpara] } tmp <- c(CGGP$CorrMat(c(0), xl, theta.thisiter)) tmpdf <- data.frame(x=xl, y=tmp, d=paste0("X",di), outdim=paste0("Y", outdim)) vdf <- if (is.null(vdf)) tmpdf else rbind(vdf, tmpdf) } } p <- ggplot2::ggplot(vdf, ggplot2::aes_string(x='x', y='y')) + ggplot2::geom_line() + ggplot2::ylim(c(0,1)) # p <- p + facet_grid(d ~ .) if (facet==1) { p <- p + ggplot2::facet_grid(outdim ~ d) p <- p + ggplot2::scale_x_continuous(breaks=c(0,1)) } else if (facet==2) { p <- p + ggplot2::facet_grid(d ~ outdim) } else if (facet==3) { p <- p + ggplot2::facet_wrap(d ~ outdim) } else { stop("facet is not 1, 2, or 3") } p } #' Plot theta samples #' #' @param CGGP CGGP object #' #' @return ggplot2 object #' @export #' @family CGGP plot functions #' #' @examples #' gs <- CGGPcreate(d=3, batchsize=100) #' f <- function(x){x[1]^1.2+x[3]^.4*sin(2*pi*x[2]^2*3) + .1*exp(3*x[3])} #' y <- apply(gs$design, 1, f) #' gs <- CGGPfit(gs, Y=y) #' CGGPplottheta(gs) CGGPplottheta <- function(CGGP) { # stripchart(data.frame(t(CGGP$thetaPostSamples)), xlim=c(-1,1)) # stripchart(data.frame(t(CGGP$thetaMAP)), add=T, col=2, pch=17) if (is.matrix(CGGP$thetaMAP)) { tsamp <- NULL tmap <- NULL for (i in 1:dim(CGGP$thetaPostSamples)[3]) { tsamp <- rbind(tsamp, reshape2::melt(CGGP$thetaPostSamples[,,i]), pdim=i) tmap <- rbind(tmap, data.frame(value=CGGP$thetaMAP[,i], Var1=1:nrow(CGGP$thetaMAP), pdim=i)) } } else { # single output tsamp <- reshape2::melt(CGGP$thetaPostSamples) tmap <- data.frame(value=CGGP$thetaMAP, Var1=1:length(CGGP$thetaMAP)) } p <- ggplot2::ggplot() + ggplot2::geom_point(data=tmap, mapping=ggplot2::aes_string("value", "Var1"), color="green", size=5) + ggplot2::geom_point(data=tsamp, mapping=ggplot2::aes_string("value", "Var1")) if (is.matrix(CGGP$thetaMAP)) { p <- p + ggplot2::facet_grid(. ~ pdim) } p } #' Plot negative log posterior likelihood of samples #' #' @param CGGP CGGP object #' #' @return ggplot2 object #' @export #' @family CGGP plot functions #' #' @examples #' gs <- CGGPcreate(d=3, batchsize=100) #' f <- function(x){x[1]^1.2+x[3]^.4*sin(2*pi*x[2]^2*3) + .1*exp(3*x[3])} #' y <- apply(gs$design, 1, f) #' gs <- CGGPfit(gs, Y=y) #' CGGPplotsamplesneglogpost(gs) CGGPplotsamplesneglogpost <- function(CGGP) { # Number of output parameter dimensions, one plot for each nopd <- if (is.matrix(CGGP$thetaPostSamples)) {1} else {dim(CGGP$thetaPostSamples)[3]} if (nopd==1) { neglogpost_thetaMAP <- CGGP_internal_neglogpost(CGGP$thetaMAP, CGGP, y=CGGP$y, Xs=CGGP$Xs, ys=CGGP$ys) } else { neglogpost_thetaMAP <- apply(CGGP$thetaMAP, 2, CGGP_internal_neglogpost, CGGP, y=CGGP$y, Xs=CGGP$Xs, ys=CGGP$ys) } over_dim <- if (nopd == 1) {2} else {2:3} neglogpost_samples <- apply(CGGP$thetaPostSamples, over_dim, CGGP_internal_neglogpost, CGGP=CGGP, y=CGGP$y, Xs=CGGP$Xs, ys=CGGP$ys) num_Inf <- sum(is.infinite(neglogpost_samples)) if (num_Inf > 0) { warning(paste(num_Inf, "neglogpost samples are Inf")) } nlps_melt <- reshape2::melt(neglogpost_samples) nlps_melt$Y_var2 <- paste0('Y', nlps_melt$Var2) p <- ggplot2::ggplot() + ggplot2::geom_histogram(ggplot2::aes_string(x='value'), nlps_melt, bins=30) + ggplot2::xlab("neglogpost") + ggplot2::ggtitle("neglogpost of theta samples (blue is MAP)") if (nopd > 1) { vl <- data.frame(nlp=neglogpost_thetaMAP, Y_var2=paste0('Y', 1:length(neglogpost_thetaMAP))) p <- p + ggplot2::geom_vline(data=vl, mapping=ggplot2::aes_string(xintercept="nlp"), color="blue", size=2) + ggplot2::facet_wrap(. ~ Y_var2) } else { vl <- data.frame(nlp=neglogpost_thetaMAP) p <- p + ggplot2::geom_vline(data=vl, mapping=ggplot2::aes_string(xintercept="nlp"), color="blue", size=2) } p } #' Plot CGGP block selection over time #' #' Shows the order in which blocks were selected #' for each dimension. #' Gives an idea of how the selections change over time. #' #' @param CGGP CGGP object #' @param indims Which input dimensions should be shown? #' #' @return ggplot2 object #' @export #' #' @examples #' gs <- CGGPcreate(d=3, batchsize=100) #' # All dimensions will look similar #' CGGPplotblockselection(gs) #' \donttest{ #' # You need to append with CGGPappend after fitting to see a difference #' f <- function(x){x[1]^1.2} #' y <- apply(gs$design, 1, f) #' gs <- CGGPfit(gs, Y=y) #' gs <- CGGPappend(gs, 100) #' # Now you will see higher for X1 from 100 to 200 while others remain low. #' CGGPplotblockselection(gs) #' } CGGPplotblockselection <- function(CGGP, indims) { uodf <- CGGP$uo[1:CGGP$uoCOUNT,] if (!missing(indims) && !is.null(indims)) { uodf <- uodf[,indims] } tdf2 <- reshape2::melt(data.frame(uodf, ninblock=CGGP$gridsize, ncumsum=cumsum(CGGP$gridsize), ind=1:CGGP$uoCOUNT), id.vars=c("ind", "ninblock", "ncumsum")) tdf2$Var2 <- as.integer(substr(tdf2$variable, 2, 3)) ggplot2::ggplot(data=tdf2, mapping=ggplot2::aes_string("ncumsum", "value", weight="ninblock")) + ggplot2::geom_point() + ggplot2::facet_grid(Var2 ~ .) + ggplot2::stat_smooth(color="green", method="loess", formula = y ~ x) + ggplot2::xlab("uo") + ggplot2::ylab("Block level") }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/CGGP_plot.R
#' Calculate posterior variance, faster version #' #' @param GMat Matrix #' @param dGMat Derivative of matrix #' @param cholS Cholesky factorization of S #' @param dSMat Deriv of SMat #' @param INDSN Indices, maybe #' @param numpara Number of parameters for correlation function #' @param returnlogs Should log scale be returned #' @param returnderiratio Should derivative ratio be returned? #' @param returndG Should dG be returned #' @param returndiag Should diag be returned #' @param ... Placeholder #' #' @return Variance posterior # @export #' @noRd CGGP_internal_postvarmatcalc_fromGMat <- function(GMat, dGMat,cholS,dSMat,INDSN,numpara,..., returnlogs=FALSE, returnderiratio =FALSE, returndG = FALSE,returndiag = FALSE) { # Next line was giving error with single value, so I changed it CoinvC1o = backsolve(cholS,backsolve(cholS, t(GMat[,INDSN, drop=F]), transpose = TRUE)) # backsolve1 <- backsolve(cholS,if (is.matrix(GMat[,INDSN]) && ncol(GMat[,INDSN])>1) t(GMat[,INDSN]) else GMat[,INDSN], transpose = TRUE) # CoinvC1o = backsolve(cholS,backsolve1) if(returndiag){ if(!returnlogs){ Sigma_mat = rowSums(t((CoinvC1o))*((GMat[,INDSN]))) }else{ nlSm = rowSums(t((CoinvC1o))*((GMat[,INDSN]))) Sigma_mat =log(nlSm) } np = length(Sigma_mat) }else{ if(!returnlogs){ Sigma_mat = t(CoinvC1o)%*%(t(GMat[,INDSN])) }else{ nlSm =(t(CoinvC1o))%*%(t(GMat[,INDSN])) Sigma_mat =log(nlSm) } np = dim(Sigma_mat)[1] } if(returndG){ nb = dim(GMat)[2] nc = dim(dSMat)[1] if(returndiag){ dSigma_mat = matrix(0,np,numpara) }else{ dSigma_mat = matrix(0,np,np*numpara) } for(k in 1:numpara){ dS = dSMat[,(k-1)*nc+(1:nc)] CoinvC1oE = ((as.matrix(dS))%*%t(GMat[,INDSN])) if(returndiag){ dCoinvC1o = backsolve(cholS,backsolve(cholS,CoinvC1oE, transpose = TRUE)) dCoinvC1o = dCoinvC1o + backsolve(cholS,backsolve(cholS,t(dGMat[,(k-1)*nb+INDSN]), transpose = TRUE)) if(!returnlogs && !returnderiratio){ dSigma_mat[,k] = rowSums(t(dCoinvC1o)*(GMat[,INDSN]))+rowSums(t(CoinvC1o)*(dGMat[,(k-1)*nb+INDSN])) }else if(returnderiratio){ dSigma_mat[,k] = rowSums(t(dCoinvC1o)*(GMat[,INDSN]))+rowSums(t(CoinvC1o)*(dGMat[,(k-1)*nb+INDSN]))/Sigma_mat }else{ dSigma_mat[,k] = (rowSums(t(dCoinvC1o)*(GMat[,INDSN]))+rowSums(t(CoinvC1o)*(dGMat[,(k-1)*nb+INDSN])))/nlSm } }else{ dCoinvC1_part1 = t(CoinvC1o)%*%(CoinvC1oE) dCoinvC1_part2 = t(CoinvC1o)%*%t(dGMat[,(k-1)*nb+INDSN]) dCoinvC1_part2 = dCoinvC1_part2+t(dCoinvC1_part2) if(!returnlogs && !returnderiratio){ dSigma_mat[,(k-1)*np + 1:np] =dCoinvC1_part1+dCoinvC1_part2 }else if(returnderiratio){ dSigma_mat[,(k-1)*np + 1:np] =( dCoinvC1_part1+dCoinvC1_part2)/Sigma_mat }else{ dSigma_mat[,(k-1)*np + 1:np] =( dCoinvC1_part1+dCoinvC1_part2)/nlSm } } } return(list("Sigma_mat"= Sigma_mat,"dSigma_mat" = dSigma_mat)) }else{ return(Sigma_mat) } }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/CGGP_postvarcalc.R
#' Predict with CGGP object #' #' Predict using SG with y values at xp? #' Shouldn't y values already be stored in SG? #' #' @param xp x value to predict at #' @param CGGP SG object #' @param theta Leave as NULL unless you want to use a value other than thetaMAP. #' Much slower. #' @param outdims If multiple outputs fit without PCA and with separate #' parameters, you can predict just for certain dimensions to speed it up. #' Will leave other columns in the output, but they will be wrong. #' #' @return Predicted mean values #' @export #' @family CGGP core functions #' #' @examples #' SG <- CGGPcreate(d=3, batchsize=100) #' y <- apply(SG$design, 1, function(x){x[1]+x[2]^2+rnorm(1,0,.01)}) #' SG <- CGGPfit(SG, Y=y) #' CGGPpred(SG, matrix(c(.1,.1,.1),1,3)) #' cbind(CGGPpred(SG, SG$design)$mean, y) # Should be near equal CGGPpred <- function(CGGP, xp, theta=NULL, outdims=NULL) { if (!inherits(CGGP, "CGGP")) { stop("First argument to CGGP must be an CGGP object") } # Require that you run CGGPfit first if (is.null(CGGP$supplemented)) { stop("You must run CGGPfit on CGGP object before using CGGPpredict") } if (CGGP$supplemented && (is.null(CGGP[["Y"]]) || length(CGGP$Y)==0)) { return(CGGP_internal_predwithonlysupp(CGGP=CGGP, xp=xp, theta=theta, outdims=outdims)) } # We could check for design_unevaluated, maybe give warning? # If xp has many rows, split it up over calls to CGGPpred and regroup predgroupsize <- 100 if (nrow(xp) >= predgroupsize*2) { ngroups <- floor(nrow(xp) / predgroupsize) list_preds <- lapply(1:ngroups, function(i) { inds.i <- if (i < ngroups) {1:predgroupsize + (i-1)*predgroupsize} else {((i-1)*predgroupsize+1):(nrow(xp))} CGGPpred(CGGP=CGGP, xp=xp[inds.i, , drop=FALSE], theta=theta, outdims=outdims) }) outlist <- list(mean=do.call(rbind, lapply(list_preds, function(ll) ll$mean)), var= do.call(rbind, lapply(list_preds, function(ll) ll$var )) ) if (nrow(outlist$mean)!=nrow(xp) || nrow(outlist$var)!=nrow(xp)) { stop("Error with CGGPpred predicting many points") } return(outlist) } # If theta is given (for full Bayesian prediction), need to recalculate pw if (!is.null(theta) && length(theta)!=length(CGGP$thetaMAP)) {stop("Theta is wrong length")} if (!is.null(theta) && all(theta==CGGP$thetaMAP)) { # If you give in theta=thetaMAP, set it to NULL to avoid recalculating. theta <- NULL } if (is.null(theta)) { thetaMAP <- CGGP$thetaMAP recalculate_pw <- FALSE } else { thetaMAP <- theta rm(theta) # pw <- CGGP_internal_calcpw(CGGP, CGGP$y, theta=thetaMAP) recalculate_pw <- TRUE } separateoutputparameterdimensions <- is.matrix(CGGP$thetaMAP) # nopd is numberofoutputparameterdimensions nopd <- if (separateoutputparameterdimensions) { ncol(CGGP$y) } else { 1 } if (nopd > 1) { # meanall <- matrix(NaN, nrow(xp), ncol=nopd) meanall2 <- matrix(0, nrow(xp), ncol=ncol(CGGP$Y)) # varall <- matrix(NaN, nrow(xp), ncol=ncol(CGGP$Y)) tempvarall <- matrix(0, nrow(xp), ncol=ncol(CGGP$Y)) } if (!is.null(outdims) && nopd==1) { stop("outdims can only be given when multiple outputs and separate correlation parameters") } opd_values <- if (is.null(outdims)) {1:nopd} else {outdims} for (opdlcv in opd_values) {# 1:nopd) { thetaMAP.thisloop <- if (nopd==1) thetaMAP else thetaMAP[, opdlcv] if (!recalculate_pw) { # use already calculated pw.thisloop <- if (nopd==1) CGGP$pw else CGGP$pw[,opdlcv] sigma2MAP.thisloop <- CGGP$sigma2MAP cholS.thisloop <- if (nopd==1) CGGP$cholSs else CGGP$cholSs[[opdlcv]] } else { # recalculate pw and sigma2MAP y.thisloop <- if (nopd==1) CGGP$y else CGGP$y[,opdlcv] lik_stuff <- CGGP_internal_calc_cholS_lS_sigma2_pw(CGGP=CGGP, y=y.thisloop, theta=thetaMAP.thisloop ) cholS.thisloop = lik_stuff$cholS sigma2MAP.thisloop <- lik_stuff$sigma2 pw.thisloop = lik_stuff$pw # It can be vector when there is multiple output sigma2MAP.thisloop <- as.vector(sigma2MAP.thisloop) rm(y.thisloop) } mu.thisloop <- if (nopd==1) CGGP$mu else CGGP$mu[opdlcv] # Not used for PCA, added back at end # Cp is sigma(x_0) in paper, correlation vector between design points and xp Cp = matrix(0,dim(xp)[1],CGGP$ss) GGGG = list(matrix(1,dim(xp)[1],length(CGGP$xb)),CGGP$d) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(xp[,dimlcv], CGGP$xb[1:CGGP$sizest[max(CGGP$uo[,dimlcv])]], thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara], returnlogs=TRUE) GGGG[[dimlcv]] = exp(V) Cp = Cp+V[,CGGP$designindex[,dimlcv]] } Cp = exp(Cp) ME_t = matrix(1,dim(xp)[1],1) MSE_v = list(matrix(0,dim(xp)[1],2),(CGGP$d+1)*(CGGP$maxlevel+1)) Q = max(CGGP$uo[1:CGGP$uoCOUNT,]) for (dimlcv in 1:CGGP$d) { for (levellcv in 1:max(CGGP$uo[1:CGGP$uoCOUNT,dimlcv])) { Q = max(CGGP$uo[1:CGGP$uoCOUNT,]) gg = (dimlcv-1)*Q INDSN = 1:CGGP$sizest[levellcv] INDSN = INDSN[sort(CGGP$xb[1:CGGP$sizest[levellcv]], index.return = TRUE)$ix] MSE_v[[(dimlcv)*CGGP$maxlevel+levellcv]] = CGGP_internal_postvarmatcalc_fromGMat(GGGG[[dimlcv]], c(), as.matrix( cholS.thisloop[[gg+levellcv]] ), c(), INDSN, CGGP$numpara, returndiag=TRUE) } } for (blocklcv in 1:CGGP$uoCOUNT) { if(abs(CGGP$w[blocklcv]) > 0.5){ ME_s = matrix(1,nrow=dim(xp)[1],1) for (dimlcv in 1:CGGP$d) { levelnow = CGGP$uo[blocklcv,dimlcv] ME_s = ME_s*MSE_v[[(dimlcv)*CGGP$maxlevel+levelnow]] } ME_t = ME_t-CGGP$w[blocklcv]*ME_s } } if (!CGGP$supplemented) { # Return list with mean and var predictions if(is.vector(pw.thisloop)){ if (nopd == 1) { mean = (mu.thisloop+Cp%*%pw.thisloop) var=sigma2MAP.thisloop*ME_t } # With sepparout and PCA (or not), do this if (nopd > 1) { # meanall2 <- meanall2 + outer(c(Cp%*%pw.thisloop), CGGP$M[opdlcv, ]) meanall2[,opdlcv] <- c(Cp%*%pw.thisloop) # This should be correct variance. Needs to be tested better. # Pick out the current dimension, set other values to zero tempM <- diag(nopd) #CGGP$M tempM[-opdlcv,] <- 0 tempsigma2.thisloop <- sigma2MAP.thisloop tempsigma2.thisloop[-opdlcv] <- 0 tempvar <- (as.vector(ME_t)%*%t(diag(t(tempM)%*%diag(tempsigma2.thisloop)%*%(tempM)))) } }else{ # y was a matrix if(length(sigma2MAP.thisloop)==1){ stop("When is it a matrix but sigma2MAP a scalar???") }else{ mean = (matrix(rep(mu.thisloop,each=dim(xp)[1]), ncol=ncol(CGGP$Y), byrow=FALSE) + (Cp%*%pw.thisloop)) var=as.vector(ME_t)%*%t(sigma2MAP.thisloop) } } } else { # CGGP$supplemented is TRUE if (!recalculate_pw) { pw_uppad.thisloop <- if (nopd==1) CGGP$pw_uppad else CGGP$pw_uppad[,opdlcv] supppw.thisloop <- if (nopd==1) CGGP$supppw else CGGP$supppw[,opdlcv] Sti.thisloop <- if (nopd==1) CGGP$Sti else CGGP$Sti[,,opdlcv] } else { stop("Give theta in not implemented in CGGPpred. Need to fix sigma2MAP here too!") } Cps = matrix(0,dim(xp)[1],dim(CGGP$Xs)[1]) GGGG2 = list(matrix(0,nrow=dim(xp)[1],ncol=dim(CGGP$Xs)[1]),CGGP$d) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(xp[,dimlcv], CGGP$Xs[,dimlcv], thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara], returnlogs=TRUE) Cps = Cps+V V = CGGP$CorrMat(CGGP$Xs[,dimlcv], CGGP$xb[1:CGGP$sizest[max(CGGP$uo[,dimlcv])]], thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara], returnlogs=TRUE) GGGG2[[dimlcv]] = exp(V) } Cps = exp(Cps) yhatp = Cp%*%pw_uppad.thisloop + Cps%*%supppw.thisloop MSE_ps = matrix(NaN,nrow=dim(CGGP$Xs)[1]*dim(xp)[1],ncol=(CGGP$d)*(CGGP$maxlevel)) Q = max(CGGP$uo[1:CGGP$uoCOUNT,]) for (dimlcv in 1:CGGP$d) { gg = (dimlcv-1)*Q for (levellcv in 1:max(CGGP$uo[1:CGGP$uoCOUNT,dimlcv])) { INDSN = 1:CGGP$sizest[levellcv] INDSN = INDSN[sort(CGGP$xb[1:CGGP$sizest[levellcv]],index.return = TRUE)$ix] REEALL= CGGP_internal_postvarmatcalc_fromGMat_asym(GGGG[[dimlcv]], GGGG2[[dimlcv]], as.matrix(cholS.thisloop[[gg+levellcv]]), INDSN) MSE_ps[,(dimlcv-1)*CGGP$maxlevel+levellcv] = as.vector(REEALL) } } Cps2 = as.vector(Cps) rcpp_fastmatclcr(CGGP$uo[1:CGGP$uoCOUNT,], CGGP$w[1:CGGP$uoCOUNT], MSE_ps, Cps2,CGGP$maxlevel) Cps = matrix(Cps2,ncol=dim(CGGP$Xs)[1] , byrow = FALSE) ME_adj = rowSums((Cps%*%Sti.thisloop)*Cps) ME_t = ME_t-ME_adj # Return list with mean and var predictions if(is.vector(pw.thisloop)){ if (nopd == 1) { mean = (CGGP$mu+ yhatp) if (length(CGGP$sigma2MAP)>1) {warning("If this happens, you should fix var here")} # Should this be sigma2MAP.thisloop? var=CGGP$sigma2MAP[1]*ME_t } # With sepparout and PCA (or not), do this if (nopd > 1) { # meanall2 <- meanall2 + outer(c(yhatp), CGGP$M[opdlcv,]) meanall2[,opdlcv] <- yhatp leftvar <- if (is.null(CGGP$leftover_variance)) {0} else {CGGP$leftover_variance} tempM <- diag(nopd) #CGGP$M tempM[-opdlcv,] <- 0 tempsigma2.thisloop <- sigma2MAP.thisloop tempsigma2.thisloop[-opdlcv] <- 0 tempvar <- (as.vector(ME_t)%*%t( leftvar + diag(t(tempM)%*%diag(tempsigma2.thisloop)%*%(tempM)))) } }else{ if(length(CGGP$sigma2MAP)==1){ stop("This should never happen #952570") }else{ leftvar <- if (is.null(CGGP$leftover_variance)) {0} else {CGGP$leftover_variance} mean = matrix(rep(CGGP$mu,each=dim(xp)[1]), ncol=ncol(CGGP$Y), byrow=FALSE)+ yhatp var=as.vector(ME_t)%*%t(leftvar+CGGP$sigma2MAP) } } } rm(Cp,ME_t, MSE_v, V) # Just to make sure nothing is carrying through if (nopd > 1) {tempvarall <- tempvarall + tempvar} } # If PCA values were calculated separately, need to do transformation on # both before mu is added, then add mu back # if (nopd > 1) {meanall <- sweep(sweep(meanall,2,CGGP$mu) %*% CGGP$M,2,CGGP$mu, `+`)} if (nopd > 1) {meanall2 <- sweep(meanall2, 2, CGGP$mu, `+`)} if (nopd > 1) { GP <- list(mean=meanall2, var=tempvarall) } else { GP <- list(mean=mean, var=var) } # Check for negative variances, set them all to be a tiny number GP$var <- pmax(GP$var, .Machine$double.eps) return(GP) } #' Calculate MSE prediction along a single dimension #' #' @param xp Points at which to calculate MSE #' @param xl Levels along dimension, vector??? #' @param theta Correlation parameters #' @param CorrMat Function that gives correlation matrix for vectors of 1D points. #' #' @return MSE predictions #' @export #' #' @examples #' CGGP_internal_MSEpredcalc(c(.4,.52), c(0,.25,.5,.75,1), theta=c(.1,.2), #' CorrMat=CGGP_internal_CorrMatCauchySQ) CGGP_internal_MSEpredcalc <- function(xp,xl,theta,CorrMat) { S = CorrMat(xl, xl, theta) n = length(xl) cholS = chol(S) Cp = CorrMat(xp, xl, theta) CiCp = backsolve(cholS,backsolve(cholS,t(Cp), transpose = TRUE)) MSE_val = 1 - rowSums(t(CiCp)*((Cp))) return(MSE_val) } #' Calculate posterior variance, faster version #' #' @param GMat1 Matrix 1 #' @param GMat2 Matrix 2 #' @param cholS Cholesky factorization of S #' @param INDSN Indices, maybe #' #' @return Variance posterior ## @export #' @noRd CGGP_internal_postvarmatcalc_fromGMat_asym <- function(GMat1,GMat2,cholS,INDSN) { CoinvC1o = backsolve(cholS, backsolve(cholS,t(GMat1[,INDSN]), transpose = TRUE)) Sigma_mat = (t(CoinvC1o)%*%(t(GMat2[,INDSN]))) return(Sigma_mat) }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/CGGP_pred_fs.R
#' Predict with only supplemental data #' #' @param CGGP CGGP object with supplemental data #' @param xp Matrix of points to predict at #' @param theta Correlation parameters #' @param outdims Output dimensions to predict for #' #' @return Predictions # @export #' @noRd #' #' @examples #' d <- 3 #' n <- 30 #' Xs <- matrix(runif(d*n), n, d) #' Ys <- apply(Xs, 1, function(x){x[1]/(x[3]+.2)+exp(x[3])*cos(x[2]^2)}) #' cg <- CGGPcreate(d, Xs=Xs, Ys=Ys, batchsize=0) #' xp <- matrix(runif(d*10), ncol=d) #' predict(cg, xp) CGGP_internal_predwithonlysupp <- function(CGGP, xp, theta=NULL, outdims=NULL) { if (!inherits(CGGP, "CGGP")) { stop("First argument to CGGP must be an CGGP object") } # Require that you run CGGPfit first if (is.null(CGGP$supplemented)) { stop("You must run CGGPfit on CGGP object before using CGGPpredict") } if (!CGGP$supplemented) { stop("Must be supplemented to use CGGPpred_supponly") } # We could check for design_unevaluated, maybe give warning? # If theta is given, need to recalculate pw if (!is.null(theta) && length(theta)!=length(CGGP$thetaMAP)) {stop("Theta is wrong length")} if (!is.null(theta) && all(theta==CGGP$thetaMAP)) { # If you give in theta=thetaMAP, set it to NULL to avoid recalculating. theta <- NULL } if (is.null(theta)) { thetaMAP <- CGGP$thetaMAP recalculate_pw <- FALSE } else { thetaMAP <- theta rm(theta) # pw <- CGGP_internal_calcpw(CGGP, CGGP$y, theta=thetaMAP) recalculate_pw <- TRUE } separateoutputparameterdimensions <- is.matrix(CGGP$thetaMAP) # nopd is numberofoutputparameterdimensions nopd <- if (separateoutputparameterdimensions) { ncol(CGGP$ys) } else { 1 } if (nopd > 1) { meanall2 <- matrix(0, nrow(xp), ncol=ncol(CGGP$Ys)) tempvarall <- matrix(0, nrow(xp), ncol=ncol(CGGP$Ys)) } if (!is.null(outdims) && nopd==1) { stop("outdims can only be given when multiple outputs and separate correlation parameters") } opd_values <- if (is.null(outdims)) {1:nopd} else {outdims} for (opdlcv in opd_values) {# 1:nopd) { thetaMAP.thisloop <- if (nopd==1) thetaMAP else thetaMAP[, opdlcv] if (!recalculate_pw) { # use already calculated sigma2MAP.thisloop <- CGGP$sigma2MAP supppw.thisloop <- if (nopd==1) CGGP$supppw else CGGP$supppw[,opdlcv] Sti.thisloop <- if (nopd==1) CGGP$Sti else CGGP$Sti[,,opdlcv] } else { # recalculate pw and sigma2MAP ys.thisloop <- if (nopd==1) CGGP$ys else CGGP$ys[,opdlcv] Sigma_t = matrix(1,dim(CGGP$Xs)[1],dim(CGGP$Xs)[1]) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(CGGP$Xs[,dimlcv], CGGP$Xs[,dimlcv], thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara]) Sigma_t = Sigma_t*V } Sti_chol <- chol(Sigma_t + diag(CGGP$nugget, nrow(Sigma_t), ncol(Sigma_t))) Sti.thisloop <- chol2inv(Sti_chol) supppw.thisloop <- backsolve(Sti_chol, backsolve(Sti_chol, ys.thisloop, transpose = T)) if (is.matrix(supppw.thisloop) && ncol(supppw.thisloop)==1) { supppw.thisloop <- as.vector(supppw.thisloop) } sigma2MAP.thisloop <- (t(ys.thisloop) %*% supppw.thisloop) / nrow(CGGP$Xs) if (is.matrix(sigma2MAP.thisloop)) {sigma2MAP.thisloop <- diag(sigma2MAP.thisloop)} rm(Sigma_t, V, Sti_chol, ys.thisloop) } mu.thisloop <- if (nopd==1) CGGP$mu else CGGP$mu[opdlcv] # Not used for PCA, added back at end Cps = matrix(1,dim(xp)[1],dim(CGGP$Xs)[1]) for (dimlcv in 1:CGGP$d) { # Loop over dimensions V = CGGP$CorrMat(xp[,dimlcv], CGGP$Xs[,dimlcv], thetaMAP.thisloop[(dimlcv-1)*CGGP$numpara+1:CGGP$numpara]) Cps = Cps*V } yhatp = Cps%*%supppw.thisloop # Return list with mean and var predictions if(is.vector(supppw.thisloop)){ if (nopd == 1) { mean = (CGGP$mu + yhatp) var=CGGP$sigma2MAP[1]* (1-diag(Cps %*% CGGP$Sti %*% t(Cps))) # ME_t # could return cov mat here } # With sepparout and PCA (or not), do this if (nopd > 1) { meanall2[,opdlcv] <- yhatp tempvar <- matrix(0, nrow(xp), nopd) tempvar[,opdlcv] <- CGGP$sigma2MAP[opdlcv]* (1-diag(Cps %*% CGGP$Sti[,,opdlcv] %*% t(Cps))) } }else{ # supppw is matrix, so predicting multiple columns at once if(length(CGGP$sigma2MAP)==1){ stop("This should never happen #952570") }else{ mean <- matrix(rep(CGGP$mu,each=dim(xp)[1]), ncol=ncol(CGGP$Ys), byrow=FALSE) + yhatp var <- sweep(matrix((1-diag(Cps %*% CGGP$Sti %*% t(Cps))), nrow(xp), ncol(CGGP$Ys), byrow = F), 2, CGGP$sigma2MAP, `*`) } } # rm(Cp,ME_t, MSE_v, V) # Just to make sure nothing is carrying through if (nopd > 1) {tempvarall <- tempvarall + tempvar} } # If PCA values were calculated separately, need to do transformation on both before mu is added, then add mu back if (nopd > 1) {meanall2 <- sweep(meanall2, 2, CGGP$mu, `+`)} if (nopd > 1) { GP <- list(mean=meanall2, var=tempvarall) } else { GP <- list(mean=mean, var=var) } # Check for negative variances, set them all to be a tiny number GP$var <- pmax(GP$var, .Machine$double.eps) return(GP) }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/CGGP_predwithonlysupp.R
#' Set correlation function of CGGP object #' #' @param CGGP CGGP object #' @param corr Correlation function #' #' @return CGGP object #' @export #' #' @examples #' obj <- CGGPcreate(3, 20, corr="matern52") #' CGGP_internal_set_corr(obj, "gaussian") CGGP_internal_set_corr <- function(CGGP, corr) { if (is.function(corr)) { CGGP$CorrMat <- corr CGGP$CorrName <- "UserDefined" } else if (tolower(corr) %in% c("cauchysqt")) { CGGP$CorrMat <- CGGP_internal_CorrMatCauchySQT CGGP$CorrName <- "CauchySQT" } else if (tolower(corr) %in% c("cauchysq")) { CGGP$CorrMat <- CGGP_internal_CorrMatCauchySQ CGGP$CorrName <- "CauchySQ" } else if (tolower(corr) %in% c("cauchy")) { CGGP$CorrMat <- CGGP_internal_CorrMatCauchy CGGP$CorrName <- "Cauchy" } else if (tolower(corr) %in% c("gaussian", "gauss", "sqexp")) { CGGP$CorrMat <- CGGP_internal_CorrMatGaussian CGGP$CorrName <- "Gaussian" } else if (tolower(corr) %in% c("powerexp", "pe", "powerexponential")) { CGGP$CorrMat <- CGGP_internal_CorrMatPowerExp CGGP$CorrName <- "PowerExponential" } else if (tolower(corr) %in% c("matern32", "m32", "m3")) { CGGP$CorrMat <- CGGP_internal_CorrMatMatern32 CGGP$CorrName <- "Matern32" } else if (tolower(corr) %in% c("matern52", "m52", "m5")) { CGGP$CorrMat <- CGGP_internal_CorrMatMatern52 CGGP$CorrName <- "Matern52" } else if (tolower(corr) %in% c("wendland0", "w0", "wend0", "triangle", "triangular", "tri", "triang")) { CGGP$CorrMat <- CGGP_internal_CorrMatWendland0 CGGP$CorrName <- "Wendland0" } else if (tolower(corr) %in% c("wendland1", "w1", "wend1")) { CGGP$CorrMat <- CGGP_internal_CorrMatWendland1 CGGP$CorrName <- "Wendland1" } else if (tolower(corr) %in% c("wendland2", "w2", "wend2")) { CGGP$CorrMat <- CGGP_internal_CorrMatWendland2 CGGP$CorrName <- "Wendland2" } else { stop(paste0("corr given to CGGPcreate should be one of CauchySQT, CauchySQ,", " Cauchy, Gaussian, PowerExponential, Matern32, or Matern52.\n", "Given value was ", corr, ".")) } # Fix related parameters stored with CGGP CGGP$numpara <- CGGP$CorrMat(return_numpara=TRUE) CGGP$thetaMAP <- rep(0,CGGP$d*CGGP$numpara) CGGP$thetaPostSamples <- matrix(2*rbeta(CGGP$d*CGGP$numpara*CGGP$numPostSamples, 0.5, 0.5)-1, ncol=CGGP$numPostSamples ) CGGP } #' Add more rows to CGGP object #' #' After a lot of blocks have been added, the storage #' #' @param CGGP #' @param numrowstoadd #' #' @return CGGP object ## @export #' @noRd CGGP_internal_addrows <- function(CGGP, numrowstoadd=20) { CGGP$uo <- rbind(CGGP$uo, matrix(0,numrowstoadd,ncol(CGGP$uo))) CGGP$ML <- nrow(CGGP$uo) # Need to get everything else upsized too CGGP$po = rbind(CGGP$po, matrix(0, nrow = 4 * numrowstoadd, ncol = ncol(CGGP$po))) #proposed levels tracker CGGP$pila = rbind(CGGP$pila, matrix(0, nrow = numrowstoadd, ncol=ncol(CGGP$pila))) #proposed immediate level ancestors CGGP$pala = rbind(CGGP$pala, matrix(0, nrow = numrowstoadd, ncol=ncol(CGGP$pala))) #proposedal all level ancestors CGGP$uala = rbind(CGGP$uala, matrix(0, nrow = numrowstoadd, ncol=ncol(CGGP$uala))) #used all level ancestors CGGP$pilaCOUNT = c(CGGP$pilaCOUNT, rep(0, numrowstoadd)) #count of number of pila CGGP$palaCOUNT = c(CGGP$palaCOUNT, rep(0, numrowstoadd)) #count of number of pala CGGP$ualaCOUNT = c(CGGP$ualaCOUNT, rep(0, numrowstoadd)) #count of number of uala CGGP$pogsize = c(CGGP$pogsize, rep(0, 4 * numrowstoadd)) CGGP$w = c(CGGP$w, rep(0, numrowstoadd)) CGGP } CGGP_internal_getdesignfromCGGP <- function(CGGP) { CGGP$gridsizes = matrix(CGGP$sizes[CGGP$uo[1:CGGP$uoCOUNT, ]], CGGP$uoCOUNT, CGGP$d) CGGP$gridsizest = matrix(CGGP$sizest[CGGP$uo[1:CGGP$uoCOUNT, ]], CGGP$uoCOUNT, CGGP$d) CGGP$gridsize = apply(CGGP$gridsizes, 1, prod) CGGP$gridsizet = apply(CGGP$gridsizest, 1, prod) CGGP$di = matrix(0, nrow = CGGP$uoCOUNT, ncol = max(CGGP$gridsize)) CGGP$dit = matrix(0, nrow = CGGP$uoCOUNT, ncol = sum((CGGP$gridsize))) CGGP$design = matrix(0, nrow = sum(CGGP$gridsize), ncol = CGGP$d) CGGP$designindex = matrix(0, nrow = sum(CGGP$gridsize), ncol = CGGP$d) tv = 0 for (blocklcv in 1:CGGP$uoCOUNT) { CGGP$di[blocklcv, 1:CGGP$gridsize[blocklcv]] = (tv + 1):(tv + CGGP$gridsize[blocklcv]) for (dimlcv in 1:CGGP$d) { levelnow = CGGP$uo[blocklcv, dimlcv] if (levelnow < 1.5) { CGGP$design[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(CGGP$xb[1], CGGP$gridsize[blocklcv]) CGGP$designindex[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(CGGP$xindex[1], CGGP$gridsize[blocklcv]) } else{ x0 = CGGP$xb[(CGGP$sizest[levelnow - 1] + 1):CGGP$sizest[levelnow]] xi0 = CGGP$xindex[(CGGP$sizest[levelnow - 1] + 1):CGGP$sizest[levelnow]] if (dimlcv < 1.5) { CGGP$design[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(x0, "each" = CGGP$gridsize[blocklcv] / CGGP$gridsizes[blocklcv, dimlcv]) CGGP$designindex[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(xi0, "each" = CGGP$gridsize[blocklcv] / CGGP$gridsizes[blocklcv, dimlcv]) CGGP$blockassign[(tv + 1):(tv + CGGP$gridsize[blocklcv])] <- blocklcv } if (dimlcv > (CGGP$d - 0.5)) { CGGP$design[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(x0, CGGP$gridsize[blocklcv] / CGGP$gridsizes[blocklcv, dimlcv]) CGGP$designindex[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(xi0, CGGP$gridsize[blocklcv] / CGGP$gridsizes[blocklcv, dimlcv]) CGGP$blockassign[(tv + 1):(tv + CGGP$gridsize[blocklcv])] <- blocklcv } if (dimlcv < (CGGP$d - 0.5) && dimlcv > 1.5) { CGGP$design[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(rep(x0, each = prod(CGGP$gridsizes[blocklcv, (dimlcv + 1):CGGP$d])), prod(CGGP$gridsizes[blocklcv, 1:(dimlcv - 1)])) CGGP$designindex[(tv + 1):(tv + CGGP$gridsize[blocklcv]), dimlcv] = rep(rep(xi0, each = prod(CGGP$gridsizes[blocklcv, (dimlcv + 1):CGGP$d])), prod(CGGP$gridsizes[blocklcv, 1:(dimlcv - 1)])) CGGP$blockassign[(tv + 1):(tv + CGGP$gridsize[blocklcv])] <- blocklcv } } } tvv = 0 if (blocklcv > 1.5) { for (ances in CGGP$uala[blocklcv, 1:CGGP$ualaCOUNT[blocklcv]]) { CGGP$dit[blocklcv, (tvv + 1):(tvv + CGGP$gridsize[ances])] = CGGP$di[ances, 1:CGGP$gridsize[ances]] tvv = tvv + CGGP$gridsize[ances] } CGGP$dit[blocklcv, (tvv + 1):(tvv + CGGP$gridsize[blocklcv])] = CGGP$di[blocklcv, 1:CGGP$gridsize[blocklcv]] Xset = CGGP$design[CGGP$dit[blocklcv, 1:CGGP$gridsizet[blocklcv]], ] reorder = do.call(order, lapply(1:NCOL(Xset), function(kvt) Xset[, kvt])) CGGP$dit[blocklcv, 1:CGGP$gridsizet[blocklcv]] = CGGP$dit[blocklcv, reorder] } else{ CGGP$dit[blocklcv, 1:CGGP$gridsize[blocklcv]] = CGGP$di[blocklcv, 1:CGGP$gridsize[blocklcv]] } tv = tv + CGGP$gridsize[blocklcv] } CGGP }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/CGGP_sharedfunctions.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' rcpp_kronDBS #' #' @param A Vector #' @param B Vector #' @param p Vector #' @return kronDBS calculation #' @export #' @import Rcpp rcpp_kronDBS <- function(A, B, p) { invisible(.Call('_CGGP_rcpp_kronDBS', PACKAGE = 'CGGP', A, B, p)) } #' rcpp_kronDBS #' #' @param A Vector #' @param dA Vector #' @param B Vector #' @param p Vector #' @return kronDBS calculation #' @export #' @examples #' rcpp_gkronDBS(c(1,1), c(0,0), c(.75), c(1,1)) rcpp_gkronDBS <- function(A, dA, B, p) { .Call('_CGGP_rcpp_gkronDBS', PACKAGE = 'CGGP', A, dA, B, p) } #' rcpp_fastmatclcr #' #' @param I Matrix #' @param w vector #' @param MSEmat Matrix #' @param S Vector #' @param maxlevel Integer #' @return Nothing, void #' @export rcpp_fastmatclcr <- function(I, w, MSEmat, S, maxlevel) { invisible(.Call('_CGGP_rcpp_fastmatclcr', PACKAGE = 'CGGP', I, w, MSEmat, S, maxlevel)) } #' rcpp_fastmatclcranddclcr #' #' @param I Matrix #' @param w vector #' @param MSEmat Matrix #' @param dMSEmat Matrix #' @param S Vector #' @param dS Matrix #' @param maxlevel Integer #' @param numpara Integer #' @return Nothing, void #' @export rcpp_fastmatclcranddclcr <- function(I, w, MSEmat, dMSEmat, S, dS, maxlevel, numpara) { invisible(.Call('_CGGP_rcpp_fastmatclcranddclcr', PACKAGE = 'CGGP', I, w, MSEmat, dMSEmat, S, dS, maxlevel, numpara)) }
/scratch/gouwar.j/cran-all/cranData/CGGP/R/RcppExports.R
## ----include = FALSE---------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 7 ) ## ----setup-------------------------------------------------------------------- ## ----cggpcreate--------------------------------------------------------------- library(CGGP) # Create the initial design d <- 6 mod <- CGGPcreate(d=d, batchsize=100) mod ## ----------------------------------------------------------------------------- str(mod$design) ## ----------------------------------------------------------------------------- f <- function(x){x[1]*x[2] + x[3]^2 + (x[2]+.5)*sin(2*pi*x[4])} Y <- apply(mod$design, 1, f) ## ----cggpfit------------------------------------------------------------------ mod <- CGGPfit(mod, Y) mod ## ----cggppred----------------------------------------------------------------- xp <- matrix(runif(d*100), ncol=d) str(CGGPpred(CGGP=mod, xp=xp)) ## ----cggpappend--------------------------------------------------------------- mod <- CGGPappend(mod, 200, "MAP") mod ## ----updatefit---------------------------------------------------------------- Ynew <- apply(mod$design_unevaluated, 1, f) mod <- CGGPfit(mod, Ynew=Ynew) mod ## ----plotblocks--------------------------------------------------------------- CGGPplotblocks(mod) ## ----plothist----------------------------------------------------------------- CGGPplothist(mod) ## ----plotcorr----------------------------------------------------------------- CGGPplotcorr(mod) ## ----plotslice---------------------------------------------------------------- CGGPplotslice(mod)
/scratch/gouwar.j/cran-all/cranData/CGGP/inst/doc/CGGP.R
--- title: "An Introduction to the CGGP Package" author: "Collin Erickson" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{CGGP} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 7 ) ``` ```{r setup} ``` ## Introduction The R package `CGGP` implements the adaptive composite grid using Gaussian process models presented in a forthcoming publication by Matthew Plumlee, Collin Erickson, Bruce Ankenman, et al. It provides an algorithm for running sequential computer experiments with thousands of data points. The composite grid structure imposes strict requirements on which points should be evaluated. The inputs chosen to be evaluated are specified by the algorithm. This does not work with preexisting data sets, it is not a regression technique. This only works in sequential experimental design scenarios: you start with no data, and then decide which points to evaluate in batches according to the algorithm. When to use it: * You have not started collecting data yet, or only have a small data set * You will collect 5,000 to 100,000 data points * You will collect data iteratively * Your simulation has four to twenty input dimensions * The simulation output is deterministic (evaluating the same input twice always returns the same value) Why you should use it: * Gaussian process models, a common model choice for modeling computer experiments, have computation issues for more than a thousand data points * Accuracy is much better than popular machine learning algorithms, which are better suited for noisy data ## How to use `CGGP` You should have a deterministic function that takes $d$-dimensional input that you can evaluate for any point in the unit cube $[0,1]^d$. The points generated by the algorithm will be given to you to evaluate, then you will return the function output for each input point. The model will be fit to this data and you will be able to use it to make predictions or evaluate additional points. To begin, use `CGGPcreate` to create a `CGGP` object. You must tell it the number of input dimensions $d$ and the number of points for the first batch. For example, if $d=6$ and you want to begin will 100 points, you can create a model `mod` with the following code. ```{r cggpcreate} library(CGGP) # Create the initial design d <- 6 mod <- CGGPcreate(d=d, batchsize=100) mod ``` Now `mod` will contain all the relevant information for the composite grid design and model. Most importantly, it has the initial set of points that must be evaluated. These are accessed as `mod$design`. ```{r} str(mod$design) ``` Now you must pass these points to your function to be evaluated. ```{r} f <- function(x){x[1]*x[2] + x[3]^2 + (x[2]+.5)*sin(2*pi*x[4])} Y <- apply(mod$design, 1, f) ``` Once you have the data for each row of `mod$design`, you can now fit the model using `CGGPfit`. ```{r cggpfit} mod <- CGGPfit(mod, Y) mod ``` Now that you have a fitted model, you can either use it to make predictions at points, or augment the design with additional runs. To use the model to predict the output at new points, use the function `CGGPpred` or `predict`. Let`xp` be the matrix whose rows are the points that you want to make predictions at. Then the following will return a list with the mean and predictive variance for each row of `xp`. ```{r cggppred} xp <- matrix(runif(d*100), ncol=d) str(CGGPpred(CGGP=mod, xp=xp)) ``` To add points to the design, use the function `CGGPappend`, and include how many points you want to add. This is the maximum number; it may append a smaller number of points if it is not able to reach the specified number. To add 200 points: ```{r cggpappend} mod <- CGGPappend(mod, 200, "MAP") mod ``` You would choose to add points to the design in multiple steps, as opposed to all in a single step, so that the fitted model can be used to efficiently select the points to augment the design. Once you have appended new points, you need to evaluate them and fit the model again. You can access the new design points that need to be evaluated using `mod$design_unevaluated`. ```{r updatefit} Ynew <- apply(mod$design_unevaluated, 1, f) mod <- CGGPfit(mod, Ynew=Ynew) mod ``` ### Plotting CGGP objects It is very difficult to comprehend what designs in high dimensions look like, but we would like to be able to have visuals and diagnostics to make sure the design is sensible and to try to get an idea of what it is doing. We have implemented a few plotting functions in the CGGP package that aim to provide a visualization of the design and its parameters. The function `CGGPplotblocks` can be used to view the blocks (indexes) when projected down to each pair of dimensions. Dimensions that are more interesting should have a wider variety in values. ```{r plotblocks} CGGPplotblocks(mod) ``` Histograms for the values of each index for each dimension are given by `CGGPplothist`. Dimensions with more spread to the right can be thought of as having been allocated more simulation effort. ```{r plothist} CGGPplothist(mod) ``` The correlation parameters for each input dimension can also provide useful information about how active each dimension is. `CGGPplotcorr` shows Gaussian process (GP) samples using the correlation parameters for each input dimension. The lines shown do not depict each dimension, but give an idea of what GP models with the same correlation parameters look like. ```{r plotcorr} CGGPplotcorr(mod) ``` The function `CGGPplotslice` shows how the output changes when a single input is varied across its range from 0 to 1 while holding all the other inputs at a constant value. This plot may also be referred to as a slice plot. By default the other input values are held constant at 0.5, but this can be changed with a parameter. The dots on the plot are included for points that were measured and used to fit the model. These dots generally only appear when the other dimensions are held at 0.5. ```{r plotslice} CGGPplotslice(mod) ```
/scratch/gouwar.j/cran-all/cranData/CGGP/inst/doc/CGGP.Rmd
--- title: "An Introduction to the CGGP Package" author: "Collin Erickson" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{CGGP} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 7 ) ``` ```{r setup} ``` ## Introduction The R package `CGGP` implements the adaptive composite grid using Gaussian process models presented in a forthcoming publication by Matthew Plumlee, Collin Erickson, Bruce Ankenman, et al. It provides an algorithm for running sequential computer experiments with thousands of data points. The composite grid structure imposes strict requirements on which points should be evaluated. The inputs chosen to be evaluated are specified by the algorithm. This does not work with preexisting data sets, it is not a regression technique. This only works in sequential experimental design scenarios: you start with no data, and then decide which points to evaluate in batches according to the algorithm. When to use it: * You have not started collecting data yet, or only have a small data set * You will collect 5,000 to 100,000 data points * You will collect data iteratively * Your simulation has four to twenty input dimensions * The simulation output is deterministic (evaluating the same input twice always returns the same value) Why you should use it: * Gaussian process models, a common model choice for modeling computer experiments, have computation issues for more than a thousand data points * Accuracy is much better than popular machine learning algorithms, which are better suited for noisy data ## How to use `CGGP` You should have a deterministic function that takes $d$-dimensional input that you can evaluate for any point in the unit cube $[0,1]^d$. The points generated by the algorithm will be given to you to evaluate, then you will return the function output for each input point. The model will be fit to this data and you will be able to use it to make predictions or evaluate additional points. To begin, use `CGGPcreate` to create a `CGGP` object. You must tell it the number of input dimensions $d$ and the number of points for the first batch. For example, if $d=6$ and you want to begin will 100 points, you can create a model `mod` with the following code. ```{r cggpcreate} library(CGGP) # Create the initial design d <- 6 mod <- CGGPcreate(d=d, batchsize=100) mod ``` Now `mod` will contain all the relevant information for the composite grid design and model. Most importantly, it has the initial set of points that must be evaluated. These are accessed as `mod$design`. ```{r} str(mod$design) ``` Now you must pass these points to your function to be evaluated. ```{r} f <- function(x){x[1]*x[2] + x[3]^2 + (x[2]+.5)*sin(2*pi*x[4])} Y <- apply(mod$design, 1, f) ``` Once you have the data for each row of `mod$design`, you can now fit the model using `CGGPfit`. ```{r cggpfit} mod <- CGGPfit(mod, Y) mod ``` Now that you have a fitted model, you can either use it to make predictions at points, or augment the design with additional runs. To use the model to predict the output at new points, use the function `CGGPpred` or `predict`. Let`xp` be the matrix whose rows are the points that you want to make predictions at. Then the following will return a list with the mean and predictive variance for each row of `xp`. ```{r cggppred} xp <- matrix(runif(d*100), ncol=d) str(CGGPpred(CGGP=mod, xp=xp)) ``` To add points to the design, use the function `CGGPappend`, and include how many points you want to add. This is the maximum number; it may append a smaller number of points if it is not able to reach the specified number. To add 200 points: ```{r cggpappend} mod <- CGGPappend(mod, 200, "MAP") mod ``` You would choose to add points to the design in multiple steps, as opposed to all in a single step, so that the fitted model can be used to efficiently select the points to augment the design. Once you have appended new points, you need to evaluate them and fit the model again. You can access the new design points that need to be evaluated using `mod$design_unevaluated`. ```{r updatefit} Ynew <- apply(mod$design_unevaluated, 1, f) mod <- CGGPfit(mod, Ynew=Ynew) mod ``` ### Plotting CGGP objects It is very difficult to comprehend what designs in high dimensions look like, but we would like to be able to have visuals and diagnostics to make sure the design is sensible and to try to get an idea of what it is doing. We have implemented a few plotting functions in the CGGP package that aim to provide a visualization of the design and its parameters. The function `CGGPplotblocks` can be used to view the blocks (indexes) when projected down to each pair of dimensions. Dimensions that are more interesting should have a wider variety in values. ```{r plotblocks} CGGPplotblocks(mod) ``` Histograms for the values of each index for each dimension are given by `CGGPplothist`. Dimensions with more spread to the right can be thought of as having been allocated more simulation effort. ```{r plothist} CGGPplothist(mod) ``` The correlation parameters for each input dimension can also provide useful information about how active each dimension is. `CGGPplotcorr` shows Gaussian process (GP) samples using the correlation parameters for each input dimension. The lines shown do not depict each dimension, but give an idea of what GP models with the same correlation parameters look like. ```{r plotcorr} CGGPplotcorr(mod) ``` The function `CGGPplotslice` shows how the output changes when a single input is varied across its range from 0 to 1 while holding all the other inputs at a constant value. This plot may also be referred to as a slice plot. By default the other input values are held constant at 0.5, but this can be changed with a parameter. The dots on the plot are included for points that were measured and used to fit the model. These dots generally only appear when the other dimensions are held at 0.5. ```{r plotslice} CGGPplotslice(mod) ```
/scratch/gouwar.j/cran-all/cranData/CGGP/vignettes/CGGP.Rmd
CONGA.fn <- function(y, Interval = 5, n=2) { #*************************************************************************** # Function to calculate the continuous overlapping net glycemic action (CONGA). # CONGA: # For each observation after the first n hours of observations, the difference # between the current observation and the observation n hours previous was calculated. # CONGAn is defined as the standard deviation of the differences. # Input # y: measured response, must be evenly spaced in measured time # Interval: number of minutes between two consecutive time points # n: the length of a segment in CONGA # Output # a value of CONGA # Author: Xiaohua Douglas Zhang, Dandan Wang # Date: 2017-12-12 #**************************************************************************** Npoint.segment <- 60/Interval*n N <- length(y)-Npoint.segment diff.vec <- rep(NA, N) for( i in 1:N ) { diff.vec[i] <- y[i+Npoint.segment] - y[i] } CONGA <- sd( diff.vec, na.rm=TRUE) return(CONGA) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/CONGA.fn.R
MODD.fn <- function(y, Interval = 5) { #*************************************************************************** # Function to calculate the mean of daily differences (MODD). # MODD: # The absolute value of the difference between glucose values taken # on two consecutive days at the same time was calculated; the MODD is # the mean of these differences. # Input # y: measured response, must be evenly spaced in measured time # Interval: number of minutes between two consecutive time points # Output # a value of MODD # Author: Xiaohua Douglas Zhang # Date: 2017-12-12 #**************************************************************************** Nsegment <- floor(length(y)*Interval/24) Npoint <- 24/Interval if( Nsegment < 2) { MODD <- NA warning("To be able to calculate MODD, the number of full days must be at least 2!") } else { diff.mat <- matrix( NA, nrow=Nsegment-1, ncol= Npoint) for( i in 1:(Nsegment-1) ) { diff.mat[i, ] <- y[i*Npoint+1:Npoint] - y[(i-1)*Npoint+1:Npoint] } MODD <- mean( abs(as.vector(diff.mat)), na.rm=TRUE ) } return( MODD ) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/MODD.fn.R
MSEbyC.fn <- function(x, scaleMax=10, scaleStep=1, mMin=2, mMax=2, mStep=1, rMin=0.15, rMax=0.15, I=400000) { # ********************************************************************************** # Function to call and run a C program to calculate multiscale entropy (MSE) # of an equally spaced time series. # # ARGUMENTS # x: A numeric vector, with data for a regularly spaced time series. # No missing value is allowed because the C program is not set up to # handle missing value. # scaleMax: maximal value of scale factors for coarse graining in the MSE algorithm. # The scale factors are a sequence from 1 to a value no more than 'scaleMax' # with equal space 'scaleStep'. Scale factors are positive integers that specify # bin size for coarse graining: the number of consecutive observations # in 'x' that form a bin and are averaged in the first step of the algorithm. # scaleStep: see 'scaleMax' above. # mMin: A sequence from 'mMin' to 'mMax' with equal space of 'mStep' that defines # the vector of positive integers that give the window size for the entropy # calculations in the second step of the algorithm: the number of # consecutive _bins_ over which similarity between subsequences is # of interest. Typical values in the sequence are 1, 2, or 3. # mMax and mStep: See 'Min' above # rMin and rMax: A sequence from 'rMin' to 'rMax' with equal space of 0.05 that defines # coefficients for similarity thresholds. Typical values in the sequence are 0.15, 0.2. # r*sd(x) must be in the same units as 'x'. Averages in two bins are # defined to be similar if they differ by 'r*sd(x)' or less. # I: the maximal number of points to be used for calculating MSE # VALUE # A data frame with with one row for each combination of 'Scale', 'm' and 'rSD'. # Columns are "Scale", "m", "rSD", and "SampEn" (the calculated sample entropy). # The data frame will also have an attribute "SD", the standard deviation # of 'x'. rSD = r*sd(x) # VERSION # V1: X.H.D. Zhang, July 3, 2017 #******************************************************************************************* if ( anyNA(x) ) stop("'NA' values in 'x' are not allowed") N <- length(x) if ( scaleMax > N/10 ) stop( "'Scale' is too large compared to data length" ) # Temporary files for input and output for running a C program tempin <- tempfile("tempin", tmpdir=getwd(), fileext=".txt") tempout <- tempfile("tempout", tmpdir=getwd(), fileext=".txt") write(x, file=tempin, ncolumns=1, sep="\t") on.exit(unlink(tempin)) # only for test # mMin <- 0 options(scipen=999) # Construct command line arguments for running the C program. Args <- paste("-n", scaleMax, "-a", scaleStep, "-b", mStep, "-m", mMin, "-M", mMax, "-r", rMin, "-R", rMax, "-I", I) #Command <- paste0(cFolder, "/", cmdCore, ".e","xe") cmd <- paste("MSE.exe", Args, "-z", tempin, "-Z", tempout) on.exit(unlink(tempout), add=TRUE) #shell(cmd, wait=TRUE, intern=FALSE, invisible=TRUE) # Call the C function 'Mse' to calculate sample entropy .C(C_Mse, cmd) # Read calculated sample entropy back into R Text <- readLines(tempout) Text <- Text[-(1:4)] # exclude 4 header lines Text <- Text[Text != ""] # exclude empty line blockStarts <- grep("^m =", Text) # identify block start line "m = , r = " blockEnds <- c(tail(blockStarts, -1) - 1, length(Text)) result.lst <- vector("list", length(blockStarts)) for (i in seq_along(blockStarts)) { blockLine1 <- Text[ blockStarts[i] ] mr.vec <- eval(parse(text=paste0("c(", blockLine1, ")"))) con <- textConnection(Text[(blockStarts[i]+1):(blockEnds[i])]) mseBlock.df <- read.table(con, header=FALSE, sep="\t", row.names=NULL, col.names=c("Scale", "SampleEntropy", "endNA"), colClasses="numeric", comment.char="") mseBlock.df$endNA <- NULL # remove the last NA column generated by trailing "\t" in each line close(con) result.lst[[i]] <- data.frame("m"=rep(mr.vec["m"], nrow(mseBlock.df)), "r"=rep(mr.vec["r"], nrow(mseBlock.df)), mseBlock.df) } # Combine results in all block into a single data frame. result.df <- do.call("rbind", result.lst) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/MSEbyC.fn.R
MSEplot.fn <- function(Scale, MSE, Name, responseName=NA, timeUnit="", byGroup=TRUE, MSEsd=NA, N=NA, stdError=TRUE, xRange=NA, yRange=NA, las=2, col=NA, pch=NA, Position="topleft", cex.legend=0.75, main="") { ################################################################################################ # function to plot the mean and standard error or standard deviation of multiscale entropy by group #*********************************************************************************************** # Input # Scale: a vector for scale # MSE: matrix for entropy if byGroup=FALSE, and otherwise for average entropy value in a group # at a scale. In the matrix, the row is for scale and column for individuals or groups. # Name: vector of names for groups # responseName: name to represent the response to be analyzed, such as 'glucose' # timeUnit: the time unit for scale. # byGroup: If byGroup = TRUE, multiscale entropy is plotted by groups; otherwise, by individuals # MSEsd: matrix for standard deviation of entropy value in a group at a scale # N: matrix for number of subjects in a group at a scale # stdError: if it is true, the length of a vertical bar represent 2*standard error; # otherwise, the length of a vertical bar represent 2*standard deviation # xRange: range for the x-axis # yRange: range for the y-axis # las: las for the y-axis # col: vector for the colors to indicate groups or individuals # pch: vector for the point types to indicate groups or individuals # Position: position for the legend # cex.legend: cex for the legend # main: main title for title() # Output # a figure for plotting entropy vs. scale # Author: Xiaohua Douglas Zhang # Date: 2017-06-30 #*********************************************************************************************** nScale <- length(Scale) K <- dim(MSE)[2] if( is.na(xRange[1]) ) xRange <- range( Scale ) if( is.na(col[1]) ) col <- 1:K if( is.na(pch[1]) ) pch <- 1:K if( is.na(yRange[1]) ) { yRange <- switch(byGroup+1, range( MSE, na.rm=TRUE ), switch(stdError+1, range( c(range(MSE+MSEsd, na.rm=TRUE), range(MSE-MSEsd, na.rm=TRUE)) ), range( c(range(MSE+MSEsd/sqrt(N), na.rm=TRUE), range(MSE-MSEsd/sqrt(N), na.rm=TRUE)) ) ) ) } plot( xRange, yRange, type="n", axes=FALSE, xlab=paste0("Scale factor in ", timeUnit), ylab= paste0("Sample entropy of ", responseName) ) axis(1, at=Scale, labels=Scale); axis(2, las=las); box() for( i in 1:K ) { points( Scale, MSE[,i], col=col[i], pch=pch[i] ) lines( Scale, MSE[,i], col=col[i] ) if( byGroup ) { #draw error bar if byGroup = TRUE x.vec <- Scale if( stdError ) { y1.vec <- MSE[,i]-MSEsd[,i]/sqrt(N[,i]) y2.vec <- MSE[,i]+MSEsd[,i]/sqrt(N[,i]) } else { y1.vec <- MSE[,i]-MSEsd[,i] y2.vec <- MSE[,i]+MSEsd[,i] } segments(x.vec, y1.vec, x.vec, y2.vec, col=col[i]) } } legend(Position, legend=Name, col=col, cex=cex.legend, lty=1, pch=pch) title(main=main) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/MSEplot.fn.R
antennaPlot.fn <- function(Mean, SSMD, Name, CIlower, CIupper, xRange=NA, yRange=NA, col=1:length(Mean), pch=1:length(Mean), cex=1, Position="topleft", main="") { ######################################################################################### # function to draw an antenna plot #**************************************************************************************** # Input: # Mean: vector for mean difference in a comparison # SSMD: vector for ssmd in a comparison # Name: vector for name of pairs in a comparison # CIlower: vector for the lower bound of confidence interval # CIupper: vector for the upper bound of confidence interval # col: vector of colors for pairs in a comparison # pch: vector of point types for pairs in a comparison # main: main for title() # Position: position for the legend # Output: # an antenna plot # Author: Xiaohua Douglas Zhang # Date: 2017-06-29 #**************************************************************************************** if( is.na(xRange[1]) ) xRange <- range( c( range( CIlower, na.rm=TRUE), 0, range( CIupper, na.rm=TRUE) ) ) if( is.na(yRange[1]) ) yRange <- range( c(0, SSMD), na.rm=TRUE ) plot( xRange, yRange, type="n", axes=FALSE, xlab="Mean of difference and its confidence interval", ylab= "SSMD" ) axis(1); axis(2, las=2); box() lines( rep(0, 2), yRange, col="grey", lty=2 ) lines( xRange, rep(0, 2), col="grey", lty=2 ) N <- length(Mean) for(i in 1:N) { points( Mean[i], SSMD[i], col=col[i], pch=pch[i] ) lines( c(CIlower[i], CIupper[i]), rep(SSMD[i], 2), col=col[i] ) } COEF <- lm( SSMD ~ Mean - 1, na.action="na.exclude")$coef YY <- range(SSMD, na.rm=T) lines( c(0,YY/COEF), c(0, YY) ) legend(Position, legend=Name, col=col, pch=pch, cex=cex, lty=1) title(main=main) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/antennaPlot.fn.R
boxplotCGM.fn <- function(dataFolder, dataFiles, idxNA=NA, responseName, sensorIDs, columnNames=NULL, yRange, skip=0, header=TRUE, comment.char="", sep=",", cex.axis1=0.75) { ######################################################################################### # function to draw an antenna plot #**************************************************************************************** # Input: # dataFolder: name for the folder for holding data # dataFiles: name of the data file to be read in R # idxNA: symbol to represent a missing value, such as NA # responseName: name to represent the response to be analyzed, such as 'glucose' # sensorIDs: names of sensors or subjects # columnNames: names of columns of the data after reading in R # rRange: range of y-axis to be drawn in the boxplot # skip: number of lines to be skipped in each data file when the data is read in R # header, comment.char, sep: the same meaning as in read.table() # cex.axis1: cex for the x-axis # Output: # a box plot for the data by each sensor or subject # Author: Xiaohua Douglas Zhang # Date: 2017-06-29 #**************************************************************************************** nFile <- length(dataFiles) plot( c(1,nFile), yRange, xlab="", ylab=responseName, type="n", axes=FALSE) axis(2); box() axis(1, at=1:nFile, labels=sensorIDs, las=2, cex.axis=cex.axis1) for( iFile in 1:nFile ) { print(paste(iFile, "th file") ) data.df0 <- read.table(paste(dataFolder, dataFiles[iFile], sep="/"), skip=skip, header=header, comment.char=comment.char, sep=sep) if( !header ) { data.df0 <- data.df0[, 1:length(columnNames)] dimnames(data.df0)[[2]] <- columnNames } if( !is.na(idxNA) ) data.df0[ data.df0[, responseName]==idxNA, responseName] <- NA Y <- data.df0[, responseName] boxplot( Y, at=iFile, add=TRUE ) } }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/boxplotCGM.fn.R
equalInterval.fn <- function(x, y, Interval = NA, minGap = 4*Interval) { #*************************************************************************** # Function to derive the data with equal interval # Input # x: time sequence # y: measured response # Interval: interval indicating equal space between two consecutive points # minGap: the length of a chain of continuous missing values in which the # missing values will not be derived from the neighbor points # Output # a matrix with equally spaced time sequence and corresponding signal value # Author: Xiaohua Douglas Zhang # Date: 2017-05-26 #**************************************************************************** if( length(table( diff(x) )) == 1 ) { warning("The data have already had equal intervals between any two consecutive points. No adjustment!") xNew <- x; yNew <- y } x <- x[ !is.na(y) ] y <- y[ !is.na(y) ] xNew <- seq(min(x, na.rm=TRUE), max(x, na.rm=TRUE), by = Interval) yNew <- rep( NA, length(xNew) ) for( j in 1:length(xNew) ) { theX <- xNew[j] condt1 <- x <= theX; condt2 <- x >= theX if( sum(condt1, na.rm=TRUE)>0 & sum(condt2, na.rm=TRUE)>0 ) { #exclude edge points i1 <- max(which(x <= theX), na.rm=TRUE) i2 <- min(which(x >= theX), na.rm=TRUE) if( i2 - i1 <= minGap) { #exclude long chain of missing value x1 <- x[i1]; x2 <- x[i2] y1 <- y[i1]; y2 <- y[i2] if( x1 == x2 ) { yNew[j] <- (y1+y2)/2 } else { yNew[j] <- y1 + (y2-y1)/(x2-x1)*(theX-x1) } } } } return(cbind("timeSeries"=xNew, "signal"=yNew)) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/equalInterval.fn.R
fac2char.fn <- function(x) {levels(x)[as.numeric(x)]}
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/fac2char.fn.R
fixMissing.fn <- function( y, x, Method=c("skip","linearInterpolation", "loess", "dayCycle"), OBScycle = 24*60*60/10 ) { #***************************************************************************************** # Function to fix missing values in a vector # Input # y: a vector of data with missing values # x: a vector for a series of consecutive time indices # Method: method options for fixing missing value # "skip": skip all missing values # "loess": use local fitting by loess() # "dayCycle":a missing value is replaced by the mean of the two values one day ahead # and one day behind plus the mean of the differences between the two edge points # and their corresponding means of the two values one day head and one day behind # in a segment with missing values in which the missing value belongs to. # OBScycle: number of observations in a full cycle # Output: # newY: a vector of data from 'y' but with missing values fixed # Author: # Xiaohua Douglas Zhang, Ph.D., ASA Fellow # Date: # December 22, 2015 # updated, February 2017 #***************************************************************************************** newY <- y; newX <- x names(y) <- 1:length(y) a <- rle( is.na(y) ) nNA <- a$lengths[ a$values == 1 ] if( sum(nNA) ==0 ) { print( "Warning: no missing value") } else if (sum(nNA) == length(y) ) { print( "Warning: all missing values") } else { idxNA <- as.numeric( names(nNA) ) if( Method == "skip" | Method == "Skip" | Method == "SKIP" ) { newY <- y[ !is.na(y) ] newX <- x[ !is.na(y) ] } else if ( Method == "linearInterpolation" | Method == "loess" ) { idxStart <- ifelse( idxNA[1]-nNA[1]==1, idxNA[1], 1 ) idxEnd <- ifelse( sum(is.na(idxNA))==1, length(y) - nNA[length(nNA)], length(y)) yy <- y[idxStart:idxEnd] xx <- x[idxStart:idxEnd] #### using neighborhoood linear interpolation if( Method == "linearInterpolation") { newY[idxStart:idxEnd] <- approx(xx, yy, xout=xx, method = "linear")$y } else { #### using "loess" # hard to control the smoothness a.df <- data.frame("xx"=xx, "yy"=yy) yPredict <- predict(loess(yy~xx), data=a.df, data.frame("xx"=xx) ) yy[is.na(yy)] <- yPredict[is.na(yy)] newY[idxStart:idxEnd] <- yy } } else if( Method == "dayCycle") { #### using day cycle # treat the case where the last segment of missing values is in the end of y if( sum(is.na(idxNA)) == 1 ) idxNA[is.na(idxNA)] <- length(y)+1 # idxNA = idxNA[ !is.na[idxNA] ] for( k in 1:length(idxNA) ) { theIdxNAs <- idxNA[k]-nNA[k]:1 segment1 <- theIdxNAs-OBScycle segment1 <- c(segment1[1]-1, segment1, segment1[length(segment1)]+1) segment2 <- theIdxNAs+OBScycle segment2 <- c(segment2[1]-1, segment2, segment2[length(segment2)]+1) if( segment1[1] >= 1 & segment2[length(segment2)] <= length(y) ) { # fix the missing value in the middle days base.mat <- rbind( y[segment1], y[segment2] ) theValue <- apply(base.mat, 2, mean, na.rm=TRUE) } else if( segment1[1] < 1 & segment2[length(segment2)] <= length(y)) { # fix the missing value in the first days theValue <- y[segment2] } else if( segment2[length(segment2)] > length(y) ) { # fix the missing value in the last days theValue <- y[segment1] } else { stop("Warning: need at least data for 3 days") } adjValue <- mean(c(y[theIdxNAs[1]-1] - theValue[1], y[theIdxNAs[length(theIdxNAs)]+1] - theValue[length(theIdxNAs)]), na.rm=TRUE ) theValue <- theValue + adjValue newY[theIdxNAs] <- theValue[ 2:(length(theValue)-1) ] } } else { stop( "'Method' has to be 'skip', 'linearInterpolation', 'loess' or 'dayCycle'") } } return( cbind("x"=newX, "signal"=newY) ) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/fixMissing.fn.R
.onUnload <- function (libpath) { library.dynam.unload("CGManalyzer", libpath) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/onUnload.R
pairwiseComparison.fn <- function(y, INDEX, na.rm=TRUE, conf.level=0.95) { ################################################################################################ # function to calculate mean difference and its confidence interval, SSMD, p-value of t.test for # pairwise comparison #*********************************************************************************************** # Input # y: response value # INDEX: vector for group names # na.rm: whether to remove value for calculation # conf.level: confidence level for two-sided t-test # Output # a vector for calculated mean difference, its upper and lower bounds of CI, SSMD and pvalue # in each pairs of group comparison, along with mean, standard deviation, and sample size # in each group # Author: Xiaohua Douglas Zhang # Date: 2017-06-30 #*********************************************************************************************** Types <- sort( unique(INDEX) ) nType <- length(Types) nPair <- nType*(nType-1)/2 Means <- tapply( y, INDEX=INDEX, mean, na.rm=na.rm ) SDs <- tapply( y, INDEX=INDEX, sd, na.rm=na.rm ) Ns <- tapply( y, INDEX=INDEX, function(x) {sum(!is.na(x))} ) meanD.vec <- CIlower.vec <- CIupper.vec <- SSMD.vec <- pval.vec <- rep(NA, nPair) idx <- 0 coreNames <- rep(NA, nPair) for(j in 1:(nType-1) ) { for(k in (j+1):nType ) { idx <- idx+1 coreNames[idx] <- paste(Types[j], "vs", Types[k], sep=".") meanD.vec[idx] <- Means[j] - Means[k] condt1 <- INDEX==Types[j]; condt2 <- INDEX==Types[k] if( sum(condt1, na.rm=TRUE)>1 & sum(condt2, na.rm=TRUE)>1 ) { SSMD.vec[idx] <- meanD.vec[idx]/sqrt(SDs[j]^2 + SDs[k]^2) Ttest.lst <- t.test(y[condt1], y[condt2], conf.level=conf.level) pval.vec[idx] <- Ttest.lst$p.value CIlower.vec[idx] <- Ttest.lst$conf.int[1] CIupper.vec[idx] <- Ttest.lst$conf.int[2] } } } results <- c(meanD.vec, CIlower.vec, CIupper.vec, SSMD.vec, pval.vec, Means, SDs, Ns) outNames <- c( paste0("mDiff_",coreNames), paste0("CIlower_",coreNames), paste0("CIupper_",coreNames), paste0("SSMD_", coreNames), paste0("p_", coreNames), paste0("mean_", Types), paste0("SD_", Types), paste0("N_", Types) ) names(results) <- outNames return(results) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/pairwiseComparison.fn.R
plotTseries.fn <- function(x, y, xAt=NA, xLab=NA, yRange=NA, Frame=TRUE, xlab="", ylab="", pch=1, lty=1, col.point=1, col.line=1, cex.point=1, lwd=1) { ################################################################################################ # function to plot time series data #*********************************************************************************************** # Input # x: time in continuous value such as in seconds or minutes, (e.g. the return from timeSeqConversion.fn) # y: measured response value # Frame: whether the plot frame should be drawn # Author: Xiaohua Douglas Zhang # Date: 2017-05-24 #*********************************************************************************************** if( is.na(yRange[1]) ) yRange <- range(y, na.rm=TRUE) if( Frame == TRUE ) { plot(range(x, na.rm=TRUE), yRange, type="n", axes=F, xlab=xlab, ylab=ylab) axis(2, las=2); box() if( sum(is.na(xAt))!=0 | sum(is.na(xLab))!=0 ) { warning("Time is in the smallest unit since 'xAt' or 'xLab' is not provided.") axis(1) } else { axis(1, at = xAt, labels = xLab) } } lines(x, y, lty=lty, col=col.line, lwd=lwd) points(x, y, pch=pch, col=col.point, cex=cex.point) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/plotTseries.fn.R
setSPEC.fn = function(SPEC.name) { #**************************************************************************************************** # Function to load settings for the selected SPEC parameter # SPEC.name: the SPEC name to load, which is a R script name. # one of "SPEC.FreestyleLibre.R", "SPEC.Glutalor.R" and "SPEC.Medtronic.R". # Author: Xiaohua Douglas Zhang # Date: 2019-10-08 #***************************************************************************************************** source( system.file("SPEC", SPEC.name, package = "CGManalyzer") ) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/setSPEC.fn.R
ssmdEffect.fn <- function(ssmd.vec, criterion=c("mainType","subType")) { ##************************************************************************** ## function to derive the type of effect size based on SSMD values ## Input ## ssmd.vec: a vector for SSMD value ## criterion: whether use the criterion for deriving the main effect type ## or the sub-type ## Author: Xiaohua Douglas Zhang, 2007 ## Reference: ## Zhang XHD, 2011. Optimal High-Throughput Screening: Practical ## Experimental Design and Data Analysis for Genome-scale RNAi Research. ## Cambridge University Press, Cambridge, UK ##************************************************************************** effectClass.vec <- rep( NA, length(ssmd.vec) ) if( criterion == "mainType" ) { effectClass.vec[ ssmd.vec >= 1.645 ] <- "extra.Large+" effectClass.vec[ ssmd.vec >= 1 & ssmd.vec < 1.645 ] <- "Large+" effectClass.vec[ ssmd.vec > 0.25 & ssmd.vec < 1 ] <- "Medium+" effectClass.vec[ ssmd.vec > 0 & ssmd.vec <= 0.25 ] <- "Small+" effectClass.vec[ ssmd.vec == 0 ] <- "ZeroEfffect" effectClass.vec[ ssmd.vec < 0 & ssmd.vec > -0.25 ] <- "Small-" effectClass.vec[ ssmd.vec <= -0.25& ssmd.vec > -1 ] <- "Medium-" effectClass.vec[ ssmd.vec <= -1 & ssmd.vec > -1.645] <- "Large-" effectClass.vec[ ssmd.vec <= -1.645 ] <- "extra.Large-" } else if ( criterion == "subType" ) { effectClass.vec[ ssmd.vec >= 5 ] <- "ExtremelyStrong+" effectClass.vec[ ssmd.vec >= 3 & ssmd.vec < 5 ] <- "VeryStrong+" effectClass.vec[ ssmd.vec >= 2 & ssmd.vec < 3 ] <- "Strong+" effectClass.vec[ ssmd.vec >= 1.645& ssmd.vec < 2 ] <- "FairlyStrong+" effectClass.vec[ ssmd.vec >= 1.28 & ssmd.vec < 1.645 ] <- "Moderate+" effectClass.vec[ ssmd.vec >= 1 & ssmd.vec < 1.28 ] <- "FairlyModerate+" effectClass.vec[ ssmd.vec > 0.75 & ssmd.vec < 1 ] <- "FairlyWeak+" effectClass.vec[ ssmd.vec > 0.50 & ssmd.vec <= 0.75 ] <- "Weak+" effectClass.vec[ ssmd.vec > 0.25 & ssmd.vec <= 0.50 ] <- "VeryWeak+" effectClass.vec[ ssmd.vec > 0 & ssmd.vec <= 0.25 ] <- "ExtremelyWeak+" effectClass.vec[ ssmd.vec == 0 ] <- "ZeroEffect" effectClass.vec[ ssmd.vec < 0 & ssmd.vec >= -0.25] <- "ExtremelyWeak-" effectClass.vec[ ssmd.vec < -0.25 & ssmd.vec >= -0.50] <- "VeryWeak-" effectClass.vec[ ssmd.vec < -0.50 & ssmd.vec >= -0.75] <- "Weak-" effectClass.vec[ ssmd.vec < -0.75 & ssmd.vec > -1 ] <- "FairlyWeak-" effectClass.vec[ ssmd.vec <= -1 & ssmd.vec > -1.28 ] <- "FairlyModerate-" effectClass.vec[ ssmd.vec <= -1.28& ssmd.vec > -1.645] <- "Moderate-" effectClass.vec[ ssmd.vec <= -1.645& ssmd.vec > -2 ] <- "FairlyStrong-" effectClass.vec[ ssmd.vec <= -2 & ssmd.vec > -3 ] <- "Strong-" effectClass.vec[ ssmd.vec <= -3 & ssmd.vec > -5 ] <- "VeryStrong-" effectClass.vec[ ssmd.vec <= -5 ] <- "ExtremelyStrong-" } else { return("Error: criterion must be 'mainType' or 'subType'.") } if( sum(is.na(ssmd.vec)) > 0 ) effectClass.vec[ is.na(ssmd.vec) ] <- NA effectClass.vec }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/ssmdEffect.fn.R
summaryCGM.fn <- function(dataFolder, dataFiles, responseNames, sensorIDs, columnNames=NULL, skip=0, header=TRUE, comment.char="", sep=",") { #*************************************************************************** # Function to calculate the summary statistics for each subject or sensor: # number of subjects or sensors, minimum, 1st quartile, median, mean, # 2nd quartile, maximum, standard deviation, MAD # skip: number of lines to be skip in data file when using read.table # Author: Xiaohua Douglas Zhang # Date: 2017-06-06 #**************************************************************************** nFile = length(dataFiles) Nresponse = length(responseNames) Nsensor = length(sensorIDs) summary.arr = array( NA, dim=c(Nsensor, 10, Nresponse) ) for( iFile in 1:nFile ) { print(paste(iFile, "th file") ) data.df0 = read.table(paste(dataFolder, dataFiles[iFile], sep="/"), skip=skip, header=header,comment.char=comment.char, sep=sep) if( !header ) { data.df0=data.df0[, 1:length(columnNames)] dimnames(data.df0)[[2]] = columnNames } for( k in 1:length(responseNames) ) { Y = data.df0[, responseNames[k]] if( sum(is.na(Y)) ==0) s.vec=c(summary(Y), 0) else s.vec=summary(Y) summary.arr[iFile,,k] = c( length(Y), s.vec, sd(Y, na.rm=TRUE), mad(Y, na.rm=TRUE) ) } } dimnames(summary.arr)= list( "SensorID" = sensorIDs, "SummaryStat"=c("N", "Min", "Q1", "Median", "Mean", "Q3", "Max", "nNA", "SD", "MAD"), "Response"=responseNames) return(summary.arr) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/summaryCGM.fn.R
timeSeqConversion.fn <- function(time.stamp, time.format = "yyyy:mm:dd:hh:nn", timeUnit = "minute") { #*************************************************************************************************** # function to convert a matrix (with columns for year, month, day, minute and/or second) # to a time sequence in a unit of minute or second # Input # time.stamp: a vector for the time stamp. It can have any format such as "2016:08:11:09:14:00", # "11/08/2016 09:14:00" and others. The requirement is simply that the positions for year, month, # day, hour, minute, second are fixed and consistent in all data files and "0" before a non-zero # number cannot be skipped. # time.format: a string to specify the format in time.stamp in a study, such as "yyyy:mm:dd:hh:nn:ss:ii", # "dd/mm/yyyy hh:nn:ss:ii" and others which must have 'y' for year, 'm' for month, 'd' for day, # 'h' for hour, 'n' for minute, 's' for second, 'i' for millisecond(one thousandth of a second), # each uniquely # timeUnit: minimal time unit in time.stamp. can be 'minute' or 'second' # Output: a matrix with 6 columns for timeseries, year, month, day, hour and minute, respectively # Author: Xiaohua Douglas Zhang # Date: 2017-05-25 #**************************************************************************************** yearPos <- gregexpr(pattern ='y', time.format)[[1]] monthPos <- gregexpr(pattern ='m', time.format)[[1]] dayPos <- gregexpr(pattern ='d', time.format)[[1]] hourPos <- gregexpr(pattern ='h', time.format)[[1]] minutePos <- gregexpr(pattern ='n', time.format)[[1]] secondPos <- gregexpr(pattern ='s', time.format)[[1]] millisecondPos <- gregexpr(pattern ='i', time.format)[[1]] pos.lst <- list( "Year"=yearPos, "Month"=monthPos, "Day"=dayPos, "Hour"=hourPos, "Minute"=minutePos, "Second"=secondPos, "Millisecond"=millisecondPos) pos.name <- names(pos.lst) Time.mat <- NULL for( i in 1:length(pos.lst) ) { thePos <- pos.lst[[i]] Time <- as.matrix( as.numeric(substr( time.stamp, min(thePos), max(thePos) ))) dimnames(Time)[[2]] <- list(pos.name[i]) if(thePos[1] != -1) Time.mat <- cbind(Time.mat, Time) } minYear <- min(Time.mat[, "Year"], na.rm=TRUE) if( timeUnit == "minute" | timeUnit == "Minute" | timeUnit == "MINUTE" ) { date.vec <- as.Date( paste(Time.mat[, "Year"], substring(Time.mat[, "Month"]+1000, 3,4), substring(Time.mat[, "Day"]+1000, 3,4), sep="/") ) days.vec <- as.numeric( date.vec - as.Date(paste( minYear, "01", "01", sep="/")) ) Tsequence.vec <- days.vec*24*60 + Time.mat[, "Hour"]*60 + Time.mat[, "Minute"] Tsequence.vec <- Tsequence.vec - min(Tsequence.vec, na.rm=TRUE) } else if( timeUnit == "second" | timeUnit == "Second" | timeUnit == "SECOND" ) { date.vec <- as.Date( paste(Time.mat[, "Year"], substring(Time.mat[, "Month"]+1000, 3,4), substring(Time.mat[, "Day"]+1000, 3,4), sep="/") ) days.vec <- as.numeric( date.vec - as.Date(paste( minYear, "01", "01", sep="/")) ) Tsequence.vec <- days.vec*24*60*60 + Time.mat[,"Hour"]*60*60 + Time.mat[,"Minute"]*60 + Time.mat[,"Second"] Tsequence.vec <- Tsequence.vec - min(Tsequence.vec, na.rm=TRUE) } else { warning("'timeUnit' must be in minute or second." ) Tsequence.vec <- rep(NA, dim(Time.mat)[2]) } return( cbind("timeSequence"=Tsequence.vec, Time.mat) ) }
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/R/timeSeqConversion.fn.R
# for the .csv has the following format coming from the Freestyle Libre CGM device #------------------------------------------------------------------------------------------------- #Patient report Generated on 19/05/2017 Generated by who place #S000xP00xx #Serial Number Meter Timestamp Glucose reading(mmol/L) #JGMW251-T0672 FreeStyle Libre 2017:03:23:19:28 6.5 #JGMW251-T0672 FreeStyle Libre 2017:03:23:19:43 6.3 #JGMW251-T0672 FreeStyle Libre 2017:03:23:19:59 6.6 # ... #------------------------------------------------------------------------------------------------- ########################################################################################## # set up for reading data ########################################################################################## # Please complete the following steps before reading any data in R # 1. Put all the data (in .csv or .txt) in the data folder and remove all .zip or other files # 2. Call createFileList.fn create a file named "00filelist.csv" which holds # all the names of data files, one file for the data in one subject or sensor. # 3. Change the second column in generated file "00filelist.csv" in which the group type for each # subject is specified. After the addition is completed, the first 5 lines in "00filelist.csv" # should be more or less as follows #______________________________ #dataFiles,dataType #00filelist.csv,H #S0003P0001T1.csv,H #S0003P0001T2.csv,H #S0003P0002.csv,H #S0003P0003.csv,H #_______________________________ # 4. Each data file should have the same structure with the same number of columns and # the same column names, the same time stamp structure, the same number of head lines # to be skipped for read # 5. change the settings in the SPEC.R file so that the input for the parameters corresponds to # your data file and the CGM device that is used in your study. #****************************************************************************************** # 'Skip' in skip=Skip # 'timeStamp' in timeStamp = data.df0[,"timeStamp"] # 'Glucose.reading.mmol.L.' in data.df0[,responseName] # 00filelist.csv: a file containing the file names for time series data #****************************************************** # SPEC for reading the data in R #****************************************************** dataFolder = file.path(mainFolder, "data") dataFileType.df = read.table( paste(dataFolder, "00filelist.csv", sep="/"), skip=2, sep="," ,stringsAsFactors = TRUE, as.is = FALSE) dataFiles = fac2char.fn(dataFileType.df[,1]) subjectTypes = fac2char.fn(dataFileType.df[,2]) nFile = length(dataFiles) dataFileSuffix = ".csv" # suffix for the name of data files sensorIDs = gsub(dataFileSuffix, "", dataFiles, fixed=TRUE) Skip = 3 # number of lines to be skipped in each data file when the data is read in R Header = FALSE # whether to use the first line after skipping 'Skip' lines as the column names if( !Header ) columnNames = c("Serial", "Meter", "Time", "Glucose") Comment.char="" # in read.table() Sep="," # usually, Sep=',' when reading '.csv' and Sep='\t' when reading '.txt'. timeStamp.column = "Time" # this must be corrsponding to the column names after using read.table() responseName = "Glucose" # this must be corrsponding to the column names after using read.table() timeUnit = "minute" # the smallest time unit in the time series equal.interval = 15 # the size of interval between two consecutive points time.format = "yyyy:mm:dd:hh:nn" #"2016:08:11:09:14" ### handle with various time formats #time.format = "yyyy:mm:dd:hh:nn" #"2016:08:11:09:14" # The format must have 'y' for year, 'm' for month, 'd' for day, 'h' for hour, 'n' for minute, # 's' for second, 'i' for millisecond(one thousandth of a second), each uniquely idxNA = NA # idxNA = NA if the missing value is marked with NA correctly ####handle with the situation of using different symbol for missing value #****************************************************** # SPEC for calculating multiscale sample entropy #****************************************************** r <- 0.15 m <- 2 I <- 400000 scaleMax <- 10; scaleStep <- 1 Scales <- seq(1, scaleMax, by=scaleStep) cFile = "mseLong.c" #****************************************************************************************** # SPEC for whether to run calculation of summary statistics and/or boxplot for each sensor #****************************************************************************************** Summary = TRUE Boxplot = TRUE
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/inst/SPEC/SPEC.FreestyleLibre.R
# for the .csv has the following format coming from the Glutalor CGM device #------------------------------------------------------------------------------------------------- #ID PatientId SensorId Time Value #1 S0002P0004 1511131055-8 2016:05:27:12:07 0 #2 S0002P0004 1511131055-8 2016:05:27:12:10 0 #3 S0002P0004 1511131055-8 2016:05:27:12:13 0 # ... #------------------------------------------------------------------------------------------------- ########################################################################################## # set up for reading data ########################################################################################## # Please complete the following steps before reading any data in R # 1. Put all the data (in .csv or .txt) in the data folder and remove all .zip or other files # 2. Call createFileList.fn create a file named "00filelist.csv" which holds # all the names of data files, one file for the data in one subject or sensor. # 3. Change the second column in generated file "00filelist.csv" in which the group type for each # subject is specified. After the addition is completed, the first 5 lines in "00filelist.csv" # should be more or less as follows #______________________________ #dataFiles,dataType #00filelist.csv,H #S0003P0001T1.csv,H #S0003P0001T2.csv,H #S0003P0002.csv,H #S0003P0003.csv,H #_______________________________ # 4. Each data file should have the same structure with the same number of columns and # the same column names, the same time stamp structure, the same number of head lines # to be skipped for read # 5. change the settings in the SPEC.R file so that the input for the parameters corresponds to # your data file and the CGM device that is used in your study. #****************************************************************************************** # 'Skip' in skip=Skip # 'timeStamp' in timeStamp = data.df0[,"timeStamp"] # 'Glucose.reading.mmol.L.' in data.df0[,responseName] # 00filelist.csv: a file containing the file names for time series data #****************************************************** # SPEC for reading the data in R #****************************************************** dataFolder = file.path(mainFolder, "data") dataFileType.df = read.table( paste(dataFolder, "00filelist.csv", sep="/"), skip=2, sep="," ,stringsAsFactors = TRUE, as.is = FALSE) dataFiles = fac2char.fn(dataFileType.df[,1]) subjectTypes = fac2char.fn(dataFileType.df[,2]) nFile = length(dataFiles) dataFileSuffix = ".csv" # suffix for the name of data files sensorIDs = gsub(dataFileSuffix, "", dataFiles, fixed=TRUE) Skip = 3 # number of lines to be skipped in each data file when the data is read in R Header = FALSE # whether to use the first line after skipping 'Skip' lines as the column names if( !Header ) columnNames = c("Serial", "Meter", "Time", "Glucose") Comment.char="" # in read.table() Sep="," # usually, Sep=',' when reading '.csv' and Sep='\t' when reading '.txt'. timeStamp.column = "Time" # this must be corrsponding to the column names after using read.table() responseName = "Glucose" # this must be corrsponding to the column names after using read.table() timeUnit = "minute" # the smallest time unit in the time series equal.interval = 3 # the size of interval between two consecutive points #time.format = "yyyy:mm:\tdd:hh:nn" #"2016:08:11:09:14" ### handle with various time formats time.format = "yyyy:mm:dd:hh:nn" #"2016:08:11:09:14" # The format must have 'y' for year, 'm' for month, 'd' for day, 'h' for hour, 'n' for minute, # 's' for second, 'i' for millisecond(one thousandth of a second), each uniquely idxNA = 0 # idxNA = NA if the missing value is marked with NA correctly ####handle with the situation of using different symbol for missing value #****************************************************** # SPEC for calculating multiscale sample entropy #****************************************************** r <- 0.15 m <- 2 I <- 400000 scaleMax <- 10; scaleStep <- 1 Scales <- seq(1, scaleMax, by=scaleStep) cFile = "mseLong.c" #****************************************************************************************** # SPEC for whether to run calculation of summary statistics and/or boxplot for each sensor #****************************************************************************************** Summary = TRUE Boxplot = TRUE
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/inst/SPEC/SPEC.Glutalor.R
# for the .csv has the following format coming from the Medtronic CGM device #------------------------------------------------------------------------------------------------- # Name Patient ID #S000xP00xx 00:00 #Start Date End Date #30/06/2016 00:00 2016:07:01 #------- MiniMed Paradigm 722 Sensor 728974 ------- #Index Date Time Sensor Glucose (mmol/L) #1 2016/07/01 15:14 13.1 #2 2016/07/01 15:09 12.99 #3 2016/07/01 15:04 12.88 #4 2016/07/01 14:59 12.77 # ... #------------------------------------------------------------------------------------------------- ########################################################################################## # set up for reading data ########################################################################################## # Please complete the following steps before reading any data in R # 1. Put all the data (in .csv or .txt) in the data folder and remove all .zip or other files # 2. Call createFileList.fn create a file named "00filelist.csv" which holds # all the names of data files, one file for the data in one subject or sensor. # 3. Change the second column in generated file "00filelist.csv" in which the group type for each # subject is specified. After the addition is completed, the first 5 lines in "00filelist.csv" # should be more or less as follows #______________________________ #dataFiles,dataType #00filelist.csv,H #S0003P0001T1.csv,H #S0003P0001T2.csv,H #S0003P0002.csv,H #S0003P0003.csv,H #_______________________________ # 4. Each data file should have the same structure with the same number of columns and # the same column names, the same time stamp structure, the same number of head lines # to be skipped for read # 5. change the settings in the SPEC.R file so that the input for the parameters corresponds to # your data file and the CGM device that is used in your study. #****************************************************************************************** # 'Skip' in skip=Skip # 'timeStamp' in timeStamp = data.df0[,"timeStamp"] # 'Glucose.reading.mmol.L.' in data.df0[,responseName] # 00filelist.csv: a file containing the file names for time series data #****************************************************** # SPEC for reading the data in R #****************************************************** dataFolder = file.path(mainFolder, "data") dataFileType.df = read.table( paste(dataFolder, "00filelist.csv", sep="/"), skip=2, sep="," ,stringsAsFactors = TRUE, as.is = FALSE) dataFiles = fac2char.fn(dataFileType.df[,1]) subjectTypes = fac2char.fn(dataFileType.df[,2]) nFile = length(dataFiles) dataFileSuffix = ".csv" # suffix for the name of data files sensorIDs = gsub(dataFileSuffix, "", dataFiles, fixed=TRUE) Skip = 6 # number of lines to be skipped in each data file when the data is read in R Header = FALSE # whether to use the first line after skipping 'Skip' lines as the column names if( !Header ) columnNames = c("Index", "Date", "Time", "Glucose") #must be specified if Header=FALSE Comment.char="" # in read.table() Sep="," # usually, Sep=',' when reading '.csv' and Sep='\t' when reading '.txt'. timeStamp.column = c("Date", "Time") # this must be corrsponding to the column names after using read.table() responseName = "Glucose" # this must be corrsponding to the column names after using read.table() timeUnit = "minute" # the smallest time unit in the time series equal.interval = 5 # the size of interval between two consecutive points #equal.interval = 15 # the size of interval between two consecutive points #time.format = "yyyy:mm:\tdd:hh:nn" #"2016:08:11:09:14" ### handle with various time formats time.format = "yyyy/mm/dd hh:nn" #"2016:08:11:09:14" # The format must have 'y' for year, 'm' for month, 'd' for day, 'h' for hour, 'n' for minute, # 's' for second, 'i' for millisecond(one thousandth of a second), each uniquely # If timeStamp.column has multiple columns, put an empty space " " between them idxNA = NA # idxNA = NA if the missing value is marked with NA correctly ####handle with the situation of using different symbol for missing value #****************************************************** # SPEC for calculating multiscale sample entropy #****************************************************** r <- 0.15 m <- 2 I <- 400000 scaleMax <- 10; scaleStep <- 1 Scales <- seq(1, scaleMax, by=scaleStep) cFile = "mseLong.c" #****************************************************************************************** # SPEC for whether to run calculation of summary statistics and/or boxplot for each sensor #****************************************************************************************** Summary = TRUE Boxplot = TRUE
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/inst/SPEC/SPEC.Medtronic.R
#****************************************************** # SPEC for reading the data in R #****************************************************** a0 <- "00filelist.csv" a <- system.file("exampleDATA", a0, package = package.name) dataFolder <- substring(a, 1, nchar(a)-nchar(a0)-1 ) dataFileType.df = read.table( paste(dataFolder, "00filelist.csv", sep="/"), skip=2, sep="," ,stringsAsFactors = TRUE, as.is = FALSE) dataFiles = fac2char.fn(dataFileType.df[,1]) subjectTypes = fac2char.fn(dataFileType.df[,2]) nFile = length(dataFiles) dataFileSuffix = ".csv" # suffix for the name of data files sensorIDs = gsub(dataFileSuffix, "", dataFiles, fixed=TRUE) Skip = 1 # number of lines to be skipped in each data file when the data is read in R #Skip = 3 # number of lines to be skipped in each data file when the data is read in R Header = FALSE # whether to use the first line after skipping 'Skip' lines as the column names if( !Header ) columnNames = c("Time", "Glucose") #must specify #if( !Header ) columnNames = c("ID", "PatientId", "SensorId", "Time", "Glucose") #if( !Header ) columnNames = c("serialNumber", "SensorId", "Time", "Glucose", "Empty1", "Empty2") Comment.char="" # in read.table() Sep="," # usually, Sep=',' when reading '.csv' and Sep='\t' when reading '.txt'. timeStamp.column = "Time" # this must be corrsponding to the column names after using read.table() responseName = "Glucose" # this must be corrsponding to the column names after using read.table() timeUnit = "minute" # the smallest time unit in the time series equal.interval = 3 # the size of interval between two consecutive points #equal.interval = 15 # the size of interval between two consecutive points #time.format = "yyyy:mm:\tdd:hh:nn" #"2016:08:11:09:14" ### handle with various time formats time.format = "yyyy:mm:dd:hh:nn" #"2016:08:11:09:14" # The format must have 'y' for year, 'm' for month, 'd' for day, 'h' for hour, 'n' for minute, # 's' for second, 'i' for millisecond(one thousandth of a second), each uniquely idxNA = 0 # idxNA = NA if the missing value is marked with NA correctly ####handle with the situation of using different symbol for missing value #idxNA = NA # idxNA = NA if the missing value is marked with NA correctly #****************************************************** # SPEC for calculating multiscale sample entropy #****************************************************** r <- 0.15 m <- 2 I <- 400000 scaleMax <- 10; scaleStep <- 1 Scales <- seq(1, scaleMax, by=scaleStep) cFile = "mseLong.c" #****************************************************************************************** # SPEC for whether to run calculation of summary statistics and/or boxplot for each sensor #****************************************************************************************** Summary = TRUE Boxplot = TRUE
/scratch/gouwar.j/cran-all/cranData/CGManalyzer/inst/SPEC/SPECexample.R
## TODO remove parallel statements from the documentation repmat=function(subM,numrows,numcol){ matrix_out=subM if(numrows>1){ for(i in seq(1,numrows-1)){ matrix_out=rbind(matrix_out,subM) } } tempM=matrix_out if(numcol>1){ for(i in seq(1,numcol-1)){ matrix_out=cbind(matrix_out,tempM) } } return(matrix_out) } col_normalize=function(data_in){ out=data_in; for(i in seq(1,dim(data_in)[2])){ if(sd(data_in[,i])!=0){ out[,i]=(data_in[,i]-mean(data_in[,i]))/sd(data_in[,i]) } } return(out) } col_sd=function(data_in){ out=c() for(i in seq(1,dim(data_in)[2])){ out=c(out,sd(data_in[,i],na.rm = TRUE)) } return(out) } col_max=function(data_in){ out=c() for(i in seq(1,dim(data_in)[2])){ out=c(out,max(data_in[,i],na.rm = TRUE)) } return(out) } col_min=function(data_in){ out=c() for(i in seq(1,dim(data_in)[2])){ out=c(out,min(data_in[,i],na.rm = TRUE)) } return(out) } col_mean=function(data_in){ out=c() for(i in seq(1,dim(data_in)[2])){ out=c(out,mean(data_in[,i],na.rm = TRUE)) } return(out) } col_median=function(data_in){ out=c() for(i in seq(1,dim(data_in)[2])){ out=c(out,median(data_in[,i],na.rm = TRUE)) } return(out) } col_quantile=function(data_in, prob){ out=c() for(i in seq(1,dim(data_in)[2])){ out=c(out,as.numeric(quantile(data_in[,i],na.rm = TRUE, prob=prob))) } return(out) } elbow_index=function(vec_in){ trapizoido_area=c() for(i in seq(1,length(vec_in)-1)) trapizoido_area=c(trapizoido_area, (vec_in[1]+vec_in[i])*i+(vec_in[i+1]+vec_in[length(vec_in)])*(length(vec_in)-i)) return(which(trapizoido_area==min(trapizoido_area))) } optimal_kmeans=function(data_in){ #Assume data is stored in rows normalized_data=col_normalize(data_in) residual=c() numMaxCluster=min(round(dim(data_in)[1]/dim(data_in)[2]/2),10) if(numMaxCluster>1){ for(i in seq(2,numMaxCluster)){ kmeans_res=kmeans(normalized_data,i) residual=c(residual,kmeans_res$tot.withinss) } elbow_ind=(elbow_index(residual)) if(length(elbow_ind)>0){ kmeans(normalized_data,(elbow_ind[1]+1)) }else{ kmeans(normalized_data,1) } }else{ kmeans(normalized_data,1) } } matlabSum <-function(matrix,direction){ if (direction==1){ return(t(as.matrix(colSums(matrix)))) }else{ return(as.matrix(rowSums(matrix))) } } matlabMedian<-function(matrix,direction){ out=c() if (direction==1){ for(i in seq(1,dim(matrix)[2])){ out=c(out,median(matrix[,i], na.rm =TRUE)) } return(t(as.matrix(out))) }else{ for(i in seq(1,dim(matrix)[1])){ out=c(out,median(matrix[i,], na.rm =TRUE)) } return((as.matrix(out))) } } dot=function(vec1,vec2){ return(as.numeric(t(as.matrix(vec1))%*%as.matrix(vec2))) } matlabRand<-function(numRow,numCol){ outMat=runif(numCol) for(i in seq(2,numRow)){ outMat=rbind(outMat,runif(numCol)) } return(outMat) } tryCatch_nonlinearFunction=function(x,num_observations, nonlinearFunction, validTarget){ if(is.null(dim(x))){ numXrows=1 }else{ numXrows=dim(x)[1] } out <- tryCatch( { nonlinearFunction(x) }, error=function(cond) { if(numXrows==1){ temoOut=rep(NaN,num_observations) }else{ temoOut=matrix(rep(NaN,num_observations*numXrows),nrow = numXrows) } return(temoOut) }, warning=function(cond) { nonlinearFunction(x) }, finally={ } ) if(numXrows==1){ out[!validTarget]=0 if(length(out)!=num_observations){ out=rep(NaN,num_observations) }else if(is.na(sum(out))){ out=rep(NaN,num_observations) }else if(is.infinite(sum(abs(out)))){ out=rep(NaN,num_observations) } }else{ if(dim(out)[2]!=num_observations){ out=matrix(rep(NaN,num_observations*numXrows),nrow = numXrows) }else{ out[is.na(rowSums(out)),]=NaN out[is.infinite(abs(rowSums(out))),]=NaN out[is.nan(rowSums(out)),]=NaN } out[,!validTarget]=0 } return(out) } CGNM_input_test <- function(nonlinearFunction, targetVector, initial_lowerRange, initial_upperRange ){ tempOut <- tryCatch( { (dim(nonlinearFunction(t(matrix(rep(initial_upperRange,2),ncol = 2))))) }, error=function(cond) { return(NULL) }, warning=function(cond) { (dim(nonlinearFunction(t(matrix(rep(initial_upperRange,2),ncol = 2))))) }, finally={ } ) if(is.null(tempOut)){ out=FALSE }else{ out=(tempOut[1]==2) } if(length(initial_lowerRange)!=length(initial_upperRange)){ stop("initial_lowerRange and initial_upperRange need to have the same length") } if(sum(is.na(as.numeric(initial_lowerRange)))+sum(is.na(as.numeric(initial_upperRange)))>0){ stop("initial_lowerRange and initial_upperRange can only be the vector of non-numericl values") } if(out){ message("nonlinearFunction is given as matrix to matrix function") testEval=nonlinearFunction(t(matrix(c(initial_lowerRange,(initial_upperRange+initial_lowerRange)/2,initial_upperRange),ncol = 3))) RS_testEval=rowSums(testEval) if(is.na(RS_testEval[1])){ message("WARNING: nonlinearFunction evaluation at initial_lowerRange NOT Successful.") }else{ message("NonlinearFunction evaluation at initial_lowerRange Successful.") } if(is.na(RS_testEval[2])){ message("WARNING: nonlinearFunction evaluation at (initial_upperRange+initial_lowerRange)/2 NOT Successful.") }else{ message("NonlinearFunction evaluation at (initial_upperRange+initial_lowerRange)/2 Successful.") } if(is.na(RS_testEval[3])){ message("WARNING: nonlinearFunction evaluation at initial_upperRange NOT Successful.") }else{ message("NonlinearFunction evaluation at initial_upperRange Successful.") } if(dim(testEval)[2]!=length(targetVector)){ stop("Length of output of the nonlinearFunction and targetVector are not the same. Double check the nonlinear function definition and targetVector input.") } }else{ message("checking if the nonlinearFunction can be evaluated at the initial_lowerRange") testEval=nonlinearFunction(initial_lowerRange) if(!is.na(sum(testEval))&&length(testEval)==length(targetVector)){ message("Evaluation Successful") }else{ message("WARNING: nonlinearFunction evaluation at initial_lowerRange NOT Successful.") } message("checking if the nonlinearFunction can be evaluated at the initial_upperRange") testEval=nonlinearFunction(initial_upperRange) if(!is.na(sum(testEval))&&length(testEval)==length(targetVector)){ message("Evaluation Successful") }else{ message("WARNING: nonlinearFunction evaluation at initial_upperRange NOT Successful.") } message("checking if the nonlinearFunction can be evaluated at the (initial_upperRange+initial_lowerRange)/2") testEval=nonlinearFunction((initial_upperRange+initial_lowerRange)/2) if(!is.na(sum(testEval))&&length(testEval)==length(targetVector)){ message("Evaluation Successful") }else{ message("WARNING: nonlinearFunction evaluation at (initial_upperRange+initial_lowerRange)/2 NOT Successful.") } if(length(testEval)!=length(targetVector)){ stop("Length of output of the nonlinearFunction and targetVector are not the same. Double check the nonlinear function definition and targetVector input.") } } return(out) } #' @title Cluster_Gauss_Newton_method #' @description Find multiple minimisers of the nonlinear least squares problem. #' \deqn{argmin_x ||f(x)-y*||} #' where #' \enumerate{\item f: nonlinear function (e.g., mathematical model) #' \item y*: target vector (e.g., observed data to fit the mathematical model) #' \item x: variable of the nonlinear function that we aim to find the values that minimize (minimizers) the differences between the nonlinear function and target vector (e.g., model parameter) #' } #' Parameter estimation problems of mathematical models can often be formulated as nonlinear least squares problems. In this context f can be thought at a model, x is the parameter, and y* is the observation. #' CGNM iteratively estimates the minimizer of the nonlinear least squares problem from various initial estimates hence finds multiple minimizers. #' Full detail of the algorithm and comparison with conventional method is available in the following publication, also please cite this publication when this algorithm is used in your research: Aoki et al. (2020) <doi.org/10.1007/s11081-020-09571-2>. Cluster Gauss–Newton method. Optimization and Engineering, 1-31. As illustrated in this paper, CGNM is faster and more robust compared to repeatedly applying the conventional optimization/nonlinear least squares algorithm from various initial estimates. In addition, CGNM can realize this speed assuming the nonlinear function to be a black-box function (e.g. does not use things like adjoint equation of a system of ODE as the function does not have to be based on a system of ODEs.). #' @param nonlinearFunction (required input) \emph{A function with input of a vector x of real number of length n and output a vector y of real number of length m.} In the context of model fitting the nonlinearFunction is \strong{the model}. Given the CGNM does not assume the uniqueness of the minimizer, m can be less than n. Also CGNM does not assume any particular form of the nonlinear function and also does not require the function to be continuously differentiable (see Appendix D of our publication for an example when this function is discontinuous). Also this function can be matrix to matrix equation. This can be used for parallerization, see vignettes for examples. #' @param ... Further arguments to be supplied to nonlinearFunction #' @param targetVector (required input) \emph{A vector of real number of length m} where we minimize the Euclidean distance between the nonlinearFuncition and targetVector. In the context of curve fitting targetVector can be though as \strong{the observational data}. #' @param initial_lowerRange (required input) \emph{A vector of real number of length n} where each element represents \strong{the lower range of the initial iterate}. Similarly to regular Gauss-Newton method, CGNM iteratively reduce the residual to find minimizers. Essential differences is that CGNM start from the initial RANGE and not an initial point. #' @param initial_upperRange (required input) \emph{A vector of real number of length n} where each element represents \strong{the upper range of the initial iterate}. #' @param lowerBound (default: NA) \emph{A vector of real number or NA of length n} where each element represents \strong{the lower bound of the parameter search}. If no lower bound set that element NA. Note that CGNM is an unconstraint optimization method so the final minimizer can be anywhere. In the parameter estimation problem, there often is a constraints to the parameters (e.g., parameters cannot be negative). So when the upper or lower bound is set using this option, parameter transformation is conducted internally (e.g., if either the upper or lower bound is given parameters are log transformed, if the upper and lower bounds are given logit transform is used.) #' @param upperBound (default: NA) \emph{A vector of real number or NA of length n} where each element represents \strong{the upper bound of the parameter search}. If no upper bound set that element NA. #' @param ParameterNames (default: NA) \emph{A vector of string} of length n User can specify names of the parameters that will be used for the plots. #' @param stayIn_initialRange (default: FALSE) \emph{TRUE or FALSE} if set TRUE, the parameter search will conducted strictly within the range specified by initial_lowerRange and initial_upperRange. #' @param num_minimizersToFind (default: 250) \emph{A positive integer} defining number of approximate minimizers CGNM will find. We usually \strong{use 250 when testing the model and 1000 for the final analysis}. The computational cost increase proportionally to this number; however, larger number algorithm becomes more stable and increase the chance of finding more better minimizers. See Appendix C of our paper for detail. #' @param num_iteration (default: 25) \emph{A positive integer} defining maximum number of iterations. We usually \strong{set 25 while model building and 100 for final analysis}. Given each point terminates the computation when the convergence criterion is met the computation cost does not grow proportionally to the number of iterations (hence safe to increase this without significant increase in the computational cost). #' @param saveLog (default: TRUE) \emph{TRUE or FALSE} indicating either or not to save computation result from each iteration in CGNM_log folder. It requires disk write access right in the current working directory. \strong{Recommended to set TRUE if the computation is expected to take long time} as user can retrieve intrim computation result even if the computation is terminated prematurely (or even during the computation). #' @param runName (default: "") \emph{string} that user can ue to identify the CGNM runs. The run history will be saved in the folder name CGNM_log_<runName>. If this is set to "TIME" then runName is automatically set by the run start time. #' @param textMemo (default: "") \emph{string} that user can write an arbitrary text (without influencing computation). This text is stored with the computation result so that can be used for example to describe model so that the user can recognize the computation result. #' @param algorithmParameter_initialLambda (default: 1) \emph{A positive number} for initial value for the regularization coefficient lambda see Appendix B of of our paper for detail. #' @param algorithmParameter_gamma (default: 2) \emph{A positive number} a positive scalar value for adjusting the strength of the weighting for the linear approximation see Appendix A of our paper for detail. #' @param algorithmVersion (default: 3.0) \emph{A positive number} user can choose different version of CGNM algorithm currently 1.0 and 3.0 are available. If number chosen other than 1.0 or 3.0 it will choose 1.0. #' @param initialIterateMatrix (default: NA) \emph{A matrix} with dimension num_minimizersToFind x n. User can provide initial iterate as a matrix This input is used when the user wishes not to generate initial iterate randomly from the initial range. The user is responsible for ensuring all function evaluation at each initial iterate does not produce NaN. #' @param targetMatrix (default: NA) \emph{A matrix} with dimension num_minimizersToFind x m User can define multiple target vectors in the matrix form. This input is mainly used when running bootstrap method and not intended to be used for other purposes. #' @param keepInitialDistribution (default: NA) \emph{A vector of TRUE or FALSE} of length n User can specify if the initial distribution of one of the input variable (e.g. parameter) to be kept as the initial iterate throughout CGNM iterations. #' @return list of a matrix X, Y,residual_history and initialX, as well as a list runSetting #' \enumerate{\item X: \emph{a num_minimizersToFind by n matrix} which stores the approximate minimizers of the nonlinear least squares in each row. In the context of model fitting they are \strong{the estimated parameter sets}. #' \item Y: \emph{a num_minimizersToFind by m matrix} which stores the nonlinearFunction evaluated at the corresponding approximate minimizers in matrix X above. In the context of model fitting each row corresponds to \strong{the model simulations}. #' \item residual_history: \emph{a num_iteration by num_minimizersToFind matrix} storing sum of squares residual for all iterations. #' \item initialX: \emph{a num_minimizersToFind by n matrix} which stores the set of initial iterates. #' \item runSetting: a list containing all the input variables to Cluster_Gauss_Newton_method (i.e., nonlinearFunction, targetVector, initial_lowerRange, initial_upperRange ,algorithmParameter_initialLambda, algorithmParameter_gamma, num_minimizersToFind, num_iteration, saveLog, runName, textMemo).} #' @examples #' ##lip-flop kinetics (an example known to have two distinct solutions) #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, num_iteration = 10, num_minimizersToFind = 100, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' saveLog = FALSE) #' #' acceptedApproximateMinimizers(CGNM_result) #' # ## flip-flop kinetics using RxODE (an example known to have two distinct solutions) #' \dontrun{ #' library(RxODE) #' #' model_text=" #' d/dt(X_1)=-ka*X_1 #' d/dt(C_2)=(ka*X_1-CL_2*C_2)/V1" #' #' model=RxODE(model_text) #' #define nonlinearFunction #' model_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' #' theta <- c(ka=x[1],V1=x[2],CL_2=x[3]) #' ev <- eventTable() #' ev$add.dosing(dose = 1000, start.time =0) #' ev$add.sampling(observation_time) #' odeSol=model$solve(theta, ev) #' log10(odeSol[,"C_2"]) #' #' } #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_function, #' targetVector = observation, saveLog = FALSE, #' initial_lowerRange = c(0.1,0.1,0.1),initial_upperRange = c(10,10,10))} #' #' @export #' @import stats MASS Cluster_Gauss_Newton_method <- function(nonlinearFunction, ... ,targetVector, initial_lowerRange, initial_upperRange , lowerBound=NA, upperBound=NA, ParameterNames=NA, stayIn_initialRange=FALSE, num_minimizersToFind=250, num_iteration=25, saveLog=TRUE, runName="", textMemo="",algorithmParameter_initialLambda=1, algorithmParameter_gamma=2, algorithmVersion=3.0, initialIterateMatrix=NA, targetMatrix=NA, keepInitialDistribution=NA){ if(length(lowerBound)==1&is.na(lowerBound)[1]){ lowerBound=rep(NA, length(initial_lowerRange)) } if(length(upperBound)==1&is.na(upperBound)[1]){ upperBound=rep(NA, length(initial_upperRange)) } if(!(length(initial_lowerRange)==length(initial_upperRange) & length(lowerBound)==length(upperBound)&length(initial_upperRange)==length(lowerBound))){ stop("length of initial_lowerRange, initial_upperRange, lowerBound, upperBound must be the same") } length_paraVector=length(initial_lowerRange) validIndex=!is.na(lowerBound) if((sum(initial_lowerRange[validIndex]>lowerBound[validIndex])!=sum(validIndex))){ stop("Initial lower range must be STRICTRY larger than lower BOUND") } validIndex=!is.na(upperBound) if((sum(initial_upperRange[validIndex]<upperBound[validIndex])!=sum(validIndex))){ stop("Initial upper range must be STRICTRY less than upper BOUND") } if(is.na(ParameterNames)[1]){ ParameterNames=paste0("theta_",seq(1,length_paraVector)) } ReparameterizationDef=paste0("x",seq(1,length_paraVector)) LB_index=(!is.na(as.numeric(lowerBound)))&is.na(upperBound) UB_index=(!is.na(as.numeric(upperBound)))&is.na(lowerBound) BB_index=(!is.na(as.numeric(lowerBound)))&(!is.na(as.numeric(upperBound))) LB_paraReDef=paste0("exp(x",seq(1,length(lowerBound)),")+",lowerBound) UB_paraReDef=paste0(upperBound,"-exp(x",seq(1,length(lowerBound)),")") BB_paraReDef=paste0("(",upperBound,"-",lowerBound,")*(exp(x",seq(1,length(lowerBound)),")/(exp(x",seq(1,length(lowerBound)),")+1))+",lowerBound) ReparameterizationDef[LB_index]=LB_paraReDef[LB_index] ReparameterizationDef[UB_index]=UB_paraReDef[UB_index] ReparameterizationDef[BB_index]=BB_paraReDef[BB_index] X_LR=initial_lowerRange X_LR[LB_index]=log(initial_lowerRange[LB_index]-lowerBound[LB_index]) X_LR[UB_index]=log(-initial_lowerRange[UB_index]+upperBound[UB_index]) X_LR[BB_index]=log((initial_lowerRange[BB_index]-lowerBound[BB_index])/(upperBound[BB_index]-initial_lowerRange[BB_index])) X_UR=initial_upperRange X_UR[LB_index]=log(initial_upperRange[LB_index]-lowerBound[LB_index]) X_UR[UB_index]=log(-initial_upperRange[UB_index]+upperBound[UB_index]) X_UR[BB_index]=log((initial_upperRange[BB_index]-lowerBound[BB_index])/(upperBound[BB_index]-initial_upperRange[BB_index])) if(!is.na(initialIterateMatrix)[1]){ originalInit=initialIterateMatrix rowNumInitMatrix=dim(initialIterateMatrix)[1] initialIterateMatrix[,LB_index]=log(initialIterateMatrix[,LB_index]-repmat(lowerBound[LB_index],numrows = rowNumInitMatrix ,numcol = 1)) initialIterateMatrix[,UB_index]=log(-initialIterateMatrix[,UB_index]+repmat(upperBound[UB_index],numrows = rowNumInitMatrix ,numcol = 1)) initialIterateMatrix[,BB_index]=log((initialIterateMatrix[,BB_index]-repmat(lowerBound[BB_index],numrows = rowNumInitMatrix ,numcol = 1))/(repmat(upperBound[BB_index],numrows = rowNumInitMatrix ,numcol = 1)-initialIterateMatrix[,BB_index])) } lowerBoundMatrix=repmat(lowerBound[BB_index],numrows = num_minimizersToFind ,numcol = 1) upperBoundMatrix=repmat(upperBound[BB_index],numrows = num_minimizersToFind ,numcol = 1) nonlinearFunction_varTrans=function(x,...){ if(is.vector(x)){ theta=x theta[LB_index]=exp(x[LB_index])-lowerBound[LB_index] theta[UB_index]=-exp(x[UB_index])+upperBound[UB_index] theta[BB_index]=(upperBound[BB_index]-lowerBound[BB_index])*(exp(x[BB_index])/(exp(x[BB_index])+1))+lowerBound[BB_index] }else{ theta=x theta[,LB_index]=exp(x[,LB_index])-repmat(lowerBound[LB_index],numrows = dim(x)[1] ,numcol = 1) theta[,UB_index]=-exp(x[,UB_index])+repmat(upperBound[UB_index],numrows = dim(x)[1] ,numcol = 1) theta[,BB_index]=(upperBoundMatrix-lowerBoundMatrix)[seq(1,dim(x)[1]),]*(exp(x[,BB_index])/(exp(x[,BB_index])+1))+lowerBoundMatrix[seq(1,dim(x)[1]),] } nonlinearFunction(theta,...) } out=Cluster_Gauss_Newton_method_core(nonlinearFunction_varTrans, targetVector, initial_lowerRange=X_LR, initial_upperRange=X_UR ,lowerBound=lowerBound, upperBound=upperBound, stayIn_initialRange, num_minimizersToFind, num_iteration, saveLog, runName, textMemo,algorithmParameter_initialLambda, algorithmParameter_gamma, algorithmVersion, initialIterateMatrix, targetMatrix, keepInitialDistribution,ParameterNames,ReparameterizationDef) return(out) } Cluster_Gauss_Newton_method_core <- function(nonlinearFunction, targetVector, initial_lowerRange, initial_upperRange , stayIn_initialRange=FALSE, num_minimizersToFind=250, num_iteration=25, saveLog=FALSE, runName="", textMemo="",algorithmParameter_initialLambda=1, algorithmParameter_gamma=2, algorithmVersion=3.0, initialIterateMatrix=NA, targetMatrix=NA, keepInitialDistribution=NA,ParameterNames=NA,ReparameterizationDef=NA,lowerBound=NA, upperBound=NA){ CGNM_start_time=Sys.time() targetMatrix_in=targetMatrix dimTargetMatrix=c(0,0) dimInitialIterateMatrix=c(0,0) if(is.matrix(initialIterateMatrix)){ dimInitialIterateMatrix=dim(initialIterateMatrix) } if(is.matrix(targetMatrix_in)){ dimTargetMatrix=dim(targetMatrix_in) } if(dimInitialIterateMatrix[1]>0&dimTargetMatrix[1]>0){ num_minimizersToFind=min(dimInitialIterateMatrix[1], dimTargetMatrix[1]) initialIterateMatrix=initialIterateMatrix[1:num_minimizersToFind,] targetMatrix_in=targetMatrix_in[1:num_minimizersToFind,] }else if(dimTargetMatrix[1]>0){ num_minimizersToFind=dimTargetMatrix[1] }else if(dimInitialIterateMatrix[1]>0){ num_minimizersToFind=dimInitialIterateMatrix[1] } textMemo=paste0("CGNM algorithm version ",algorithmVersion,"\n\n",textMemo) runSetting=list(nonlinearFunction=nonlinearFunction, targetVector=targetVector, initial_lowerRange=initial_lowerRange, initial_upperRange=initial_upperRange, stayIn_initialRange=stayIn_initialRange,algorithmParameter_initialLambda=algorithmParameter_initialLambda, algorithmParameter_gamma=algorithmParameter_gamma, num_minimizersToFind=num_minimizersToFind, num_iteration=num_iteration, saveLog=saveLog, runName=runName, textMemo=textMemo, algorithmVersion=algorithmVersion, initialIterateMatrix=initialIterateMatrix, targetMatrix=targetMatrix,ParameterNames=ParameterNames,ReparameterizationDef=ReparameterizationDef,lowerBound=lowerBound, upperBound=upperBound) testCGNMinput=TRUE nonlinearFunctionCanTakeMatrixInput=FALSE if(testCGNMinput){ testCGNMinput_time_start=Sys.time() nonlinearFunctionCanTakeMatrixInput=CGNM_input_test(nonlinearFunction, targetVector, initial_lowerRange, initial_upperRange ) testCGNMinput_time_end=Sys.time() # message(paste("Initial estimation of required computation time:",round((testCGNMinput_time_end-testCGNMinput_time_start)/3*num_minimizersToFind*num_iteration/60),"min")) message(paste("CGNM iteration should finish before:",Sys.time()+(testCGNMinput_time_end-testCGNMinput_time_start)/3*num_minimizersToFind*num_iteration)) } showIntermetiateResults=FALSE targetVector=as.numeric(targetVector) validTarget_vec=!is.na(targetVector) targetVector[!validTarget_vec]=0 if(dimTargetMatrix[1]==0){ targetMatrix=repmat(matrix(targetVector,nrow=1), num_minimizersToFind,1) }else{ targetMatrix=targetMatrix_in targetMatrix[,!validTarget_vec]=0 } X_ul_in=t(matrix(c(initial_lowerRange,initial_upperRange), nrow=length(initial_upperRange))) saveFolderName="CGNM_log" if(runName=="TIME"){ runName=as.character( Sys.time()) runSetting$runName=runName } if(runName!=""){ saveFolderName=paste0(saveFolderName,"_",runName) } if(saveLog){ dir.create(saveFolderName) } X_history=c() Y_history=c() algorithmParameter_gamma=algorithmParameter_gamma method <- 'CGNM'# set algorithm name for the log files) descriptionText <- paste0(toString(num_minimizersToFind),'samples_initLambda',toString(algorithmParameter_initialLambda),'_distanceOrder',toString(algorithmParameter_gamma)) # setting the name depending on if we do restart or not. Restart is an # experimental feature so I suggest not to use at this point. num_parameters <- dim(X_ul_in)[2] num_observations = length(targetVector) timeOneParaTook <- c() # tic ############################ # 1) Pre-iteration process # ############################ X <- matrix(0,num_minimizersToFind,num_parameters)# initialize X (We keep the same naming for the variables as in the manuscript) Y <- matrix(1,num_minimizersToFind,num_observations)# initialize Y Y_new <- matrix(1,num_minimizersToFind,num_observations)# initialize Y lambda_vec <- matrix(1,1,num_minimizersToFind)*algorithmParameter_initialLambda# initialise regularisation parameter lambda residual_history <- c()# initialise a matrix that stores the SSR for all iterations ## Generate initial cluster is_alive <- matrix(0,1,num_minimizersToFind)# initialise the vector to keep track of if the nonlinear function was able to be evaluated at the randomly generated x. userDefInitialIterateAvailable=(dimInitialIterateMatrix[1]>0) # repeat the randomsampling of x until num_minimizersToFind of 'valid' x are sampled. Where we consider x to be valid if f(x) can be evaluated. while(sum(is_alive)<num_minimizersToFind){ # random sampling of X if(userDefInitialIterateAvailable){ X_temp=initialIterateMatrix userDefInitialIterateAvailable=FALSE }else{ X_temp <- matlabRand(num_minimizersToFind,length(X_ul_in[1,]))*(repmat(X_ul_in[2,],num_minimizersToFind,1)-repmat(X_ul_in[1,],num_minimizersToFind,1))+repmat(X_ul_in[1,],num_minimizersToFind,1) } # if(algorithmVersion==4){ # minX=initial_lowerRange # maxX=initial_upperRange # # X_temp=round((X_temp)%*%diag(1/(maxX-minX))*numDiscretization)%*%diag((maxX-minX))/numDiscretization # } # replace the rows of X matrix with randomly sampled x if x was # determined to be not valid X[is_alive==0,]=X_temp[is_alive==0,] # if("parallel" %in% tolower((.packages()))){ # # Y_list=mclapply(split(X, rep(seq(1:nrow(X)),ncol(X))), tryCatch_nonlinearFunction, num_observations=num_observations, nonlinearFunction=nonlinearFunction, mc.cores = 4) # # }else{ toCompute_X=X[is_alive==0,] if(sum(is_alive==0)==1){ toCompute_X=matrix(toCompute_X,nrow=1,ncol = length(toCompute_X)) } if(nonlinearFunctionCanTakeMatrixInput){ toCompute_Y=tryCatch_nonlinearFunction(toCompute_X, num_observations=num_observations, nonlinearFunction=nonlinearFunction, validTarget=validTarget_vec) }else{ Y_list=lapply(split(toCompute_X, rep(seq(1:nrow(toCompute_X)),ncol(toCompute_X))), tryCatch_nonlinearFunction, num_observations=num_observations, nonlinearFunction=nonlinearFunction, validTarget=validTarget_vec) toCompute_Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) } Y[is_alive==0,]=toCompute_Y # if(nonlinearFunctionCanTakeMatrixInput){ # Y=tryCatch_nonlinearFunction(X, num_observations=num_observations, nonlinearFunction=nonlinearFunction, validTarget=validTarget_vec) # }else{ # Y_list=lapply(split(X, rep(seq(1:nrow(X)),ncol(X))), tryCatch_nonlinearFunction, num_observations=num_observations, nonlinearFunction=nonlinearFunction, validTarget=validTarget_vec) # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) # } #} # compute SSR residual <- matlabSum((Y-targetMatrix)^2,2) if(showIntermetiateResults){ message(residual) } # determine valid x (in this case if the residual is not a number # we consider x to be valid) is_alive=is.nan(residual)==0 message(paste("Generating initial cluster.",sum(is_alive),"out of",num_minimizersToFind,"done")) if(sum(is_alive)==0){ message("It is most likely that either nonlinearfunction definition, intial range selection, or targetVector definition is incorrect. Stop the CGNM run and fix the issue.") } } # store the residual vector for the initial cluster into the # residual_history matrix residual_history <- rbind(residual_history,residual) # store the matrix X and Y to X_history and Y_history, respectively X_history[[1]] <- X Y_history[[1]] <- Y lambda_history <- t(as.matrix(lambda_vec)) prev_residual <- residual for (k in seq(1,num_iteration)){ iteration_time_start=Sys.time() if(algorithmParameter_gamma=="AUTO"){ if(k<50){ gamma_toUse=2^round(k/15) }else{ gamma_toUse=2^round(50/15) } }else{ gamma_toUse=algorithmParameter_gamma } if(algorithmVersion==3){ out_temp <- main_iteration_version3_fast(X, Y, lambda_vec, X_ul_in[1,], X_ul_in[2,], targetMatrix, gamma_toUse, stayIn_initialRange=stayIn_initialRange, keepInitialDistribution = keepInitialDistribution) # }else if(algorithmVersion==3.1){ # # switchIndex=10 # # if(k==switchIndex){ # lambda_vec <- matrix(1,1,num_minimizersToFind)*algorithmParameter_initialLambda# initialise regularisation parameter lambda # } # # if(k>=switchIndex){ # best_index=which(residual==min(residual)) # bestFit=Y[best_index,] # targetMatrix=repmat(bestFit,dim(X)[1],1) # # targetMatrix[best_index,]=targetVector # } # # out_temp <- main_iteration_version3_fast(X, Y, lambda_vec, X_ul_in[1,], X_ul_in[2,], targetMatrix, gamma_toUse) # # }else if(algorithmVersion==4){ # # if(k==10){ # lambda_vec <- matrix(1,1,num_minimizersToFind)*algorithmParameter_initialLambda# initialise regularisation parameter lambda # } # # if(k<10){ # out_temp <- main_iteration_version4(X, Y, lambda_vec, X_ul_in[1,], X_ul_in[2,], targetMatrix, gamma_toUse, numDiscretization=numDiscretization) # }else{ # # out_temp <- main_iteration_version3(X, Y, lambda_vec, X_ul_in[1,], X_ul_in[2,], targetMatrix, gamma_toUse) # } # }else{ out_temp <- main_iteration_version1(X, Y, lambda_vec, X_ul_in[1,], X_ul_in[2,], targetMatrix, gamma_toUse) } X_new=X+out_temp # if("parallel" %in% tolower((.packages()))){ # Y_list=mclapply(split(X_new, rep(seq(1:nrow(X_new)),ncol(X_new))), tryCatch_nonlinearFunction, num_observations=num_observations, nonlinearFunction=nonlinearFunction, mc.cores = 4) # # }else{ toUpdate=(lambda_vec<(algorithmParameter_initialLambda*10^10)) X_toCompute=X_new[toUpdate,] if(sum(toUpdate)==1){ X_toCompute=matrix(X_toCompute,nrow=1,ncol = dim(X_new)[2]) } Y_new=Y if(sum(toUpdate)>0){ if(nonlinearFunctionCanTakeMatrixInput){ Y_computed=tryCatch_nonlinearFunction(X_toCompute, num_observations=num_observations, nonlinearFunction=nonlinearFunction, validTarget=validTarget_vec) }else{ Y_list=lapply(split(X_toCompute, rep(seq(1:nrow(X_toCompute)),ncol(X_toCompute))), tryCatch_nonlinearFunction, num_observations=num_observations, nonlinearFunction=nonlinearFunction, validTarget=validTarget_vec) Y_computed=t(matrix(unlist(Y_list),ncol=length(Y_list))) } Y_new[toUpdate,]=Y_computed }else{ break } #} if(showIntermetiateResults){ message(Y_new) } residual_new <- t(matlabSum((Y_new-targetMatrix)^2,2)) residual <- prev_residual for (i in seq(1,num_minimizersToFind)){ if (!is.nan(residual_new[i])&&!is.nan(prev_residual[i])&&(prev_residual[i]>residual_new[i])){ X[i,] <- X[i,]+out_temp[i,] residual[i] <- residual_new[i] Y[i,] <- Y_new[i,] lambda_vec[i] <- lambda_vec[i]/10 } else { if(lambda_vec[i]<(algorithmParameter_initialLambda*10^10)){ lambda_vec[i] <- lambda_vec[i]*10 } } } X_history[[k+1]] <- X Y_history[[k+1]] <- Y lambda_history <- cbind(lambda_history,t(lambda_vec)) residual_history <- cbind(residual_history,residual) prev_residual <- residual # message(matlabMedian(residual_history,1)) message(paste0("Iteration:",toString(k)," Median sum of squares residual=", toString(median(prev_residual)))) if(saveLog){ CGNM_result=list(X=X,Y=Y,residual_history=residual_history, initialX=X_history[[1]], initialY=Y_history[[1]],lambda_history=lambda_history, runSetting=runSetting ) save(file=paste0(saveFolderName,'/iteration_',toString(k),'.RDATA'), CGNM_result) } iteration_time_end=Sys.time() if(k==1){ message(paste("Rough estimation of remaining computation time:",round(as.numeric(iteration_time_end-iteration_time_start, units="mins")*(num_iteration-k)*10)/10,"min")) } if(k%%10==1){ message(paste("CGNM iteration estimated to finish at:",(iteration_time_end-iteration_time_start)*(num_iteration-k)+Sys.time())) } if(median(prev_residual)==0){ break } } CGNM_result=list(X=X,Y=Y,residual_history=residual_history, lambda_history=lambda_history, runSetting=runSetting, initialX=X_history[[1]], initialY=Y_history[[1]] ) if(saveLog){ save(file=paste0(saveFolderName,'/iteration_final.RDATA'), CGNM_result) } CGNM_end_time=Sys.time() message(paste("CGNM computation time: ",round(as.numeric(CGNM_end_time-CGNM_start_time, units="mins")*10)/10,"min")) return(CGNM_result) } main_iteration_version4 <- function(X_in, Y_in, lambdaV, minX, maxX, targetMatrix, algorithmParameter_gamma, numDiscretization=100){ #// aliveIndex: index of the parameter set in the cluster whose SSR have decreased in the previous iteration. #// X_in: all set of parameters in the cluster from the previous itaration X_in[i][j]: jth parameter value in the ith parameter set in the cluster #// Y_in: all set of the function value (solution of the forward problem, f(parameter)) from the previous iteration # global algorithmParameter_gamma ##//STEP 1: Linear Approximation YisNotNaN <- matrix(1,dim(X_in)[1],1) for (k in 1:dim(Y_in)[1]){ for (i in 1:dim(Y_in)[2]){ if (is.nan(Y_in[k,i])|is.infinite(Y_in[k,i])){ YisNotNaN[k] <- 0 } } } #// Linear approximation will be A x + y_o \approx f(x) = y for all y in Y matrix (stored in each row of Y matrix) #// This can be written as A_with_y0 X_append_one_column^T \approx Y^T kmean_result=optimal_kmeans(X_in) notAcceptableClusters=as.numeric(which(table(kmean_result$cluster)==1,arr.ind = TRUE)) relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) rec_relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) for (i in seq(1,dim(X_in)[1])){ relative_distance[i,i] <- 0 rec_relative_distance[i,i] <- 0 if(i>1){ for (j in seq(1,(i-1))){ relative_distance[i,j] <- 0 relative_distance[j,i] <- 0 if(kmean_result$cluster[i]==kmean_result$cluster[j]){ for (k in seq(1,dim(X_in)[2])){ relative_distance[i,j] <- relative_distance[i,j]+((X_in[i,k]-X_in[j,k])/(sd(X_in[kmean_result$cluster==kmean_result$cluster[j],k])))^2 } }else{ relative_distance[i,j] =0 } if (YisNotNaN[i]==1&YisNotNaN[j]==1&relative_distance[i,j]!=0){ relative_distance[j,i] <- relative_distance[i,j] rec_relative_distance[i,j] <- 1/relative_distance[i,j] rec_relative_distance[j,i] <- rec_relative_distance[i,j] } else { relative_distance[i,j] <- 0 rec_relative_distance[i,j] <- 0 rec_relative_distance[j,i] <- 0 } } } } # Linear approximation will be A_with_y0 X_append_one_column^T \approx Y^T now solve it for A_with_y0 # We solve for \min || X_append_one_column A_with_y0^T - Y ||_F # use CGNR and solve each row of A_with_y0 (i.e., each column of A_with_y0^T) A <- matrix(0, dim(Y_in)[2],dim(X_in)[2]) deltaX <- matrix(0, dim(X_in)[1],dim(X_in)[2]) delta_X <- matrix(0, dim(X_in)[1],dim(X_in)[2]) tempOnes <- matrix(1, dim(Y_in)[1],1) for (k in seq(1,dim(Y_in)[1])){ if(lambdaV[k]<10^10&(!(kmean_result$cluster[k] %in% notAcceptableClusters))){ ## 2-1): Construct weighted linear approximation of the nonlinear function for (i in seq(1,dim(X_in)[1])){ deltaX[i,] <- X_in[i,]-X_in[k,] } # use the following code if one wishes to use MASS's matrix # inverse function (ginv) instead of CGNR rec_relative_distance_tempvec=(rec_relative_distance[ ,k])^algorithmParameter_gamma rec_relative_distance_tempvec[is.infinite(rec_relative_distance_tempvec)]=max(rec_relative_distance_tempvec[!is.infinite(rec_relative_distance_tempvec)]) AT=t(diag(rec_relative_distance_tempvec)%*%deltaX) ATAinv=MASS::ginv(AT%*%t(AT)) delta_Y=Y_in for(i in seq(1, dim(Y_in)[2])){ delta_Y[,i]=Y_in[,i]-Y_in[k,i] } A=t(ATAinv%*%(AT%*%diag((rec_relative_distance[ ,k])^algorithmParameter_gamma)%*%(delta_Y))) # for (i in seq(1,dim(Y_in)[2])){ # A[i,] <- CGNR_ATAx_ATb_with_weight(deltaX,Y_in[ ,i]-Y_in[k,i]*tempOnes,rec_relative_distance[ ,k]^algorithmParameter_gamma) # } ## 2-2): Solve for x that minimizes the resodual using the weighted linear approximation delta_X[k,] <- CGNR_ATAx_ATb_with_reg(A, t(targetMatrix[k,]-Y_in[k,]),lambdaV[k]) } } delta_X=round((delta_X)%*%diag(1/(maxX-minX))*numDiscretization)%*%diag((maxX-minX))/numDiscretization return(delta_X) } main_iteration_version3 <- function(X_in, Y_in, lambdaV, minX, maxX, targetMatrix, algorithmParameter_gamma){ #// aliveIndex: index of the parameter set in the cluster whose SSR have decreased in the previous iteration. #// X_in: all set of parameters in the cluster from the previous itaration X_in[i][j]: jth parameter value in the ith parameter set in the cluster #// Y_in: all set of the function value (solution of the forward problem, f(parameter)) from the previous iteration # global algorithmParameter_gamma ##//STEP 1: Linear Approximation YisNotNaN <- matrix(1,dim(X_in)[1],1) for (k in 1:dim(Y_in)[1]){ for (i in 1:dim(Y_in)[2]){ if (is.nan(Y_in[k,i])|is.infinite(Y_in[k,i])){ YisNotNaN[k] <- 0 } } } #// Linear approximation will be A x + y_o \approx f(x) = y for all y in Y matrix (stored in each row of Y matrix) #// This can be written as A_with_y0 X_append_one_column^T \approx Y^T X_in_forkmeans=X_in kmean_result=optimal_kmeans(X_in_forkmeans) while(min(table(kmean_result$cluster))<dim(X_in)[2]){ kmean_result=kmeans(col_normalize(X_in_forkmeans),centers = length(unique(kmean_result$cluster))-1) } notAcceptableClusters=as.numeric(which(table(kmean_result$cluster)==1,arr.ind = TRUE)) relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) rec_relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) for (i in seq(1,dim(X_in)[1])){ relative_distance[i,i] <- 0 rec_relative_distance[i,i] <- 0 if(i>1){ for (j in seq(1,(i-1))){ relative_distance[i,j] <- 0 relative_distance[j,i] <- 0 if(kmean_result$cluster[i]==kmean_result$cluster[j]){ for (k in seq(1,dim(X_in)[2])){ relative_distance[i,j] <- relative_distance[i,j]+((X_in[i,k]-X_in[j,k])/(sd(X_in[kmean_result$cluster==kmean_result$cluster[j],k])))^2 } }else{ relative_distance[i,j] =0 } if (YisNotNaN[i]==1&YisNotNaN[j]==1&relative_distance[i,j]!=0){ relative_distance[j,i] <- relative_distance[i,j] rec_relative_distance[i,j] <- 1/relative_distance[i,j] rec_relative_distance[j,i] <- rec_relative_distance[i,j] } else { relative_distance[i,j] <- 0 rec_relative_distance[i,j] <- 0 rec_relative_distance[j,i] <- 0 } } } } # Linear approximation will be A_with_y0 X_append_one_column^T \approx Y^T now solve it for A_with_y0 # We solve for \min || X_append_one_column A_with_y0^T - Y ||_F # use CGNR and solve each row of A_with_y0 (i.e., each column of A_with_y0^T) A <- matrix(0, dim(Y_in)[2],dim(X_in)[2]) deltaX <- matrix(0, dim(X_in)[1],dim(X_in)[2]) delta_X <- matrix(0, dim(X_in)[1],dim(X_in)[2]) tempOnes <- matrix(1, dim(Y_in)[1],1) for (k in seq(1,dim(Y_in)[1])){ if(lambdaV[k]<10^10&(!(kmean_result$cluster[k] %in% notAcceptableClusters))){ ## 2-1): Construct weighted linear approximation of the nonlinear function for (i in seq(1,dim(X_in)[1])){ deltaX[i,] <- X_in[i,]-X_in[k,] } # use the following code if one wishes to use MASS's matrix # inverse function (ginv) instead of CGNR rec_relative_distance_tempvec=(rec_relative_distance[ ,k])^algorithmParameter_gamma rec_relative_distance_tempvec[is.infinite(rec_relative_distance_tempvec)]=max(rec_relative_distance_tempvec[!is.infinite(rec_relative_distance_tempvec)]) AT=t(diag(rec_relative_distance_tempvec)%*%deltaX) ATAinv=MASS::ginv(AT%*%t(AT)) delta_Y=Y_in for(i in seq(1, dim(Y_in)[2])){ delta_Y[,i]=Y_in[,i]-Y_in[k,i] } A=t(ATAinv%*%(AT%*%diag((rec_relative_distance[ ,k])^algorithmParameter_gamma)%*%(delta_Y))) # for (i in seq(1,dim(Y_in)[2])){ # A[i,] <- CGNR_ATAx_ATb_with_weight(deltaX,Y_in[ ,i]-Y_in[k,i]*tempOnes,rec_relative_distance[ ,k]^algorithmParameter_gamma) # } ## 2-2): Solve for x that minimizes the resodual using the weighted linear approximation delta_X[k,] <- CGNR_ATAx_ATb_with_reg(A, t(targetMatrix[k,]-Y_in[k,]),lambdaV[k]) } } return(delta_X) } main_iteration_version1 <- function(X_in, Y_in, lambdaV, minX, maxX, targetMatrix, algorithmParameter_gamma){ #// aliveIndex: index of the parameter set in the cluster whose SSR have decreased in the previous iteration. #// X_in: all set of parameters in the cluster from the previous itaration X_in[i][j]: jth parameter value in the ith parameter set in the cluster #// Y_in: all set of the function value (solution of the forward problem, f(parameter)) from the previous iteration # global algorithmParameter_gamma ##//STEP 1: Linear Approximation YisNotNaN <- matrix(1,dim(X_in)[1],1) for (k in 1:dim(Y_in)[1]){ for (i in 1:dim(Y_in)[2]){ if (is.nan(Y_in[k,i])|is.infinite(Y_in[k,i])){ YisNotNaN[k] <- 0 } } } #// Linear approximation will be A x + y_o \approx f(x) = y for all y in Y matrix (stored in each row of Y matrix) #// This can be written as A_with_y0 X_append_one_column^T \approx Y^T x_width <- maxX-minX relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) rec_relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) for (i in seq(1,dim(X_in)[1])){ relative_distance[i,i] <- 0 rec_relative_distance[i,i] <- 0 if(i>1){ for (j in seq(1,(i-1))){ relative_distance[i,j] <- 0 relative_distance[j,i] <- 0 for (k in seq(1,dim(X_in)[2])){ relative_distance[i,j] <- relative_distance[i,j]+((X_in[i,k]-X_in[j,k])/x_width[k])^2 } if (YisNotNaN[i]==1&YisNotNaN[j]==1){ relative_distance[i,j] <- (relative_distance[i,j]) relative_distance[j,i] <- relative_distance[i,j] rec_relative_distance[i,j] <- 1/relative_distance[i,j] rec_relative_distance[j,i] <- rec_relative_distance[i,j] } else { relative_distance[i,j] <- 0 rec_relative_distance[i,j] <- 0 rec_relative_distance[j,i] <- 0 } } } } # Linear approximation will be A_with_y0 X_append_one_column^T \approx Y^T now solve it for A_with_y0 # We solve for \min || X_append_one_column A_with_y0^T - Y ||_F # use CGNR and solve each row of A_with_y0 (i.e., each column of A_with_y0^T) A <- matrix(0, dim(Y_in)[2],dim(X_in)[2]) deltaX <- matrix(0, dim(X_in)[1],dim(X_in)[2]) delta_X <- matrix(0, dim(X_in)[1],dim(X_in)[2]) tempOnes <- matrix(1, dim(Y_in)[1],1) for (k in seq(1,dim(Y_in)[1])){ if(lambdaV[k]<10^10){ ## 2-1): Construct weighted linear approximation of the nonlinear function for (i in seq(1,dim(X_in)[1])){ deltaX[i,] <- X_in[i,]-X_in[k,] } # use the following code if one wishes to use matlab's matrix # inverse function instead of CGNR # AT=(diag((rec_relative_distance[ ,k]).^algorithmParameter_gamma)*deltaX)'; # ATAinv=inv(AT*AT'); # A=(ATAinv*(AT*diag((rec_relative_distance[ ,k]).^algorithmParameter_gamma)*(Y_in-repmat(Y_in[k,],dim(Y_in)[1],1))))'; for (i in seq(1,dim(Y_in)[2])){ A[i,] <- CGNR_ATAx_ATb_with_weight(deltaX,Y_in[ ,i]-Y_in[k,i]*tempOnes,rec_relative_distance[ ,k]^algorithmParameter_gamma) } ## 2-2): Solve for x that minimizes the resodual using the weighted linear approximation delta_X[k,] <- CGNR_ATAx_ATb_with_reg(A, t(targetMatrix[k,]-Y_in[k,]),lambdaV[k]) } } return(delta_X) } main_iteration_version3_fast <- function(X_in_original, Y_in, lambdaV_original, minX_original, maxX_original, targetMatrix, algorithmParameter_gamma, stayIn_initialRange=FALSE, keepInitialDistribution=NA){ validXcol=!(col_max(X_in_original)==col_min(X_in_original)) X_in=X_in_original[,validXcol] lambdaV=lambdaV_original minX=minX_original[validXcol] maxX=maxX_original[validXcol] #// aliveIndex: index of the parameter set in the cluster whose SSR have decreased in the previous iteration. #// X_in: all set of parameters in the cluster from the previous itaration X_in[i][j]: jth parameter value in the ith parameter set in the cluster #// Y_in: all set of the function value (solution of the forward problem, f(parameter)) from the previous iteration # global algorithmParameter_gamma ##//STEP 1: Linear Approximation YisNotNaN <- matrix(1,dim(X_in)[1],1) for (k in 1:dim(Y_in)[1]){ for (i in 1:dim(Y_in)[2]){ if (is.nan(Y_in[k,i])|is.infinite(Y_in[k,i])){ YisNotNaN[k] <- 0 } } } #// Linear approximation will be A x + y_o \approx f(x) = y for all y in Y matrix (stored in each row of Y matrix) #// This can be written as A_with_y0 X_append_one_column^T \approx Y^T kmean_result=optimal_kmeans(X_in) while(min(table(kmean_result$cluster))<dim(X_in)[2]|min(kmean_result$withinss)==0){ kmean_result=kmeans(col_normalize(X_in),centers = length(unique(kmean_result$cluster))-1) } notAcceptableClusters=as.numeric(which(table(kmean_result$cluster)==1,arr.ind = TRUE)) relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) rec_relative_distance <- matrix(0,dim(X_in)[1],dim(X_in)[1]) numClusters=length(unique(kmean_result$cluster)) sdMatrix=matrix(0, dim(X_in)[2],dim(X_in)[1]) for(i in seq(1, numClusters)){ for(j in seq(1, dim(X_in)[2])){ sdMatrix[j,kmean_result$cluster==i]=sd(X_in[kmean_result$cluster==i,j]) } } tX_in=t(X_in) for (i in seq(1,dim(X_in)[1])){ # relative_distance[i,i] <- 0 # rec_relative_distance[i,i] <- 0 useIndex=(kmean_result$cluster==kmean_result$cluster[i]) relative_distance[i,useIndex] = colSums(((tX_in[,useIndex]-tX_in[,i])/(sdMatrix[,useIndex]))^2) # if(i>1){ # # # # # for (j in seq(1,(i-1))){ # # relative_distance[i,j] <- 0 # # relative_distance[j,i] <- 0 # # if(kmean_result$cluster[i]==kmean_result$cluster[j]){ # # for (k in seq(1,dim(X_in)[2])){ # relative_distance[i,j] <- relative_distance[i,j]+((X_in[i,k]-X_in[j,k])/(sd(X_in[kmean_result$cluster==kmean_result$cluster[j],k])))^2 # } # }else{ # relative_distance[i,j] =0 # } # # if (YisNotNaN[i]==1&YisNotNaN[j]==1&relative_distance[i,j]!=0){ # # relative_distance[j,i] <- relative_distance[i,j] # rec_relative_distance[i,j] <- 1/relative_distance[i,j] # rec_relative_distance[j,i] <- rec_relative_distance[i,j] # } else { # relative_distance[i,j] <- 0 # rec_relative_distance[i,j] <- 0 # rec_relative_distance[j,i] <- 0 # } # # } # # } # } rec_relative_distance=1/relative_distance rec_relative_distance[relative_distance==0]=0 # Linear approximation will be A_with_y0 X_append_one_column^T \approx Y^T now solve it for A_with_y0 # We solve for \min || X_append_one_column A_with_y0^T - Y ||_F # use CGNR and solve each row of A_with_y0 (i.e., each column of A_with_y0^T) A <- matrix(0, dim(Y_in)[2],dim(X_in)[2]) deltaX <- matrix(0, dim(X_in)[1],dim(X_in)[2]) delta_X <- matrix(0, dim(X_in)[1],dim(X_in)[2]) tempOnes <- matrix(1, dim(Y_in)[1],1) for (k in seq(1,dim(Y_in)[1])){ if(lambdaV[k]<10^10&(!(kmean_result$cluster[k] %in% notAcceptableClusters))){ ## 2-1): Construct weighted linear approximation of the nonlinear function for (i in seq(1,dim(X_in)[1])){ deltaX[i,] <- X_in[i,]-X_in[k,] } # use the following code if one wishes to use MASS's matrix # inverse function (ginv) instead of CGNR A <- tryCatch( { rec_relative_distance_tempvec=(rec_relative_distance[ ,k])^algorithmParameter_gamma rec_relative_distance_tempvec[is.infinite(rec_relative_distance_tempvec)]=max(c(10^10,rec_relative_distance_tempvec[!is.infinite(rec_relative_distance_tempvec)])) AT=t(diag(rec_relative_distance_tempvec)%*%deltaX) ATAinv=MASS::ginv(AT%*%t(AT)) delta_Y=Y_in for(i in seq(1, dim(Y_in)[2])){ delta_Y[,i]=Y_in[,i]-Y_in[k,i] } A=t(ATAinv%*%(AT%*%diag((rec_relative_distance[ ,k])^algorithmParameter_gamma)%*%(delta_Y))); if(!is.na(keepInitialDistribution)&&length(keepInitialDistribution)==dim(X_in)[2]){ A[,keepInitialDistribution]=0 } (A) }, error=function(cond) { print("using CGNR") for (i in seq(1,dim(Y_in)[2])){ A[i,] <- CGNR_ATAx_ATb_with_weight(deltaX,Y_in[ ,i]-Y_in[k,i]*tempOnes,rec_relative_distance[ ,k]^algorithmParameter_gamma) } (A) }, warning=function(cond) { rec_relative_distance_tempvec=(rec_relative_distance[ ,k])^algorithmParameter_gamma rec_relative_distance_tempvec[is.infinite(rec_relative_distance_tempvec)]=max(c(10^10,rec_relative_distance_tempvec[!is.infinite(rec_relative_distance_tempvec)])) AT=t(diag(rec_relative_distance_tempvec)%*%deltaX) ATAinv=MASS::ginv(AT%*%t(AT)) delta_Y=Y_in for(i in seq(1, dim(Y_in)[2])){ delta_Y[,i]=Y_in[,i]-Y_in[k,i] } A=t(ATAinv%*%(AT%*%diag((rec_relative_distance[ ,k])^algorithmParameter_gamma)%*%(delta_Y))); if(!is.na(keepInitialDistribution)&&length(keepInitialDistribution)==dim(X_in)[2]){ A[,keepInitialDistribution]=0 } (A) }, finally={ } ) # # <<<<<<< Updated upstream # ======= # AT=t(diag(rec_relative_distance_tempvec)%*%deltaX) # # ATAinv=MASS::ginv(AT%*%t(AT)) # # delta_Y=Y_in # # for(i in seq(1, dim(Y_in)[2])){ # delta_Y[,i]=Y_in[,i]-Y_in[k,i] # } # # A=t(ATAinv%*%(AT%*%diag((rec_relative_distance[ ,k])^algorithmParameter_gamma)%*%(delta_Y))); # # if(!is.na(keepInitialDistribution)[1]&&length(keepInitialDistribution)==dim(X_in)[2]){ # A[,keepInitialDistribution]=0 # } # # # for (i in seq(1,dim(Y_in)[2])){ # # A[i,] <- CGNR_ATAx_ATb_with_weight(deltaX,Y_in[ ,i]-Y_in[k,i]*tempOnes,rec_relative_distance[ ,k]^algorithmParameter_gamma) # # } # >>>>>>> Stashed changes ## 2-2): Solve for x that minimizes the resodual using the weighted linear approximation delta_X[k,] <- CGNR_ATAx_ATb_with_reg(A, t(targetMatrix[k,]-Y_in[k,]),lambdaV[k]) if(stayIn_initialRange){ scaling_vector=rep(1,dim(delta_X)[2]) scaling_vector[((delta_X[k,])/(minX-X_in[k,]))>1]=((delta_X[k,])/(minX-X_in[k,])*2)[((delta_X[k,])/(minX-X_in[k,]))>1] scaling_vector[((delta_X[k,])/(maxX-X_in[k,]))>1]=((delta_X[k,])/(maxX-X_in[k,])*2)[((delta_X[k,])/(maxX-X_in[k,]))>1] #scaling_vector[((delta_X[k,])/(minX-X_in[k,]))>1]=((delta_X[k,])/(minX-X_in[k,])*1.0001)[((delta_X[k,])/(minX-X_in[k,]))>1] #scaling_vector[((delta_X[k,])/(maxX-X_in[k,]))>1]=((delta_X[k,])/(maxX-X_in[k,])*1.0001)[((delta_X[k,])/(maxX-X_in[k,]))>1] delta_X[k,]=delta_X[k,]/scaling_vector } } } delta_X_out=matrix(0, ncol = dim(X_in_original)[2], nrow = dim(X_in_original)[1]) delta_X_out[,validXcol]=delta_X return(delta_X_out) } CGNR_ATAx_ATb <- function(A, b){#solves A^TA x = A^Tb num_max_iter <- dim(A)[2] x <- matrix(0,dim(A)[2],1) if (dim(A)[1]==length(b)){ r <- t(A)%*%b p <- r innerProd_rr_old <- dot(r,r) for (i in seq(1,num_max_iter)){ tempVector <- A%*%p tempD <- dot(tempVector,tempVector) if (is.na(tempD)||tempD==0){ break } alpha <- innerProd_rr_old/tempD x <- x+alpha*p r <- r-alpha*t(A)%*%tempVector innerProd_rr_new <- dot(r,r) beta <- innerProd_rr_new/innerProd_rr_old innerProd_rr_old <- innerProd_rr_new if (innerProd_rr_old==0){ break } p <- r+beta*p } } else { message('CGNR error: matrix A and vetor b sizes do not make sense.') message(paste('Size of A: ', toString(dim(A)[1]))) message('Size of b: ', toString(length(b))) } return(x) } CGNR_ATAx_ATb_with_weight=function(A, b, weight){ for (i in seq(1,min(length(weight),dim(A)[1]))){ if (weight[i]==0){ for (j in 1:dim(A)[2]){ A[i,j] <- 0 } b[i] <- 0 } else { A[i,] <- weight[i]*A[i,] b[i] <- weight[i]*b[i] } } return(CGNR_ATAx_ATb(A[weight!=0,],b[weight!=0])) } CGNR_ATAx_ATb_with_reg=function(A, b, lambda){# //solves (A^TA+lambda I) x = A^Tb num_max_iter <- dim(A)[1] x <- matrix(0,dim(A)[2],1) if (dim(A)[1]==length(b)){ r <- t(A)%*%t(b) p <- r innerProd_rr_old <- dot(r,r) AtA <- t(A)%*%A AtA_lambda <- AtA for (i in seq(1,dim(AtA)[1])){ AtA_lambda[i,i] <- AtA_lambda[i,i]+lambda } for (i in seq(1,num_max_iter)){ tempD <- dot(p,(AtA_lambda%*%p)) if (is.na(tempD)||tempD==0){ break } alpha <- innerProd_rr_old/tempD x <- x+alpha*p r <- r-alpha*(AtA_lambda%*%p) innerProd_rr_new <- dot(r,r) beta <- innerProd_rr_new/innerProd_rr_old innerProd_rr_old <- innerProd_rr_new if (innerProd_rr_old==0){ break } p <- r+beta*p } } else { message('CGNR with reg error: matrix A and vetor b sizes do not make sense.') message(paste('Size of A: ', toString(dim(A)[1]))) message(paste('Size of b: ', toString(length(b)))) } return(x) } CGNR_ATAx_ATb_with_regVec=function(A, b, lambda){# //solves (A^TA+lambda_vec) x = A^Tb num_max_iter <- dim(A)[1] x <- matrix(0,dim(A)[2],1) if (dim(A)[1]==length(b)){ r <- t(A)%*%t(b) p <- r innerProd_rr_old <- dot(r,r) AtA <- t(A)%*%A AtA_lambda <- AtA for (i in seq(1,dim(AtA)[1])){ AtA_lambda[i,i] <- AtA_lambda[i,i]+lambda[i] } for (i in seq(1,num_max_iter)){ tempD <- dot(p,(AtA_lambda%*%p)) if (is.na(tempD)||tempD==0){ break } alpha <- innerProd_rr_old/tempD x <- x+alpha*p r <- r-alpha*(AtA_lambda%*%p) innerProd_rr_new <- dot(r,r) beta <- innerProd_rr_new/innerProd_rr_old innerProd_rr_old <- innerProd_rr_new if (innerProd_rr_old==0){ break } p <- r+beta*p } } else { message('CGNR with reg error: matrix A and vetor b sizes do not make sense.') message(paste('Size of A: ', toString(dim(A)[1]))) message(paste('Size of b: ', toString(length(b)))) } return(x) } #' @title Cluster_Gauss_Newton_Bootstrap_method #' @description Conduct residual resampling bootstrap analyses using CGNM. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param nonlinearFunction (required input) \emph{A function with input of a vector x of real number of length n and output a vector y of real number of length m.} In the context of model fitting the nonlinearFunction is \strong{the model}. Given the CGNM does not assume the uniqueness of the minimizer, m can be less than n. Also CGNM does not assume any particular form of the nonlinear function and also does not require the function to be continuously differentiable (see Appendix D of our publication for an example when this function is discontinuous). #' @param ... Further arguments to be supplied to nonlinearFunction #' @param num_bootstrapSample (default: 200) \emph{A positive integer} number of bootstrap samples to generate. #' @param indicesToUseAsInitialIterates (default: NA) \emph{A vector of integers} indices to use for initial iterate of the bootstrap analyses. For CGNM bootstrap, we use the parameters found by CGNM as the initial iterates, here you can manually spccify which of the approximate minimizers that was found by CGNM (where the CGNM computation result is given as CGNM_result file) to use as initial iterates. (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @return list of a matrix X, Y,residual_history, initialX, bootstrapX, bootstrapY as well as a list runSetting. #' \enumerate{\item X, Y, residual_history, initialX: identical to what was given as CGNM_result. #' \item X: \emph{a num_bootstrapSample by n matrix} which stores the the X values that was sampled using residual resampling bootstrap analyses (In terms of model fitting this is the parameter combinations with variabilities that represent \strong{parameter estimation uncertainties}.). #' \item Y: \emph{a num_bootstrapSample by m matrix} which stores the nonlinearFunction evaluated at the corresponding bootstrap analyses results in matrix bootstrapX above. In the context of model fitting each row corresponds to \strong{the model simulations}. #' \item runSetting: identical to what is given as CGNM_result but in addition including num_bootstrapSample and indicesToUseAsInitialIterates.} #' @examples #' ##lip-flop kinetics (an example known to have two distinct solutions) #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, num_iteration = 10, num_minimizersToFind = 100, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' lowerBound=rep(0,3), ParameterNames=c("Ka","V1","CL_2"), saveLog = FALSE) #' #' CGNM_bootstrap=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, #' nonlinearFunction=model_analytic_function, num_bootstrapSample=100) #' #' plot_paraDistribution_byHistogram(CGNM_bootstrap) #' #' @export #' @import stats MASS Cluster_Gauss_Newton_Bootstrap_method <- function(CGNM_result, nonlinearFunction, ..., num_bootstrapSample=200, indicesToUseAsInitialIterates=NA){ cutoff_pvalue=0.05 numParametersIncluded=NA useAcceptedApproximateMinimizers=TRUE targetVector=CGNM_result$runSetting$targetVector initial_lowerRange=CGNM_result$runSetting$initial_lowerRange initial_upperRange=CGNM_result$runSetting$initial_upperRange num_minimizersToFind=CGNM_result$runSetting$num_minimizersToFind num_iteration=CGNM_result$runSetting$num_iteration saveLog=CGNM_result$runSetting$saveLog runName=CGNM_result$runSetting$runName textMemo=CGNM_result$runSetting$textMemo algorithmParameter_initialLambda=CGNM_result$runSetting$algorithmParameter_initialLambda algorithmParameter_gamma=CGNM_result$runSetting$algorithmParameter_gamma algorithmVersion=CGNM_result$runSetting$algorithmVersion ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef ParameterNames=CGNM_result$runSetting$ParameterNames # CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction, targetVector, initial_lowerRange, initial_upperRange , num_minimizersToFind, num_iteration, saveLog, runName, textMemo,algorithmParameter_initialLambda, algorithmParameter_gamma, algorithmVersion, initialIterateMatrix) if(is.na(indicesToUseAsInitialIterates[1])){ acceptParaIndex=acceptedIndices(CGNM_result, cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers) }else{ acceptParaIndex=indicesToUseAsInitialIterates[indicesToUseAsInitialIterates<=dim(CGNM_result$X)[1]] } if(length(acceptParaIndex)<100){ message(paste("WARNING: only", length(acceptParaIndex) ,"acceptable parameters found, we will run bootstrap with top 50 parameters.")) #if(length(acceptParaIndex)<10){ # stop("Too few accepted parameters.") #} acceptParaIndex=acceptedIndices(CGNM_result, cutoff_pvalue, 100, FALSE) } bootstrapTargetMatrix=matrix(NA, nrow=num_bootstrapSample, ncol = dim(CGNM_result$Y)[2]) bootstrapInitialMatrix=matrix(NA, nrow=num_bootstrapSample, ncol = dim(CGNM_result$X)[2]) residual_vec=targetVector-CGNM_result$Y[acceptParaIndex[1],] residual_vec=residual_vec[!is.na(residual_vec)] for(i in seq(1,num_bootstrapSample)){ bootstrapTargetMatrix[i,]=targetVector+sample(residual_vec,length(residual_vec), replace = TRUE) } bootstrapInitialMatrix=CGNM_result$X[sample(acceptParaIndex,num_bootstrapSample,replace=TRUE),] stayIn_initRange=FALSE if(!is.null(CGNM_result$runSetting$stayIn_initialRange)){ stayIn_initRange=CGNM_result$runSetting$stayIn_initialRange } lowerBound=NA if(!is.null(CGNM_result$runSetting$lowerBound)){ lowerBound=CGNM_result$runSetting$lowerBound } upperBound=NA if(!is.null(CGNM_result$runSetting$upperBound)){ upperBound=CGNM_result$runSetting$upperBound } ParameterNames=NA if(!is.null(CGNM_result$runSetting$ParameterNames)){ ParameterNames=CGNM_result$runSetting$ParameterNames } LB_index=(!is.na(as.numeric(lowerBound)))&is.na(upperBound) UB_index=(!is.na(as.numeric(upperBound)))&is.na(lowerBound) BB_index=(!is.na(as.numeric(lowerBound)))&(!is.na(as.numeric(upperBound))) lowerBoundMatrix=repmat(lowerBound[BB_index],numrows = num_minimizersToFind ,numcol = 1) upperBoundMatrix=repmat(upperBound[BB_index],numrows = num_minimizersToFind ,numcol = 1) nonlinearFunction_varTrans=function(x,...){ if(is.vector(x)){ theta=x theta[LB_index]=exp(x[LB_index])-lowerBound[LB_index] theta[UB_index]=-exp(x[UB_index])+upperBound[UB_index] theta[BB_index]=(upperBound[BB_index]-lowerBound[BB_index])*(exp(x[BB_index])/(exp(x[BB_index])+1))+lowerBound[BB_index] }else{ theta=x theta[,LB_index]=exp(x[,LB_index])-repmat(lowerBound[LB_index],numrows = dim(x)[1] ,numcol = 1) theta[,UB_index]=-exp(x[,UB_index])+repmat(upperBound[UB_index],numrows = dim(x)[1] ,numcol = 1) theta[,BB_index]=(upperBoundMatrix-lowerBoundMatrix)[seq(1,dim(x)[1]),]*(exp(x[,BB_index])/(exp(x[,BB_index])+1))+lowerBoundMatrix[seq(1,dim(x)[1]),] } nonlinearFunction(theta,...) } CGNM_bootstrap_result=Cluster_Gauss_Newton_method_core(nonlinearFunction = nonlinearFunction_varTrans, targetVector = targetVector, initial_lowerRange = initial_lowerRange, initial_upperRange = initial_upperRange, stayIn_initialRange = stayIn_initRange, num_minimizersToFind = num_minimizersToFind, num_iteration = num_iteration, saveLog = saveLog, runName = paste0(runName,"bootstrap"), textMemo = textMemo,algorithmParameter_initialLambda = algorithmParameter_initialLambda, algorithmParameter_gamma = algorithmParameter_gamma, algorithmVersion = algorithmVersion, initialIterateMatrix=bootstrapInitialMatrix, targetMatrix = bootstrapTargetMatrix, ParameterNames=ParameterNames,ReparameterizationDef = ReparameterizationDef,keepInitialDistribution = FALSE) CGNM_result$bootstrapX=CGNM_bootstrap_result$X CGNM_result$bootstrapY=CGNM_bootstrap_result$Y CGNM_result$runSetting$num_bootstrapSample=num_bootstrapSample CGNM_result$runSetting$indicesToUseAsInitialIterates=indicesToUseAsInitialIterates CGNM_result$runSetting$targetMatrix=bootstrapTargetMatrix ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef ParameterNames=CGNM_result$runSetting$ParameterNames out=data.frame(CGNM_result$bootstrapX) names(out)=paste0("x",seq(1,dim(out)[2])) bootstrapTheta=data.frame(row.names = seq(1,dim(out)[1])) for(i in seq(1,length(ParameterNames))){ bootstrapTheta[,ParameterNames[i]]=with(out, eval(parse(text=ReparameterizationDef[i]))) } CGNM_result$bootstrapTheta=bootstrapTheta if(CGNM_result$runSetting$saveLog){ save(file =paste0("CGNM_log_",runName,"bootstrap/CGNM_bootstrapResult.RDATA"),CGNM_result) } return(CGNM_result) }
/scratch/gouwar.j/cran-all/cranData/CGNM/R/Cluster_Gauss_Newton_method.R
## TODO make autodiagnosis function, is Lambda all big? Is the minimum SSR parameter set within the initial range? ## TODO implement best parameter ## TODO implement worst accepted parameter makeParaDistributionPlotDataFrame=function(CGNM_result, indicesToInclude=NA, cutoff_pvalue=0.05, numParametersIncluded=NA, ParameterNames=NA, ReparameterizationDef=NA, useAcceptedApproximateMinimizers=TRUE){ ReReparameterise=TRUE Re_ReparameterizationDef=ReparameterizationDef Re_ParameterNames=ParameterNames if(is.null(CGNM_result$runSetting$ReparameterizationDef)){ ReparameterizationDef=paste0("x", seq(1,length(CGNM_result$runSetting$initial_lowerRange))) }else{ ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef } if(length(CGNM_result$runSetting$ParameterNames)!=length(ReparameterizationDef)){ ParameterNames=ReparameterizationDef }else{ ParameterNames=CGNM_result$runSetting$ParameterNames } if(is.na(Re_ReparameterizationDef)[1]){ ReReparameterise=FALSE } if(length(Re_ParameterNames)!=length(Re_ReparameterizationDef)|is.na(Re_ParameterNames)[1]){ Re_ParameterNames= Re_ReparameterizationDef } Kind_iter=NULL X_value=NULL cluster=NULL freeParaValues=data.frame() SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] # if(is.na(ParameterNames[1])|length(ParameterNames)!=length(ReparameterizationDef)){ # ParameterNames=ReparameterizationDef # } # # if(is.na(ParameterNames[1])){ # ParameterNames=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) # ReparameterizationDef=ParameterNames # } if(!is.na(indicesToInclude[1])){ useIndecies_b=seq(1,dim(CGNM_result$X)[1])%in%indicesToInclude }else if(useAcceptedApproximateMinimizers){ useIndecies_b=acceptedIndices_binary(CGNM_result,cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers) }else{ if(is.na(numParametersIncluded)|numParametersIncluded>dim(CGNM_result$X)[1]){ useIndecies_b=rep(TRUE, dim(CGNM_result$X)[1]) }else{ useIndecies_b=(SSR_vec<=sort(SSR_vec)[numParametersIncluded]) } } initialX_df=CGNM_result$initialX colnames(initialX_df)=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) initialX_df=data.frame(initialX_df) repara_initialX_df=data.frame(row.names = seq(1,dim(initialX_df)[1])) temp_repara_initialX_df=data.frame(row.names = seq(1,dim(initialX_df)[1])) for(i in seq(1,length(ParameterNames))){ temp_repara_initialX_df[,ParameterNames[i]]=with(initialX_df, eval(parse(text=ReparameterizationDef[i]))) } if(ReReparameterise){ for(i in seq(1,length(Re_ParameterNames))){ repara_initialX_df[,Re_ParameterNames[i]]=with(temp_repara_initialX_df, eval(parse(text=Re_ReparameterizationDef[i]))) } }else{ repara_initialX_df=temp_repara_initialX_df } finalX_df=CGNM_result$X colnames(finalX_df)=paste0("x",seq(1,dim(CGNM_result$X)[2])) finalX_df=data.frame(finalX_df) repara_finalX_df=data.frame(row.names = seq(1,dim(finalX_df)[1])) temp_repara_finalX_df=data.frame(row.names = seq(1,dim(finalX_df)[1])) for(i in seq(1,length(ParameterNames))){ temp_repara_finalX_df[,ParameterNames[i]]=with(finalX_df, eval(parse(text=ReparameterizationDef[i]))) } if(ReReparameterise){ for(i in seq(1,length(Re_ParameterNames))){ repara_finalX_df[,Re_ParameterNames[i]]=with(temp_repara_finalX_df, eval(parse(text=Re_ReparameterizationDef[i]))) } }else{ repara_finalX_df=temp_repara_finalX_df } for(i in seq(1,dim(repara_initialX_df)[2])){ freeParaValues=rbind(freeParaValues, data.frame(Name=names(repara_initialX_df)[i],X_value=repara_initialX_df[,i], Kind_iter="Initial", SSR=NA)) } for(i in seq(1,dim(repara_finalX_df)[2])){ freeParaValues=rbind(freeParaValues, data.frame(Name=names(repara_finalX_df)[i],X_value=repara_finalX_df[useIndecies_b,i], Kind_iter="Final Accepted", SSR=SSR_vec[useIndecies_b])) } if(!is.null(CGNM_result$bootstrapX)){ bootstrapX_df=CGNM_result$bootstrapX colnames(bootstrapX_df)=paste0("x",seq(1,dim(CGNM_result$bootstrapX)[2])) bootstrapX_df=data.frame(bootstrapX_df) repara_bootstrapX_df=data.frame(row.names = seq(1,dim(bootstrapX_df)[1])) temp_repara_bootstrapX_df=data.frame(row.names = seq(1,dim(bootstrapX_df)[1])) for(i in seq(1,length(ParameterNames))){ temp_repara_bootstrapX_df[,ParameterNames[i]]=with(bootstrapX_df, eval(parse(text=ReparameterizationDef[i]))) } if(ReReparameterise){ for(i in seq(1,length(Re_ParameterNames))){ repara_bootstrapX_df[,Re_ParameterNames[i]]=with(temp_repara_bootstrapX_df, eval(parse(text=Re_ReparameterizationDef[i]))) } }else{ repara_bootstrapX_df=temp_repara_bootstrapX_df } for(i in seq(1,dim(repara_bootstrapX_df)[2])){ freeParaValues=rbind(freeParaValues, data.frame(Name=names(repara_bootstrapX_df)[i],X_value=repara_bootstrapX_df[,i], Kind_iter="Bootstrap",SSR=NA)) } freeParaValues$Kind_iter=factor(freeParaValues$Kind_iter, levels = c("Initial", "Final Accepted", "Bootstrap")) }else{ freeParaValues$Kind_iter=factor(freeParaValues$Kind_iter, levels = c("Initial", "Final Accepted")) } freeParaValues$Name=factor(freeParaValues$Name, levels = names(repara_finalX_df)) return(freeParaValues) } #' @title acceptedMaxSSR #' @description #' CGNM find multiple sets of minimizers of the nonlinear least squares (nls) problem by solving nls from various initial iterates. Although CGNM is shown to be robust compared to other conventional multi-start algorithms, not all initial iterates minimizes successfully. By assuming sum of squares residual (SSR) follows the chai-square distribution we first reject the approximated minimiser who SSR is statistically significantly worse than the minimum SSR found by the CGNM. Then use elbow-method (a heuristic often used in mathematical optimisation to balance the quality and the quantity of the solution found) to find the "acceptable" maximum SSR. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param cutoff_pvalue (default: 0.05) \emph{A number} defines the rejection p-value for the first stage of acceptable computational result screening. #' @param numParametersIncluded (default: NA) \emph{A natural number} defines the number of parameter sets to be included in the assessment of the acceptable parameters. If set NA then use all the parameters found by the CGNM. #' @param useAcceptedApproximateMinimizers (default: TRUE) \emph{TRUE or FALSE} If true then use chai-square and elbow method to choose maximum accepted SSR. If false returnsnumParametersIncluded-th smallest SSR (or if numParametersIncluded=NA then returns the largest SSR). #' @param algorithm (default: 2) \emph{1 or 2} specify the algorithm used for obtain accepted approximate minimizers. (Algorithm 1 uses elbow method, Algorithm 2 uses Grubbs' Test for Outliers.) #' @return \emph{A positive real number} that is the maximum sum of squares residual (SSR) the algorithm has selected to accept. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' acceptedMaxSSR(CGNM_result) #' @export acceptedMaxSSR=function(CGNM_result, cutoff_pvalue=0.05, numParametersIncluded=NA, useAcceptedApproximateMinimizers=TRUE, algorithm=2){ SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] if(useAcceptedApproximateMinimizers){ if(algorithm==2){ numInInitialSet=dim(CGNM_result$residual_history)[1] orderedIndex=order(SSR_vec) bestIndex=topIndices(CGNM_result,1) ptest_vec=c() cumResidualFromBestFit=c() pvalue_vec=c() for(i in seq(2,numInInitialSet)){ numInSample=i-1 cumResidualFromBestFit=c(cumResidualFromBestFit, sum((CGNM_result$Y[orderedIndex[i-1],]-CGNM_result$Y[orderedIndex[i],]))) if(numInSample>3){ tStat=qt(1-cutoff_pvalue/(2*numInSample), df=(numInSample-2)) #test statistics from Grubbs' Test for Outliers testStatistics=(numInSample-1)/sqrt(numInSample)*sqrt(tStat^2/(numInSample-2+tStat^2)) #test hypothesis where the null hypothesis is that the last added sum of residual is outlier compared to the ones that are already accepted ptest_vec=c(ptest_vec,abs(mean(cumResidualFromBestFit)-cumResidualFromBestFit[length(cumResidualFromBestFit)])/sd(cumResidualFromBestFit)>testStatistics) }else{ ptest_vec=c(ptest_vec,FALSE) } } acceptMaxSSR=sort(SSR_vec)[which(ptest_vec)[1]+1] }else{ min_R=min(SSR_vec) minIndex=which(SSR_vec==min_R)[1] targetVector=as.numeric(CGNM_result$runSetting$targetVector) targetVector[is.na(targetVector)]=0 residual_vec=CGNM_result$Y[minIndex,]-targetVector acceptMaxSSR=max(qchisq(1-cutoff_pvalue, df=length(residual_vec)) *(sd(residual_vec))^2+min_R, sqrt(sqrt(.Machine$double.eps))) accept_index=which(SSR_vec<acceptMaxSSR) accept_vec=as.vector(SSR_vec<acceptMaxSSR) numAccept=sum(accept_vec, na.rm = TRUE) if(!is.na(numParametersIncluded)&(sum(accept_vec)>numParametersIncluded)){ sortedAcceptedSSR=sort(SSR_vec[accept_vec])[seq(1,numParametersIncluded)] }else{ sortedAcceptedSSR=sort(SSR_vec[accept_vec]) } trapizoido_area=c() for(i in seq(1,length(sortedAcceptedSSR)-1)) trapizoido_area=c(trapizoido_area, (sortedAcceptedSSR[1]+sortedAcceptedSSR[i])*i+(sortedAcceptedSSR[i+1]+sortedAcceptedSSR[length(sortedAcceptedSSR)])*(length(sortedAcceptedSSR)-i)) strictMaxAcceptSSR=sortedAcceptedSSR[which(trapizoido_area==min(trapizoido_area))] accept_index=which(SSR_vec<strictMaxAcceptSSR) accept_vec=as.vector(SSR_vec<strictMaxAcceptSSR) numAccept=sum(accept_vec, na.rm = TRUE) acceptMaxSSR=strictMaxAcceptSSR } }else if(is.na(numParametersIncluded)|numParametersIncluded>length(SSR_vec)){ acceptMaxSSR=max(SSR_vec, na.rm = TRUE) }else{ acceptMaxSSR=sort(SSR_vec)[numParametersIncluded] } acceptMaxSSR=max(acceptMaxSSR, min(SSR_vec)+sqrt(.Machine$double.eps)) return(acceptMaxSSR) } #' @title acceptedApproximateMinimizers #' @description #' CGNM find multiple sets of minimizers of the nonlinear least squares (nls) problem by solving nls from various initial iterates. Although CGNM is shown to be robust compared to other conventional multi-start algorithms, not all initial iterates minimizes successfully. By assuming sum of squares residual (SSR) follows the chai-square distribution we first reject the approximated minimiser who SSR is statistically significantly worse than the minimum SSR found by the CGNM. Then use elbow-method (a heuristic often used in mathematical optimisation to balance the quality and the quantity of the solution found) to find the "acceptable" maximum SSR. This function outputs the acceptable approximate minimizers of the nonlinear least squares problem found by the CGNM. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param cutoff_pvalue (default: 0.05) \emph{A number} defines the rejection p-value for the first stage of acceptable computational result screening. #' @param numParametersIncluded (default: NA) \emph{A natural number} defines the number of parameter sets to be included in the assessment of the acceptable parameters. If set NA then use all the parameters found by the CGNM. #' @param useAcceptedApproximateMinimizers (default: TRUE) \emph{TRUE or FALSE} If true then use chai-square and elbow method to choose maximum accepted SSR. If false returns the parameters upto numParametersIncluded-th smallest SSR (or if numParametersIncluded=NA then use all the parameters found by the CGNM). #' @param algorithm (default: 2) \emph{1 or 2} specify the algorithm used for obtain accepted approximate minimizers. (Algorithm 1 uses elbow method, Algorithm 2 uses Grubbs' Test for Outliers.) #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @return \emph{A dataframe} that each row stores the accepted approximate minimizers found by CGNM. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' acceptedApproximateMinimizers(CGNM_result) #' @export acceptedApproximateMinimizers=function(CGNM_result, cutoff_pvalue=0.05, numParametersIncluded=NA, useAcceptedApproximateMinimizers=TRUE, algorithm=2, ParameterNames=NA, ReparameterizationDef=NA){ out=CGNM_result$X[acceptedIndices(CGNM_result, cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers, algorithm=algorithm),] out=data.frame(out) colnames(out)=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ ParameterNames=CGNM_result$runSetting$ParameterNames } if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef } if(is.na(ParameterNames[1])|length(ParameterNames)!=length(ReparameterizationDef)){ ParameterNames=ReparameterizationDef } if(is.na(ParameterNames[1])){ ParameterNames=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) ReparameterizationDef=ParameterNames } repara_finalX_df=data.frame(row.names = seq(1,dim(out)[1])) for(i in seq(1,length(ParameterNames))){ repara_finalX_df[,ParameterNames[i]]=with(out, eval(parse(text=ReparameterizationDef[i]))) } return(repara_finalX_df) } #' @title acceptedIndices #' @description #' CGNM find multiple sets of minimizers of the nonlinear least squares (nls) problem by solving nls from various initial iterates. Although CGNM is shown to be robust compared to other conventional multi-start algorithms, not all initial iterates minimizes successfully. By assuming sum of squares residual (SSR) follows the chai-square distribution we first reject the approximated minimiser who SSR is statistically significantly worse than the minimum SSR found by the CGNM. Then use elbow-method (a heuristic often used in mathematical optimisation to balance the quality and the quantity of the solution found) to find the "acceptable" maximum SSR. This function outputs the indices of acceptable approximate minimizers of the nonlinear least squares problem found by the CGNM. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param cutoff_pvalue (default: 0.05) \emph{A number} defines the rejection p-value for the first stage of acceptable computational result screening. #' @param numParametersIncluded (default: NA) \emph{A natural number} defines the number of parameter sets to be included in the assessment of the acceptable parameters. If set NA then use all the parameters found by the CGNM. #' @param useAcceptedApproximateMinimizers (default: TRUE) \emph{TRUE or FALSE} If true then use chai-square and elbow method to choose maximum accepted SSR. If false returns the parameters upto numParametersIncluded-th smallest SSR (or if numParametersIncluded=NA then use all the parameters found by the CGNM). #' @param algorithm (default: 2) \emph{1 or 2} specify the algorithm used for obtain accepted approximate minimizers. (Algorithm 1 uses elbow method, Algorithm 2 uses Grubbs' Test for Outliers.) #' @return \emph{A vector of natural number} that contains the indices of accepted approximate minimizers found by CGNM. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' acceptedIndices(CGNM_result) #' @export acceptedIndices=function(CGNM_result, cutoff_pvalue=0.05, numParametersIncluded=NA, useAcceptedApproximateMinimizers=TRUE, algorithm=2){ acceptMaxSSR_value=acceptedMaxSSR(CGNM_result, cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers, algorithm=algorithm) SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] return(which(SSR_vec<=acceptMaxSSR_value)) } #' @title topIndices #' @description #' CGNM find multiple sets of minimizers of the nonlinear least squares (nls) problem by solving nls from various initial iterates. Although CGNM is shown to be robust compared to other conventional multi-start algorithms, not all initial iterates minimizes successfully. One can visually inspect rank v.s. SSR plot and manually choose number of best fit acceptable parameters. By using this function "topIndices", we can obtain the indices of the "numTopIndices" best fit parameter combinations. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param numTopIndices (required input) \emph{An integer} . #' @return \emph{A vector of natural number} that contains the indices of accepted approximate minimizers found by CGNM. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' topInd=topIndices(CGNM_result, 10) #' #' ## This gives top 10 approximate minimizers #' CGNM_result$X[topInd,] #' @export topIndices=function(CGNM_result, numTopIndices){ SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] sortedSSR=sort(SSR_vec) outIndices=which(SSR_vec<=sortedSSR[numTopIndices]) return(outIndices) } #' @title acceptedIndices_binary #' @description #' CGNM find multiple sets of minimizers of the nonlinear least squares (nls) problem by solving nls from various initial iterates. Although CGNM is shown to be robust compared to other conventional multi-start algorithms, not all initial iterates minimizes successfully. By assuming sum of squares residual (SSR) follows the chai-square distribution we first reject the approximated minimiser who SSR is statistically significantly worse than the minimum SSR found by the CGNM. Then use elbow-method (a heuristic often used in mathematical optimisation to balance the quality and the quantity of the solution found) to find the "acceptable" maximum SSR. This function outputs the indices of acceptable approximate minimizers of the nonlinear least squares problem found by the CGNM. (note that acceptedIndices(CGNM_result) is equal to seq(1,length(acceptedIndices_binary(CGNM_result)))[acceptedIndices_binary(CGNM_result)]) #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param cutoff_pvalue (default: 0.05) \emph{A number} defines the rejection p-value for the first stage of acceptable computational result screening. #' @param numParametersIncluded (default: NA) \emph{A natural number} defines the number of parameter sets to be included in the assessment of the acceptable parameters. If set NA then use all the parameters found by the CGNM. #' @param useAcceptedApproximateMinimizers (default: TRUE) \emph{TRUE or FALSE} If true then use chai-square and elbow method to choose maximum accepted SSR. If false returns the indicies upto numParametersIncluded-th smallest SSR (or if numParametersIncluded=NA then use all the parameters found by the CGNM). #' @param algorithm (default: 2) \emph{1 or 2} specify the algorithm used for obtain accepted approximate minimizers. (Algorithm 1 uses elbow method, Algorithm 2 uses Grubbs' Test for Outliers.) #' @return \emph{A vector of TRUE and FALSE} that indicate if the each of the approximate minimizer found by CGNM is acceptable or not. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' acceptedIndices_binary(CGNM_result) #' @export acceptedIndices_binary=function(CGNM_result, cutoff_pvalue=0.05, numParametersIncluded=NA, useAcceptedApproximateMinimizers=TRUE, algorithm=2){ acceptMaxSSR_value=acceptedMaxSSR(CGNM_result, cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers, algorithm= algorithm) SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] return(as.vector(SSR_vec<=acceptMaxSSR_value)) } #' @title plot_Rank_SSR #' @description #' Make SSR v.s. rank plot. This plot is often used to visualize the maximum accepted SSR. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param indicesToInclude (default: NA) \emph{A vector of integers} indices to include in the plot (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @return \emph{A ggplot object} of SSR v.s. rank. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' plot_Rank_SSR(CGNM_result) #' @export #' @import ggplot2 plot_Rank_SSR=function(CGNM_result, indicesToInclude=NA){ SSR_value=NULL cutoff_pvalue=0.05 numParametersIncluded=NA useAcceptedApproximateMinimizers=TRUE is_accepted=NULL SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] if(!is.na(indicesToInclude[1])){ if(sum(indicesToInclude)<=dim(CGNM_result$X)[1]&length(indicesToInclude)==dim(CGNM_result$X)[1]){ acceptedIndices_b=indicesToInclude }else{ acceptedIndices_b=seq(1,dim(CGNM_result$X)[1]) %in% indicesToInclude } }else{ acceptedIndices_b=acceptedIndices_binary(CGNM_result,cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers) } numAccept=sum(acceptedIndices_b) acceptMaxSSR=max(SSR_vec[acceptedIndices_b])#acceptedMaxSSR(CGNM_result,cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers) min_R=min(SSR_vec) plot_df=data.frame(SSR_value=SSR_vec, rank=rank(SSR_vec, na.last=TRUE, ties.method = "last"), is_accepted=acceptedIndices_b) ggplot2::ggplot(plot_df, ggplot2::aes(x=rank,y=SSR_value, colour=is_accepted))+ggplot2::geom_point()+ggplot2::coord_cartesian(ylim=c(0,acceptMaxSSR*2))+ggplot2::geom_vline(xintercept = numAccept, color="grey")+ ggplot2::annotate(geom="text", x=numAccept, y=acceptMaxSSR*0.5, label=paste("Accepted: ",numAccept,"\n Accepted max SSR: ",formatC(acceptMaxSSR, format = "g", digits = 3)),angle = 90, color="black")+ ggplot2::annotate(geom="text", x=length(SSR_vec)*0.1, y=min_R*1.1, label=paste("min SSR: ",formatC(min_R, format = "g", digits = 3)), color="black")+ylab("SSR") } #' @title plot_paraDistribution_byViolinPlots #' @description #' Make violin plot to compare the initial distribution and distribition of the accepted approximate minimizers found by the CGNM. Bars in the violin plots indicates the interquartile range. The solid line connects the interquartile ranges of the initial distribution and the distribution of the accepted approximate minimizer at the final iterate. The blacklines connets the minimums and maximums of the initial distribution and the distribution of the accepted approximate minimizer at the final iterate. The black dots indicate the median. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param indicesToInclude (default: NA) \emph{A vector of integers} indices to include in the plot (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = rep(0.01,3), initial_upperRange = rep(100,3), #' lowerBound=rep(0,3), ParameterNames = c("Ka","V1","CL"), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' plot_paraDistribution_byViolinPlots(CGNM_result) #' plot_paraDistribution_byViolinPlots(CGNM_result, #' ReparameterizationDef=c("log10(Ka)","log10(V1)","log10(CL)")) #' #' #' @export #' @import ggplot2 plot_paraDistribution_byViolinPlots=function(CGNM_result, indicesToInclude=NA, ParameterNames=NA, ReparameterizationDef=NA){ # if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ # ParameterNames=CGNM_result$runSetting$ParameterNames # } # # # if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ # ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef # } Kind_iter=NULL X_value=NULL cutoff_pvalue=0.05 numParametersIncluded=NA useAcceptedApproximateMinimizers=TRUE freeParaValues=makeParaDistributionPlotDataFrame(CGNM_result, indicesToInclude, cutoff_pvalue, numParametersIncluded, ParameterNames, ReparameterizationDef, useAcceptedApproximateMinimizers) p<-ggplot2::ggplot(freeParaValues,ggplot2::aes(x=Kind_iter,y=X_value))+ggplot2::facet_wrap(Name~., scales = "free") p+ggplot2::geom_violin(trim=T,fill="#999999",linetype="blank",alpha=I(1/2))+ ggplot2::stat_summary(geom="pointrange",fun = median, fun.min = function(x) quantile(x,probs=0.25), fun.max = function(x) quantile(x,probs=0.75), size=0.5,alpha=.5)+ ggplot2::stat_summary(geom="line",fun = function(x) quantile(x,probs=0), ggplot2::aes(group=1),size=0.5,alpha=.3,linetype=2)+ ggplot2::stat_summary(geom="line",fun = function(x) quantile(x,probs=1), ggplot2::aes(group=1),size=0.5,alpha=.3,linetype=2)+ ggplot2::stat_summary(geom="line",fun = function(x) quantile(x,probs=0.25), ggplot2::aes(group=1),size=0.5,alpha=.3)+ ggplot2::stat_summary(geom="line",fun = function(x) quantile(x,probs=0.75), ggplot2::aes(group=1),size=0.5,alpha=.3)+ ggplot2::theme(legend.position="none",axis.text.x = element_text(angle = 25, hjust = 1))+xlab("")+ylab("Value") } #' @title plot_paraDistribution_byHistogram #' @description #' Make histograms to visualize the initial distribution and distribition of the accepted approximate minimizers found by the CGNM. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param indicesToInclude (default: NA) \emph{A vector of integers} indices to include in the plot (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @param bins (default: 30) \emph{A natural number} Number of bins used for plotting histogram. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #' #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = rep(0.01,3), initial_upperRange = rep(100,3), #' lowerBound=rep(0,3), ParameterNames = c("Ka","V1","CL"), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' plot_paraDistribution_byHistogram(CGNM_result) #' plot_paraDistribution_byHistogram(CGNM_result, #' ReparameterizationDef=c("log10(Ka)","log10(V1)","log10(CL)")) #' #' @export #' @import ggplot2 plot_paraDistribution_byHistogram=function(CGNM_result, indicesToInclude=NA, ParameterNames=NA, ReparameterizationDef=NA, bins=30){ # if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ # # ParameterNames=CGNM_result$runSetting$ParameterNames # } # # # if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ # ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef # } X_value=NULL Kind_iter=NULL cutoff_pvalue=0.05 numParametersIncluded=NA useAcceptedApproximateMinimizers=TRUE freeParaValues=makeParaDistributionPlotDataFrame(CGNM_result, indicesToInclude, cutoff_pvalue, numParametersIncluded, ParameterNames, ReparameterizationDef, useAcceptedApproximateMinimizers) p<-ggplot2::ggplot(freeParaValues,ggplot2::aes(X_value))+ggplot2::geom_histogram(bins = bins)+ggplot2::facet_grid(Kind_iter~Name, scales = "free")+xlab("") p } #' @title plot_profileLikelihood #' @description #' Draw profile likelihood surface using the function evaluations conducted during CGNM computation. Note plot_SSRsurface can only be used when log is saved by setting saveLog=TRUE option when running Cluster_Gauss_Newton_method(). The grey horizontal line is the threshold for 95% pointwise confidence interval. #' @param logLocation (required input) \emph{A string} of folder directory where CGNM computation log files exist. #' @param alpha (default: 0.25) \emph{a number between 0 and 1} level of significance (used to draw horizontal line on the profile likelihood). #' @param numBins (default: NA) \emph{A positive integer} SSR surface is plotted by finding the minimum SSR given one of the parameters is fixed and then repeat this for various values. numBins specifies the number of different parameter values to fix for each parameter. (if set NA the number of bins are set as num_minimizersToFind/10) #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @param showInitialRange (default: TRUE) \emph{TRUE or FALSE} if TRUE then the initial range appears in the plot. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog=TRUE) #' #' plot_profileLikelihood("CGNM_log") #' } #' @export #' @import ggplot2 plot_profileLikelihood=function(logLocation, alpha=0.25, numBins=NA, ParameterNames=NA, ReparameterizationDef=NA, showInitialRange=TRUE){ plot_SSRsurface(logLocation, alpha= alpha, profile_likelihood=TRUE, numBins=numBins, ParameterNames=ParameterNames, ReparameterizationDef=ReparameterizationDef, showInitialRange=showInitialRange) } #' @title table_profileLikelihoodConfidenceInterval #' @description #' Make table of confidence intervals that are approximated from the profile likelihood. First inspect profile likelihood plot and make sure the plot is smooth and has good enough resolution and the initial range is appropriate. Do not report this table without checking the profile likelihood plot. #' @param logLocation (required input) \emph{A string or a list of strings} of folder directory where CGNM computation log files exist. #' @param alpha (default: 0.25) \emph{a number between 0 and 1} level of significance used to derive the confidence interval. #' @param numBins (default: NA) \emph{A positive integer} SSR surface is plotted by finding the minimum SSR given one of the parameters is fixed and then repeat this for various values. numBins specifies the number of different parameter values to fix for each parameter. (if set NA the number of bins are set as num_minimizersToFind/10) #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @param pretty (default: FALSE) \emph{TRUE or FALSE} if true then the publication ready table will be an output #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog=TRUE) #' #' table_profileLikelihoodConfidenceInterval("CGNM_log") #' } #' @export table_profileLikelihoodConfidenceInterval=function(logLocation, alpha=0.25, numBins=NA, ParameterNames=NA, ReparameterizationDef=NA, pretty=FALSE){ print("WARNING: ALWAYS first inspect the profile likelihood plot (using plot_profileLikelihood()) and then use this table, DO NOT USE this table by itself.") boundValue=NULL individual=NULL label=NULL minSSR=NULL negative2LogLikelihood=NULL newvalue=NULL parameterName=NULL reparaXinit=NULL value=NULL data=makeSSRsurfaceDataset(logLocation, TRUE, numBins, NA, ParameterNames, ReparameterizationDef, FALSE) likelihoodSurfacePlot_df=data$likelihoodSurfacePlot_df minSSR=min(likelihoodSurfacePlot_df$negative2LogLikelihood) likelihoodSurfacePlot_df$belowSignificance=(likelihoodSurfacePlot_df$negative2LogLikelihood-qchisq(1-alpha,1)-minSSR<0) cutOffValue=qchisq(1-alpha,1)+minSSR paraKind=unique(likelihoodSurfacePlot_df$parameterName) upperBound_vec=c() lowerBound_vec=c() min_vec=c() identifiability_vec=c() prettyString_vec=c() for(para_nu in paraKind){ dataframe_nu=subset(likelihoodSurfacePlot_df,parameterName==para_nu) minIndex=which(dataframe_nu$negative2LogLikelihood==minSSR) upperBoundIndex=which(max(dataframe_nu$value[dataframe_nu$belowSignificance])==dataframe_nu$value) lowerBoundIndex=which(min(dataframe_nu$value[dataframe_nu$belowSignificance])==dataframe_nu$value) identifiability="identifiable" prettyString="" if(length(minIndex)>1){ min_vec=c(min_vec, median(dataframe_nu$value[minIndex] )) identifiability="Not identifiable" }else{ min_vec=c(min_vec, dataframe_nu$value[minIndex] ) } if(upperBoundIndex==length(dataframe_nu$value)){ upperBound=paste0(">",dataframe_nu$value[upperBoundIndex]) identifiability="Not identifiable" prettyString=paste(prettyString,paste0(">",signif(dataframe_nu$value[upperBoundIndex],2),")")) }else{ diffValue=(dataframe_nu$value[upperBoundIndex]-dataframe_nu$value[upperBoundIndex+1])/(dataframe_nu$negative2LogLikelihood[upperBoundIndex]-dataframe_nu$negative2LogLikelihood[upperBoundIndex+1])*(cutOffValue-dataframe_nu$negative2LogLikelihood[upperBoundIndex]) upperBound=dataframe_nu$value[upperBoundIndex]+diffValue # upperBound=(dataframe_nu$value[upperBoundIndex]+dataframe_nu$value[upperBoundIndex+1])/2 prettyString=paste(prettyString,paste0(signif(upperBound,2),"]")) } if(lowerBoundIndex==1){ lowerBound=paste0("<",dataframe_nu$value[lowerBoundIndex]) identifiability="Not identifiable" prettyString=paste(paste0("(<",signif(dataframe_nu$value[lowerBoundIndex],2),","), prettyString) }else{ diffValue=(dataframe_nu$value[lowerBoundIndex]-dataframe_nu$value[lowerBoundIndex-1])/(dataframe_nu$negative2LogLikelihood[lowerBoundIndex]-dataframe_nu$negative2LogLikelihood[lowerBoundIndex-1])*(cutOffValue-dataframe_nu$negative2LogLikelihood[lowerBoundIndex]) lowerBound=dataframe_nu$value[lowerBoundIndex]+diffValue # lowerBound=(dataframe_nu$value[lowerBoundIndex]+dataframe_nu$value[lowerBoundIndex-1])/2 prettyString=paste(paste0("[",signif(lowerBound,2),","), prettyString) } upperBound_vec=c(upperBound_vec,upperBound) lowerBound_vec=c(lowerBound_vec,lowerBound) prettyString_vec=c(prettyString_vec,prettyString) identifiability_vec=c(identifiability_vec,identifiability) } out_df=data.frame(parameterName=paraKind,CI_lower=lowerBound_vec,best=min_vec,CI_upper=upperBound_vec, parameter_identifiability=identifiability_vec) out_df[out_df$parameter_identifiability=="Not identifiable","best"]=NA pretty_df=data.frame(parameterName=paraKind,value=paste(signif(as.numeric(out_df$best), digits = 3), prettyString_vec), parameter_identifiability=identifiability_vec) names(pretty_df)=c("", paste0("best-fit [",alpha*100,"percentile, ", (1-alpha)*100,"percentile ]"),"identifiability") names(out_df)=c("", paste(alpha*100,"percentile"), "best-fit", paste((1-alpha)*100,"percentile"),"identifiability") if(pretty){ return(pretty_df) }else{ return(out_df) } } #' @title plot_SSRsurface #' @description #' Make minimum SSR v.s. parameterValue plot using the function evaluations used during CGNM computation. Note plot_SSRsurface can only be used when log is saved by setting saveLog=TRUE option when running Cluster_Gauss_Newton_method(). #' @param logLocation (required input) \emph{A string or a list of strings} of folder directory where CGNM computation log files exist. #' @param alpha (default: 0.25) \emph{a number between 0 and 1} level of significance (used to draw horizontal line on the profile likelihood). #' @param profile_likelihood (default: FALSE) \emph{TRUE or FALSE} If set TRUE plot profile likelihood (assuming normal distribution of residual) instead of SSR surface. #' @param numBins (default: NA) \emph{A positive integer} SSR surface is plotted by finding the minimum SSR given one of the parameters is fixed and then repeat this for various values. numBins specifies the number of different parameter values to fix for each parameter. (if set NA the number of bins are set as num_minimizersToFind/10) #' @param maxSSR (default: NA) \emph{A positive number} the maximum SSR that will be plotted on SSR surface plot. This option is used to zoom into the SSR surface near the minimum SSR. #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @param showInitialRange (default: FALSE) \emph{TRUE or FALSE} if TRUE then the initial range appears in the plot. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog=TRUE) #' #' plot_SSRsurface("CGNM_log") + scale_y_continuous(trans='log10') #' } #' @export #' @import ggplot2 plot_SSRsurface=function(logLocation, alpha=0.25,profile_likelihood=FALSE, numBins=NA, maxSSR=NA, ParameterNames=NA, ReparameterizationDef=NA, showInitialRange=FALSE){ boundValue=NULL individual=NULL label=NULL minSSR=NULL negative2LogLikelihood=NULL newvalue=NULL maxBoundValue=NULL minBoundValue=NULL reparaXinit=NULL value=NULL data=makeSSRsurfaceDataset(logLocation, profile_likelihood, numBins, maxSSR, ParameterNames, ReparameterizationDef, showInitialRange) likelihoodSurfacePlot_df=data$likelihoodSurfacePlot_df #residual_variance=data$residual_variance reparaXinit=data$initialX ParameterNames=data$ParameterNames ReparameterizationDef=data$ReparameterizationDef likelihoodSurfacePlot_df$parameterName=factor(likelihoodSurfacePlot_df$parameterName, levels=ParameterNames) if(profile_likelihood){ # likelihoodSurfacePlot_df=subset(likelihoodSurfacePlot_df, negative2LogLikelihood<=(2*(3.84+min(likelihoodSurfacePlot_df$negative2LogLikelihood)))) g=ggplot2::ggplot(likelihoodSurfacePlot_df, ggplot2::aes(x=value,y=negative2LogLikelihood))+ggplot2::geom_point()+ggplot2::geom_line()+ ggplot2::coord_cartesian(ylim=c(-3.84+min(likelihoodSurfacePlot_df$negative2LogLikelihood, na.rm=TRUE), ((4*3.84+min(likelihoodSurfacePlot_df$negative2LogLikelihood,na.rm=TRUE))))) }else{ g=ggplot2::ggplot(likelihoodSurfacePlot_df, ggplot2::aes(x=value,y=minSSR))+ggplot2::geom_point()+ggplot2::geom_line() } # g=ggplot2::ggplot(likelihoodSurfacePlot_df, ggplot2::aes(x=value,y=minSSR))+ggplot2::geom_point()+ggplot2::geom_line() if(showInitialRange){ Xinit_min=c() Xinit_max=c() for(i in seq(1,dim(reparaXinit)[2])){ Xinit_min=c(Xinit_min,min(reparaXinit[,i])) Xinit_max=c(Xinit_max,max(reparaXinit[,i])) } g=g+ggplot2:: geom_rect(data=data.frame(minBoundValue=Xinit_min, maxBoundValue=Xinit_max,parameterName=factor(ParameterNames, levels=ParameterNames)), ggplot2::aes(xmin=minBoundValue, xmax=maxBoundValue, ymin=-Inf, ymax=Inf), alpha=0.3, fill="grey") g=g+ggplot2::geom_vline(data=data.frame(boundValue=Xinit_min, parameterName=factor(ParameterNames, levels=ParameterNames)), ggplot2::aes(xintercept=boundValue), colour="gray") g=g+ggplot2::geom_vline(data=data.frame(boundValue=Xinit_max, parameterName=factor(ParameterNames, levels=ParameterNames)), ggplot2::aes(xintercept=boundValue), colour="gray") } if(profile_likelihood){ g=g+ggplot2::facet_wrap(.~parameterName,scales = "free_x")+ggplot2::ylab("-2log likelihood")+ggplot2::xlab("Parameter Value") g=g+ggplot2::geom_hline(yintercept = qchisq(1-alpha,1)+min(likelihoodSurfacePlot_df$negative2LogLikelihood), colour="grey")+ ggplot2::labs(caption = paste0("Horizontal grey line is the threshold for confidence intervals corresponding to a confidence level of ",(1-alpha)*100,"%.")) }else{ g=g+ggplot2::facet_wrap(.~parameterName,scales = "free_x")+ggplot2::ylab("SSR")+ggplot2::xlab("Parameter Value") } return(g) } prepSSRsurfaceData=function(logLocation, ParameterNames=NA, ReparameterizationDef=NA,numBins=NA){ CGNM_result=NULL minSSR=NULL negative2LogLikelihood=NULL value=NULL boundValue=NULL ReReparameterise=TRUE Re_ReparameterizationDef=ReparameterizationDef Re_ParameterNames=ParameterNames if(length(Re_ParameterNames)!=length(Re_ReparameterizationDef)|is.na(Re_ParameterNames)[1]){ Re_ParameterNames=Re_ReparameterizationDef } if(is.na(Re_ReparameterizationDef)[1]){ ReReparameterise=FALSE } if(typeof(logLocation)=="character"){ DirectoryName_vec=c(logLocation) }else if(typeof(logLocation)=="list"){ if(logLocation$runSetting$runName==""){ DirectoryName_vec=c("CGNM_log","CGNM_log_bootstrap") }else{ DirectoryName_vec=c(paste0("CGNM_log_",logLocation$runSetting$runName),paste0("CGNM_log_",logLocation$runSetting$runName,"bootstrap")) } }else{ warning("DirectoryName need to be either the CGNM_result object or a string") } load(paste0(DirectoryName_vec[1],"/iteration_1.RDATA")) if(is.null(CGNM_result$runSetting$ReparameterizationDef)){ ReparameterizationDef=paste0("x", seq(1,length(CGNM_result$runSetting$initial_lowerRange))) }else{ ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef } if(length(CGNM_result$runSetting$ParameterNames)!=length(ReparameterizationDef)){ ParameterNames=ReparameterizationDef }else{ ParameterNames=CGNM_result$runSetting$ParameterNames } # # if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ # ParameterNames=CGNM_result$runSetting$ParameterNames # } # # # if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ # ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef # } # # # # if(is.na(ParameterNames[1])|length(ParameterNames)!=length(ReparameterizationDef)){ # ParameterNames=ReparameterizationDef # } initialX=CGNM_result$initialX numPara=dim(initialX)[2] if(is.na(ParameterNames[1])){ ParameterNames=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) ReparameterizationDef=ParameterNames } rawX_nu=CGNM_result$initialX R_nu=CGNM_result$residual_history[,1] if(is.null(CGNM_result$initialY)) { ResVar_nu=R_nu*NA }else{ Residual_matrix=CGNM_result$initialY[,!is.na(CGNM_result$runSetting$targetVector)]-repmat(matrix(CGNM_result$runSetting$targetVector[!is.na(CGNM_result$runSetting$targetVector)],nrow=1), dim(CGNM_result$initialY)[1],1) tempVariance=c() for(j in seq(1,dim(Residual_matrix)[1])){ tempVariance=c(tempVariance, var(Residual_matrix[j,])*(numPara-1)/numPara) } ResVar_nu=tempVariance } initiLNLfunc=CGNM_result$runSetting$nonlinearFunction rawXinit=CGNM_result$initialX residual_variance_vec=c() for(DirectoryName in DirectoryName_vec){ checkNL=TRUE for(i in seq(1,CGNM_result$runSetting$num_iteration)){ fileName=paste0(DirectoryName,"/iteration_",i,".RDATA") if (file.exists(fileName)){ load(fileName) rawX_nu=rbind(rawX_nu,CGNM_result$X) Residual_matrix=CGNM_result$Y[,!is.na(CGNM_result$runSetting$targetVector)]-repmat(matrix(CGNM_result$runSetting$targetVector[!is.na(CGNM_result$runSetting$targetVector)],nrow=1), dim(CGNM_result$Y)[1],1) tempVariance=c() for(j in seq(1,dim(Residual_matrix)[1])){ tempVariance=c(tempVariance,var(Residual_matrix[j,])*(numPara-1)/numPara) } ResVar_nu=c(ResVar_nu,tempVariance) tempR=matlabSum((Residual_matrix)^2,2) R_nu=c(R_nu, tempR) if(checkNL){ print(paste0("log saved in ",getwd(),"/",DirectoryName," is used to draw SSR/likelihood surface")) # if(!identical(initiLNLfunc, CGNM_result$runSetting$nonlinearFunction)){ # warning(paste0("the nonlinear function used in this log in ",getwd(),"/",DirectoryName," is not the same as ",getwd(),"/",DirectoryName_vec[1])) # } checkNL=FALSE } } } # residual_variance_vec=c(residual_variance_vec, min(R_nu,na.rm = TRUE)/(sum(!is.na(CGNM_result$runSetting$targetVector))-1)) } # residual_variance=min(residual_variance_vec, na.rm = TRUE) reparaXinit=data.frame(row.names = seq(1,dim(rawXinit)[1])) temp_reparaXinit=data.frame(row.names = seq(1,dim(rawXinit)[1])) colnames(rawXinit)=paste0("x",seq(1,dim(rawXinit)[2])) rawXinit=data.frame(rawXinit) for(i in seq(1,length(ParameterNames))){ temp_reparaXinit[,ParameterNames[i]]=with(rawXinit, eval(parse(text=ReparameterizationDef[i]))) } if(ReReparameterise){ for(i in seq(1,length(Re_ParameterNames))){ reparaXinit[,Re_ParameterNames[i]]=with(temp_reparaXinit, eval(parse(text=Re_ReparameterizationDef[i]))) } }else{ reparaXinit=temp_reparaXinit } # # for(i in seq(1,CGNM_result$runSetting$num_iteration)){ # fileName=paste0(DirectoryName,"bootstrap/iteration_",i,".RDATA") # # # if (file.exists(fileName)){ # load(fileName) # rawX_nu=rbind(rawX_nu,CGNM_result$X) # # R_temp=c() # for(j in seq(1, dim(CGNM_result$Y)[1])){ # R_temp=c(R_temp,sum((CGNM_result$Y[j,]-CGNM_result$runSetting$targetVector)^2,na.rm = TRUE)) # } # # R_nu=c(R_nu, R_temp) # } # } tempMatrix=unique(cbind(rawX_nu,R_nu,ResVar_nu)) rawX_nu=tempMatrix[,seq(1,dim(rawX_nu)[2])] R_nu=tempMatrix[,dim(tempMatrix)[2]-1] ResVar_nu=tempMatrix[,dim(tempMatrix)[2]] negative2LogLikelihood_nu=numPara*log(R_nu)#R_nu/ResVar_nu+numPara*log(ResVar_nu) #negative2LogLikelihood_nu=R_nu/min(ResVar_nu,na.rm = TRUE)#R_nu/ResVar_nu+numPara*log(ResVar_nu) colnames(rawX_nu)=paste0("x",seq(1,dim(rawX_nu)[2])) rawX_nu=data.frame(rawX_nu) X_nu=data.frame(row.names = seq(1,dim(rawX_nu)[1])) temp_X_nu=data.frame(row.names = seq(1,dim(rawX_nu)[1])) for(i in seq(1,length(ParameterNames))){ temp_X_nu[,ParameterNames[i]]=with(rawX_nu, eval(parse(text=ReparameterizationDef[i]))) } if(ReReparameterise){ for(i in seq(1,length(Re_ParameterNames))){ X_nu[,Re_ParameterNames[i]]=with(temp_X_nu, eval(parse(text=Re_ReparameterizationDef[i]))) } }else{ X_nu=temp_X_nu } if(is.na(numBins)){ numBins=round(dim(X_nu)[1]/100) } # residual_variance=residual_variance out=list(X_matrix=X_nu, R_vec=R_nu, ResVar_vec=ResVar_nu,negative2LogLikelihood=negative2LogLikelihood_nu,ParameterNames=names(X_nu),numBins=numBins, initialX=reparaXinit, ReparameterizationDef=Re_ReparameterizationDef) return(out) } #' @title plot_2DprofileLikelihood #' @description #' Make likelihood related values v.s. parameterValues plot using the function evaluations used during CGNM computation. Note plot_SSRsurface can only be used when log is saved by setting saveLog=TRUE option when running Cluster_Gauss_Newton_method(). #' @param logLocation (required input) \emph{A string or a list of strings} of folder directory where CGNM computation log files exist. #' @param index_x (default: NA) \emph{A vector of strings or numbers} List parameter names or indices used for the surface plot. (if NA all parameters are used) #' @param index_y (default: NA) \emph{A vector of strings or numbers} List parameter names or indices used for the surface plot. (if NA all parameters are used) #' @param plotType (default: 2) \emph{A number 0,1,2,3, or 4} 0: number of model evaluations done, 1: (1-alpha) where alpha is the significance level, this plot is recommended for the ease of visualization as it ranges from 0 to 1. 2: -2log likelihood. 3: SSR. 4: all points within 1-alpha confidence region #' @param plotMax (default: NA) \emph{A number} the maximum value that will be plotted on surface plot. (If NA all values are included in the plot, note SSR or likelihood can range many orders of magnitudes fo may want to restrict when plotting them) #' @param numBins (default: NA) \emph{A positive integer} 2D profile likelihood surface is plotted by finding the minimum SSR given two of the parameters are fixed and then repeat this for various values. numBins specifies the number of different parameter values to fix for each parameter. (if set NA the number of bins are set as num_minimizersToFind/10) #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @param showInitialRange (default: TRUE) \emph{TRUE or FALSE} if TRUE then the initial range appears in the plot. #' @param alpha (default: 0.25) \emph{a number between 0 and 1} level of significance (all the points outside of this significance level will not be plotted when plot tyoe 1,2 or 4 are chosen). #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=10^x[1] #' V1=10^x[2] #' CL_2=10^x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(-1,-1,-1), initial_upperRange = c(1,1,1), #' num_iter = 10, num_minimizersToFind = 500, saveLog=TRUE) #' #' ## the minimum example #' plot_2DprofileLikelihood("CGNM_log") #' #' ## we can draw profilelikelihood also including bootstrap result #'CGNM_result=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, #' nonlinearFunction = model_analytic_function) #' #' ## example with various options #' plot_2DprofileLikelihood(c("CGNM_log","CGNM_log_bootstrap"), #' showInitialRange = TRUE,index_x = c("ka","V1")) #' } #' @export #' @import ggplot2 plot_2DprofileLikelihood=function(logLocation, index_x=NA, index_y=NA, plotType=2,plotMax=NA, ParameterNames=NA, ReparameterizationDef=NA,numBins=NA, showInitialRange=TRUE, alpha=0.25){ x_axis=NULL y_axis=NULL value=NULL x_min=NULL x_max=NULL y_min=NULL y_max=NULL if(plotType==1|plotType=="1-alpha"){ plotType="1-alpha" }else if(plotType==2|plotType=="-2logLikelihood"){ plotType="-2logLikelihood" }else if(plotType==3|plotType=="SSR"){ plotType="SSR" }else if(plotType=="count"|plotType==0){ plotType="count" }else if(plotType=="statSignificant"|plotType==4){ plotType="statSignificant" } preppedDataset_list=prepSSRsurfaceData(logLocation, ParameterNames, ReparameterizationDef,numBins) Xinit_min=c() Xinit_max=c() for(i in seq(1,dim(preppedDataset_list$initialX)[2])){ Xinit_min=c(Xinit_min,min(preppedDataset_list$initialX[,i])) Xinit_max=c(Xinit_max,max(preppedDataset_list$initialX[,i])) } index_x_vec=c() if(is.na(index_x)){ index_x_vec=seq(1,length(preppedDataset_list$ParameterNames)) }else if(is.numeric(index_x)){ index_x_vec=index_x }else{ for(index_nu in index_x){ index_x_vec=c(index_x_vec, which(preppedDataset_list$ParameterNames==index_nu)) } } index_y_vec=c() if(is.na(index_y)){ index_y_vec=seq(1,length(preppedDataset_list$ParameterNames)) }else if(is.numeric(index_y)){ index_y_vec=index_y }else{ for(index_nu in index_y){ index_y_vec=c(index_y_vec, which(preppedDataset_list$ParameterNames==index_nu)) } } X_val=preppedDataset_list$X_matrix numBins=preppedDataset_list$numBins SSR_vec=preppedDataset_list$R_vec neg2likelihood_vec=preppedDataset_list$negative2LogLikelihood if(plotType=="1-alpha"){ z_value=pchisq(neg2likelihood_vec-min(neg2likelihood_vec),df=2) }else if(plotType=="-2logLikelihood"){ z_value=neg2likelihood_vec }else if(plotType=="SSR"){ z_value=SSR_vec }else if(plotType=="statSignificant"){ z_value=as.numeric((neg2likelihood_vec-min(neg2likelihood_vec)-qchisq(0.95,1))<0) } n2likelihood=preppedDataset_list$negative2LogLikelihood if(!is.na(plotMax)){ useIndex=(((n2likelihood-min(n2likelihood))<qchisq(1-alpha,2))&(z_value<plotMax)) }else{ useIndex=((n2likelihood-min(n2likelihood))<qchisq(1-alpha,2)) } X_val=X_val[useIndex,] SSR_vec=SSR_vec[useIndex] neg2likelihood_vec=neg2likelihood_vec[useIndex] X_rounded=X_val for(i in seq(1,dim(X_rounded)[2])){ # for(j in seq(1,numBins)){ # binUpper=quantile(X_val[,i], probs = c((j-1)*(1/numBins),(j)*(1/numBins)))[2] # binLower=quantile(X_val[,i], probs = c((j-1)*(1/numBins),(j)*(1/numBins)))[1] # indexToUse=((X_val[,i]<=binUpper)&(X_val[,i]>binLower)) # # X_rounded[indexToUse,i]=(binUpper+binLower)/2 # } for(j in seq(1,numBins)){ X_rounded[,i]=(X_val[,i]-min(X_val[,i]))/(max(X_val[,i])-min(X_val[,i])) X_rounded[,i]=round(X_rounded[,i]*numBins)/numBins X_rounded[,i]=X_rounded[,i]*(max(X_val[,i])-min(X_val[,i]))+min(X_val[,i]) } } aggData_comnbined_df=data.frame() boundData_df=data.frame() X_forPlot4=unique(X_rounded) out <- tryCatch( { optimal_kmeans((X_forPlot4)) }, error=function(cond) { rep(1,dim(X_forPlot4)[1]) }, warning=function(cond) { optimal_kmeans((X_forPlot4)) }, finally={ } ) cluster_index=as.factor(out$cluster) for(index_x in index_x_vec){ for(index_y in index_y_vec){ if(index_x!=index_y){ boundData_df=rbind(boundData_df, data.frame(x_min=Xinit_min[index_x],x_max=Xinit_max[index_x],y_min=Xinit_min[index_y],y_max=Xinit_max[index_y],x_lab=preppedDataset_list$ParameterNames[index_x],y_lab=preppedDataset_list$ParameterNames[index_y])) if(plotType=="count"){ aggData_df=data.frame(aggregate(SSR_vec, by=list(X_rounded[,index_x],X_rounded[,index_y]), FUN="length")) names(aggData_df)=c("x_axis","y_axis", "value") }else if(plotType=="statSignificant"){ aggData_df=data.frame(x_axis=X_forPlot4[,index_x],y_axis=X_forPlot4[,index_y],value=cluster_index) }else if(plotType=="SSR"){ aggData_df=data.frame(aggregate(SSR_vec, by=list(X_rounded[,index_x],X_rounded[,index_y]), FUN="min")) names(aggData_df)=c("x_axis","y_axis","SSR") aggData_df$value=aggData_df$SSR }else{ aggData_df=data.frame(aggregate(neg2likelihood_vec, by=list(X_rounded[,index_x],X_rounded[,index_y]), FUN="min")) names(aggData_df)=c("x_axis","y_axis","neg2likelihood") if(plotType=="1-alpha"){ aggData_df$value=pchisq(aggData_df$neg2likelihood-min(aggData_df$neg2likelihood),df=2) }else if(plotType=="-2logLikelihood"){ aggData_df$value=aggData_df$neg2likelihood aggData_df$value[pchisq(aggData_df$neg2likelihood-min(aggData_df$neg2likelihood),df=2)>(1-alpha)]=NA } } aggData_df$x_lab=factor(preppedDataset_list$ParameterNames[index_x],levels=preppedDataset_list$ParameterNames[index_x]) aggData_df$y_lab=factor(preppedDataset_list$ParameterNames[index_y],levels=preppedDataset_list$ParameterNames[index_y]) aggData_comnbined_df=rbind(aggData_comnbined_df,aggData_df) } } } aggData_comnbined_df=aggData_comnbined_df[order(-aggData_comnbined_df$value),] if(plotType=="count"){ g=ggplot2::ggplot(aggData_comnbined_df, ggplot2::aes(x=x_axis, y=y_axis, alpha=log10(value)))+ggplot2::geom_point()+ggplot2::xlab("")+ggplot2::ylab("")+ggplot2::labs(alpha="log10(count)")+ggplot2::facet_grid(y_lab~x_lab,scales = "free") }else if(plotType=="1-alpha"){ g=ggplot2::ggplot(subset(aggData_comnbined_df, value<(1-alpha)), ggplot2::aes(x=x_axis, y=y_axis, z=value))+ggplot2::xlab("")+ggplot2::ylab("")+ggplot2::labs(fill="1-alpha")+ggplot2::facet_grid(y_lab~x_lab,scales = "free")+ggplot2::geom_contour_filled(bins=20) }else if(plotType=="statSignificant"){ g=ggplot2::ggplot(aggData_comnbined_df, ggplot2::aes(x=x_axis, y=y_axis, colour=value))+ggplot2::xlab("")+ggplot2::ylab("")+ggplot2::geom_point()+ggplot2::facet_grid(y_lab~x_lab,scales = "free") }else{ #g=ggplot2::ggplot(aggData_comnbined_df, ggplot2::aes(x=x_axis, y=y_axis, z=value))+ggplot2::xlab("")+ggplot2::ylab("")+ggplot2::labs(fill=plotType)+ggplot2::facet_grid(y_lab~x_lab,scales = "free")+ggplot2::geom_contour_filled(bins=20) g=ggplot2::ggplot(aggData_comnbined_df, ggplot2::aes(x=x_axis, y=y_axis, colour=value))+ggplot2::xlab("")+ggplot2::ylab("")+ggplot2::labs(colour=plotType)+ggplot2::facet_grid(y_lab~x_lab,scales = "free")+ggplot2::geom_point() } if(showInitialRange){ g=g+ggplot2::geom_vline(data=boundData_df, ggplot2::aes(xintercept=x_min), colour="gray") g=g+ggplot2::geom_vline(data=boundData_df, ggplot2::aes(xintercept=x_max), colour="gray") g=g+ggplot2::geom_hline(data=boundData_df, ggplot2::aes(yintercept=y_min), colour="gray") g=g+ggplot2::geom_hline(data=boundData_df, ggplot2::aes(yintercept=y_max), colour="gray") } return(g) } makeSSRsurfaceDataset=function(logLocation, profile_likelihood=FALSE, numBins=NA, maxSSR=NA, ParameterNames=NA, ReparameterizationDef=NA, showInitialRange=FALSE){ CGNM_result=NULL minSSR=NULL negative2LogLikelihood=NULL value=NULL boundValue=NULL initialX=NULL temp_list=prepSSRsurfaceData(logLocation, ParameterNames, ReparameterizationDef, numBins) X_nu=temp_list$X_matrix R_nu=temp_list$R_vec ResVar_nu=temp_list$ResVar_vec # residual_variance=temp_list$residual_variance negative2LogLikelihood=temp_list$negative2LogLikelihood ParameterNames=temp_list$ParameterNames numBins=temp_list$numBins initialX=temp_list$initialX ReparameterizationDef=temp_list$ReparameterizationDef likelihoodSurfacePlot_df=data.frame() indexToUseForRefine_df=data.frame() for(j in seq(1,length(ParameterNames))){ for(i in seq(1,numBins)){ binUpper=quantile(X_nu[,j], probs = c((i-1)*(1/numBins),(i)*(1/numBins)))[2] binLower=quantile(X_nu[,j], probs = c((i-1)*(1/numBins),(i)*(1/numBins)))[1] indexToUse=((X_nu[,j]<=binUpper)&(X_nu[,j]>binLower)) n2l_toUse=negative2LogLikelihood[indexToUse] R_toUse=R_nu[indexToUse] #plot_index=which(indexToUse&R_nu==min(R_toUse,na.rm = TRUE)) plot_index=which(indexToUse&negative2LogLikelihood==min(n2l_toUse,na.rm = TRUE)) if(length(plot_index)>0){ plot_index=plot_index[1] indexToUseForRefine_df=rbind(indexToUseForRefine_df,data.frame(index= which(indexToUse)[order(R_toUse)[seq(1, min(length(R_nu),length(ParameterNames)+1))]], paraIndex=j)) likelihoodSurfacePlot_df=rbind(likelihoodSurfacePlot_df, data.frame(value=X_nu[plot_index,j], negative2LogLikelihood=negative2LogLikelihood[plot_index], minSSR=min(R_nu[indexToUse],na.rm = TRUE), parameterName=ParameterNames[j])) } } } # ggplot(likelihoodSurfacePlot_df, aes(x=value,y=minSSR))+geom_point()+facet_wrap(.~parameterName,scales = "free")+geom_smooth()+ylim(0.5,1) if(!is.na(maxSSR)){ likelihoodSurfacePlot_df=subset(likelihoodSurfacePlot_df, minSSR<=maxSSR) } out=list(likelihoodSurfacePlot_df=likelihoodSurfacePlot_df, indexToUseForRefine_df=indexToUseForRefine_df, X_nu=X_nu,initialX=initialX, ParameterNames=ParameterNames, ReparameterizationDef=ReparameterizationDef) return(out) } makeInitialClusterForPLrefinment=function(logLocation, paraIndex, range=NA,numPerBin=10, profile_likelihood=FALSE, numBins=NA, maxSSR=NA, ParameterNames=NA, ReparameterizationDef=NA, showInitialRange=FALSE){ CGNM_result=NULL minSSR=NULL negative2LogLikelihood=NULL value=NULL boundValue=NULL initialX=NULL temp_list=prepSSRsurfaceData(logLocation, ParameterNames, ReparameterizationDef, numBins) X_nu=temp_list$X_matrix R_nu=temp_list$R_vec # residual_variance=temp_list$residual_variance ParameterNames=temp_list$ParameterNames numBins=temp_list$numBins initialX=temp_list$initialX ReparameterizationDef=temp_list$ReparameterizationDef if(!is.na(range)[1]){ OK_index=X_nu[,paraIndex]<range[2]&X_nu[,paraIndex]>range[1] } X_nu=X_nu[OK_index,] R_nu=R_nu[OK_index] likelihoodSurfacePlot_df=data.frame() indexToUseForRefine_df=data.frame() j=paraIndex out_df=data.frame() for(i in seq(1,numBins)){ binLower=(max(X_nu[,j])-min(X_nu[,j]))/numBins*(i-1)+min(X_nu[,j]) binUpper=(max(X_nu[,j])-min(X_nu[,j]))/numBins*i+min(X_nu[,j]) # binUpper=quantile(X_nu[,j], probs = c((i-1)*(1/numBins),(i)*(1/numBins)))[2] # binLower=quantile(X_nu[,j], probs = c((i-1)*(1/numBins),(i)*(1/numBins)))[1] indexToUse=((X_nu[,j]<=binUpper)&(X_nu[,j]>binLower)) R_toUse=R_nu[indexToUse] plot_index=which(indexToUse&R_nu<=sort(R_toUse, na.last= TRUE)[numPerBin]) tempDf=X_nu[plot_index,] best_index=which(indexToUse&R_nu==min(R_toUse)) tempDf[,j]=X_nu[best_index,j] out_df=rbind(out_df, tempDf) } return(out_df) } #' @title plot_SSR_parameterValue #' @description #' Make SSR v.s. parameterValue plot of the accepted approximate minimizers found by the CGNM. Bars in the violin plots indicates the interquartile range. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param indicesToInclude (default: NA) \emph{A vector of integers} indices to include in the plot (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @param showInitialRange (default: TRUE) \emph{TRUE or FALSE} if TRUE then the initial range appears in the plot. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' plot_SSR_parameterValue(CGNM_result) #' @export #' @import ggplot2 plot_SSR_parameterValue=function(CGNM_result, indicesToInclude=NA, ParameterNames=NA, ReparameterizationDef=NA, showInitialRange=TRUE){ Kind_iter=NULL SSR=NULL X_value=NULL cluster=NULL boundValue=NULL cutoff_pvalue=0.05 numParametersIncluded=NA useAcceptedApproximateMinimizers=TRUE # if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ # ParameterNames=CGNM_result$runSetting$ParameterNames # } # if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ # ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef # } freeParaValues=makeParaDistributionPlotDataFrame(CGNM_result, indicesToInclude, cutoff_pvalue, numParametersIncluded, ParameterNames, ReparameterizationDef, useAcceptedApproximateMinimizers) plotdata_df=subset(freeParaValues, Kind_iter=="Final Accepted") kmeans_result=optimal_kmeans(matrix(plotdata_df$X_value, ncol=dim(CGNM_result$X)[2])) plotdata_df$cluster=as.factor(kmeans_result$cluster) g=ggplot2::ggplot(plotdata_df, ggplot2::aes(y=SSR, x=X_value, colour=cluster))+ggplot2::geom_point(alpha=0.3) if(showInitialRange&&is.na(ParameterNames)[1]){ ParameterNames=paste0("x",seq(1,dim(CGNM_result$X)[2])) g=g+ggplot2::geom_vline(data=data.frame(boundValue=CGNM_result$runSetting$initial_lowerRange, Name=ParameterNames), ggplot2::aes(xintercept=boundValue), colour="gray") g=g+ggplot2::geom_vline(data=data.frame(boundValue=CGNM_result$runSetting$initial_upperRange, Name=ParameterNames), ggplot2::aes(xintercept=boundValue), colour="gray") } g+ggplot2::facet_wrap(.~Name,scales="free") } #' @title plot_parameterValue_scatterPlots #' @description #' Make scatter plots of the accepted approximate minimizers found by the CGNM. Bars in the violin plots indicates the interquartile range. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param indicesToInclude (default: NA) \emph{A vector of integers} indices to include in the plot (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' plot_parameterValue_scatterPlots(CGNM_result) #' @export #' @import ggplot2 plot_parameterValue_scatterPlots=function(CGNM_result, indicesToInclude=NA){ cutoff_pvalue=0.05 numParametersIncluded=NA ParameterNames=NA useAcceptedApproximateMinimizers=TRUE SSR=NULL X_value=NULL cluster=NULL Y_value=NULL cluster=NULL lastIter=dim(CGNM_result$residual_history)[2] plot_df=data.frame() if(!is.na(indicesToInclude[1])){ useIndecies_b=seq(1,dim(CGNM_result$X)[1])%in%indicesToInclude }else{ useIndecies_b=acceptedIndices_binary(CGNM_result,cutoff_pvalue, numParametersIncluded, useAcceptedApproximateMinimizers) } if(length(ParameterNames)==dim(CGNM_result$initialX)[2]){ }else{ ParameterNames=paste0("x_",seq(1,dim(CGNM_result$initialX)[2])) } kmeans_result=optimal_kmeans(cbind(CGNM_result$X[useIndecies_b,], plot_df$SSR)) cluster_vec=as.factor(kmeans_result$cluster) for(i in seq(1,dim(CGNM_result$X)[2])){ for(j in seq(1,dim(CGNM_result$X)[2])){ plot_df=rbind(plot_df, data.frame(xName=ParameterNames[i],X_value=CGNM_result$X[useIndecies_b,i],yName=ParameterNames[j],Y_value=CGNM_result$X[useIndecies_b,j],cluster=cluster_vec)) } } ggplot2::ggplot(plot_df, ggplot2::aes(y=Y_value, x=X_value, colour=cluster))+ggplot2::geom_point(alpha=0.3)+ggplot2::facet_wrap(xName~yName,scales="free")+ ggplot2::theme( strip.background = element_blank(), strip.text.x = element_blank() ) } #' @title bestApproximateMinimizers #' @description #' Returns the approximate minimizers with minimum SSR found by CGNM. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param numParameterSet (default 1) \emph{A natural number} number of parameter sets to output (chosen from the smallest SSR to numParameterSet-th smallest SSR) . #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax #' @return \emph{A vector} a vector of accepted approximate minimizers with minimum SSR found by CGNM. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' bestApproximateMinimizers(CGNM_result,10) #' @export bestApproximateMinimizers=function(CGNM_result, numParameterSet=1,ParameterNames=NA, ReparameterizationDef=NA){ SSRorder=order(CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]]) out=CGNM_result$X[SSRorder,] out=data.frame(out) out=out[1:numParameterSet,] colnames(out)=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ ParameterNames=CGNM_result$runSetting$ParameterNames } if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef } if(is.na(ParameterNames[1])|length(ParameterNames)!=length(ReparameterizationDef)){ ParameterNames=ReparameterizationDef } if(is.na(ParameterNames[1])){ ParameterNames=paste0("x",seq(1,dim(CGNM_result$initialX)[2])) ReparameterizationDef=ParameterNames } repara_finalX_df=data.frame(row.names = seq(1,dim(out)[1])) for(i in seq(1,length(ParameterNames))){ repara_finalX_df[,ParameterNames[i]]=with(out, eval(parse(text=ReparameterizationDef[i]))) } return(repara_finalX_df) } #' @title plot_goodnessOfFit #' @description #' Make goodness of fit plots to assess the model-fit and bias in residual distribution. The linear model is fit to the residual and plotted using geom_smooth(method=lm) in ggplot.\cr\cr #' Explanation of the terminologies in terms of PBPK model fitting to the time-course drug concentration measurements: #' \cr "independent variable" is time #' \cr "dependent variable" is the concentration. #' \cr "Residual" is the difference between the measured concentration and the model simulation with the parameter fond by the CGNM. #' \cr "m" is number of observations #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param plotType (default: 1) \emph{1,2 or 3}\cr specify the kind of goodness of fit plot to create #' @param plotRank (default: c(1)) \emph{a vector of integers}\cr Specify which rank of the parameter to use for the goodness of fit plots. (e.g., if one wishes to use rank 1 to 100 then set it to be seq(1,100), or if one wish to use 88th rank parameters then set this as 88.) #' @param independentVariableVector (default: NA) \emph{a vector of numerics of length m} \cr set independent variables that target values are associated with (e.g., time of the drug concentration measurement one is fitting PBPK model to) \cr(when this variable is set to NA, seq(1,m) will be used as independent variable when appropriate). #' @param dependentVariableTypeVector (default: NA) \emph{a vector of text of length m} \cr when this variable is set (i.e., not NA) then the goodness of fit analyses is done for each variable type. For example, if we are fitting the PBPK model to data with multiple dose arms, one can see the goodness of fit for each dose arm by specifying which dose group the observations are from. #' @param absResidual (default: FALSE) \emph{TRUE or FALSE} If TRUE plot absolute values of the residual. #' @return \emph{A ggplot object} of the goodness of fit plot. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=10^x[1] #' V1=10^x[2] #' CL_2=10^x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = rep(0.01,3), initial_upperRange = rep(100,3), #' lowerBound=rep(0,3), ParameterNames = c("Ka","V1","CL"), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' plot_goodnessOfFit(CGNM_result) #' plot_goodnessOfFit(CGNM_result, #' independentVariableVector=c(0.1,0.2,0.4,0.6,1,2,3,6,12)) #' @export #' @import ggplot2 plot_goodnessOfFit=function(CGNM_result, plotType=1, plotRank=c(1), independentVariableVector=NA, dependentVariableTypeVector=NA, absResidual=FALSE){ CGNM_result$runSetting$targetVector=as.numeric(CGNM_result$runSetting$targetVector) independent_variable=NULL lower=NULL upper=NULL target=NULL model_fit=NULL ind=NULL residual=NULL SSR=NULL SD=NULL independentVariableVector_in=independentVariableVector SSR_vec=CGNM_result$residual_history[,dim(CGNM_result$residual_history)[2]] indexToInclude=seq(1,length(SSR_vec))[rank(SSR_vec,na.last = TRUE, ties.method = "last")%in%plotRank] if(is.na(independentVariableVector[1])||length(independentVariableVector)!=length(CGNM_result$runSetting$targetVector)){ independentVariableVector=seq(1, length(CGNM_result$runSetting$targetVector)) }else{ independentVariableVector=as.numeric(independentVariableVector) } if(is.na(dependentVariableTypeVector[1])||length(dependentVariableTypeVector)!=length(CGNM_result$runSetting$targetVector)){ dependentVariableTypeVector=NA }else{ dependentVariableTypeVector=as.factor(dependentVariableTypeVector) } residualPlot_df=data.frame() for(index in indexToInclude){ residualPlot_df=rbind(residualPlot_df, data.frame(independent_variable=independentVariableVector, residual=CGNM_result$Y[index,]-CGNM_result$runSetting$targetVector, target=CGNM_result$runSetting$targetVector, model_fit=CGNM_result$Y[index,], dependent_variable_type=dependentVariableTypeVector, square_residual=(CGNM_result$Y[index,]-CGNM_result$runSetting$targetVector)^2, ind=index)) } residualPlot_df$ind=as.factor(residualPlot_df$ind) if(absResidual){ residualPlot_df$residual=abs(residualPlot_df$residual) } residualPlot_df=residualPlot_df[!is.na(residualPlot_df$residual),] withBootstrap=!is.null(CGNM_result$bootstrapY) median_vec=c() percentile5_vec=c() percentile95_vec=c() uncertaintyBound_df=data.frame() if(withBootstrap){ for(i in seq(1, dim(CGNM_result$bootstrapY)[2])){ tempQ=quantile(CGNM_result$bootstrapY[,i], prob=c(0.05,0.5,0.95), na.rm=TRUE) median_vec=c(median_vec, tempQ[2]) percentile5_vec=c(percentile5_vec, tempQ[1]) percentile95_vec=c(percentile95_vec, tempQ[3]) } uncertaintyBound_df=data.frame(independent_variable=independentVariableVector, dependent_variable_type=dependentVariableTypeVector, median=median_vec, lower=percentile5_vec, upper=percentile95_vec, target=CGNM_result$runSetting$targetVector) } uncertaintyBound_df=uncertaintyBound_df[!is.na(uncertaintyBound_df$target),] if(plotType==1){ #dependent variable v.s. independent variable (e.g., concentration-time profile) if(withBootstrap){ p<-ggplot2::ggplot(uncertaintyBound_df,ggplot2::aes(x=independent_variable, y=median))+ggplot2::geom_line(colour="blue")+ggplot2::geom_ribbon(ggplot2::aes(ymin =lower, ymax =upper, x=independent_variable), alpha=0.2,fill="blue")+ggplot2::geom_point(ggplot2::aes(x=independent_variable, y=target), colour="red") }else if(length(unique(residualPlot_df$ind))==1){ p<-ggplot2::ggplot(residualPlot_df,ggplot2::aes(x=independent_variable, y=model_fit))+ggplot2::geom_line()+ggplot2::geom_point(ggplot2::aes(x=independent_variable, y=target), colour="red") }else{ p<-ggplot2::ggplot(residualPlot_df,ggplot2::aes(x=independent_variable, y=model_fit, group=ind))+ggplot2::geom_line()+ggplot2::geom_point(ggplot2::aes(x=independent_variable, y=target), colour="red") } p=p+ggplot2::xlab("Independent Variable") p=p+ggplot2::ylab("Dependent Variable") if(!is.na(dependentVariableTypeVector[1])){ p=p+ggplot2::facet_grid(.~dependent_variable_type, scales = "free") } }else if(plotType==2){ #residual v.s. dependent variable (e.g., residual-fitted model profile) p<-ggplot2::ggplot(residualPlot_df,ggplot2::aes(x=model_fit, y=residual))+ggplot2::geom_point() p=p+ggplot2::geom_smooth(method = lm) p=p+ggplot2::xlab("Dependent Variable (simulation)") if(absResidual){ p=p+ggplot2::ylab("Residual (absolute value)") }else{ p=p+ggplot2::ylab("Residual") } if(!is.na(dependentVariableTypeVector[1])){ p=p+ggplot2::facet_grid(.~dependent_variable_type, scales = "free") } p=p+geom_hline(yintercept = 0) }else if(plotType==4){ #residual v.s. dependent variable (e.g., residual-fitted model profile) p<-ggplot2::ggplot(residualPlot_df,ggplot2::aes(x=target, y=residual))+ggplot2::geom_point() p=p+ggplot2::geom_smooth(method = lm) p=p+ggplot2::xlab("Dependent Variable (target)") if(absResidual){ p=p+ggplot2::ylab("Residual (absolute value)") }else{ p=p+ggplot2::ylab("Residual") } if(!is.na(dependentVariableTypeVector[1])){ p=p+ggplot2::facet_grid(.~dependent_variable_type, scales = "free") } p=p+geom_hline(yintercept = 0) }else if(plotType==3){ #residual v.s. independent variable (e.g., residual-time profile) if(is.na(independentVariableVector_in[1])){ p<-ggplot2::ggplot(residualPlot_df,ggplot2::aes(x=residual))+ggplot2::geom_histogram() if(absResidual){ p=p+ggplot2::xlab("Residual (absolute value)") }else{ p=p+ggplot2::xlab("Residual") } if(!is.na(dependentVariableTypeVector[1])){ p=p+ggplot2::facet_grid(.~dependent_variable_type, scales = "free") } }else{ p<-ggplot2::ggplot(residualPlot_df,ggplot2::aes(x=independent_variable, y=residual))+ggplot2::geom_point() p=p+ggplot2::geom_smooth(method = lm) p=p+ggplot2::xlab("Independent Variable") if(absResidual){ p=p+ggplot2::ylab("Residual (absolute value)") }else{ p=p+ggplot2::ylab("Residual") } if(!is.na(dependentVariableTypeVector[1])){ p=p+ggplot2::facet_grid(.~dependent_variable_type, scales = "free") } p=p+geom_hline(yintercept = 0) } }else{ p=ggplot2::ggplot(residualPlot_df) } if(plotType==1&&(length(unique(dependentVariableTypeVector ))>1&length(plotRank)==1)){ SSR_byVariable=aggregate(residualPlot_df$square_residual, by=list(dependent_variable_type=residualPlot_df$dependent_variable_type), FUN=sum) SSR_byVariable$SSR=formatC(SSR_byVariable$x, format = "g", digits = 3) p=p+ geom_text( size = 5, data = SSR_byVariable, mapping = aes(x = Inf, y = Inf, label = paste0("SSR=",SSR)), hjust = 1.05, vjust = 1.5, inherit.aes = FALSE ) }else if ((length(unique(dependentVariableTypeVector ))>1&length(plotRank)==1)){ SD_byVariable=aggregate(residualPlot_df$residual, by=list(dependent_variable_type=residualPlot_df$dependent_variable_type), FUN=sd) SD_byVariable$SD=formatC(SD_byVariable$x, format = "g", digits = 3) p=p+ geom_text( size = 5, data = SD_byVariable, mapping = aes(x = Inf, y = Inf, label = paste0("StandardDiv.=",SD)), hjust = 1.05, vjust = 1.5, inherit.aes = FALSE ) } p } #' @title table_parameterSummary #' @description #' Make summary table of the approximate local minimizers found by CGNM. If bootstrap analysis result is available, relative standard error (RSE: standard deviation/mean) will also be included in the table. #' @param CGNM_result (required input) \emph{A list} stores the computational result from Cluster_Gauss_Newton_method() function in CGNM package. #' @param indicesToInclude (default: NA) \emph{A vector of integers} indices to include in the plot (if NA, use indices chosen by the acceptedIndices() function with default setting). #' @param ParameterNames (default: NA) \emph{A vector of strings} the user can supply so that these names are used when making the plot. (Note if it set as NA or vector of incorrect length then the parameters are named as theta1, theta2, ... or as in ReparameterizationDef) #' @param ReparameterizationDef (default: NA) \emph{A vector of strings} the user can supply definition of reparameterization where each string follows R syntax. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #' #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = rep(0.01,3), initial_upperRange = rep(100,3), #' lowerBound=rep(0,3), ParameterNames = c("Ka","V1","CL"), #' num_iter = 10, num_minimizersToFind = 100, saveLog = FALSE) #' #' table_parameterSummary(CGNM_result) #' table_parameterSummary(CGNM_result, #' ReparameterizationDef=c("log10(Ka)","log10(V1)","log10(CL)")) #' #' @export #' @import ggplot2 table_parameterSummary=function(CGNM_result, indicesToInclude=NA, ParameterNames=NA, ReparameterizationDef=NA){ # if(is.na(ParameterNames)[1]&!is.null(CGNM_result$runSetting$ParameterNames)){ # # ParameterNames=CGNM_result$runSetting$ParameterNames # # } # # if(is.na(ReparameterizationDef)[1]&!is.null(CGNM_result$runSetting$ReparameterizationDef)){ # ReparameterizationDef=CGNM_result$runSetting$ReparameterizationDef # } Name=NULL Kind_iter=NULL cutoff_pvalue=0.05 numParametersIncluded=NA useAcceptedApproximateMinimizers=TRUE freeParaValues=makeParaDistributionPlotDataFrame(CGNM_result, indicesToInclude, cutoff_pvalue, numParametersIncluded, ParameterNames, ReparameterizationDef, useAcceptedApproximateMinimizers) summaryData_df=data.frame() variableNames=unique(freeParaValues$Name) if(!is.null(CGNM_result$bootstrapX)){ for(vName in variableNames){ tempVec=quantile(subset(freeParaValues, Name==vName&Kind_iter=="Bootstrap")$X_value, probs = c(0,0.25,0.5,0.75,1), na.rm = TRUE) bootstrapDS=subset(freeParaValues, Name==vName&Kind_iter=="Bootstrap")$X_value tempVec=c(tempVec, sd(bootstrapDS,na.rm = TRUE)/abs(mean(bootstrapDS,na.rm = TRUE))*100) summaryData_df=rbind(summaryData_df,as.numeric(tempVec)) } colnames(summaryData_df)=c("CGNM Bootstrap: Minimum","25 percentile", "Median","75 percentile", "Maximum", "RSE (%)") }else{ for(vName in variableNames){ tempVec=quantile(subset(freeParaValues, Name==vName&Kind_iter=="Final Accepted")$X_value, probs = c(0,0.25,0.5,0.75,1), na.rm = TRUE) summaryData_df=rbind(summaryData_df,as.numeric(tempVec)) } colnames(summaryData_df)=c("CGNM: Minimum","25 percentile", "Median","75 percentile", "Maximum") } rownames(summaryData_df)=variableNames return(summaryData_df) } #' @title suggestInitialLowerRange #' @description #' Suggest initial lower range based on the profile likelihood. The user can re-run CGNM with this suggested initial range so that to improve the convergence. #' @param logLocation (required input) \emph{A string or a list of strings} of folder directory where CGNM computation log files exist. #' @param alpha (default: 0.25) \emph{a number between 0 and 1} level of significance used to derive the confidence interval. #' @param numBins (default: NA) \emph{A positive integer} SSR surface is plotted by finding the minimum SSR given one of the parameters is fixed and then repeat this for various values. numBins specifies the number of different parameter values to fix for each parameter. (if set NA the number of bins are set as num_minimizersToFind/10) #' @return \emph{A numerical vector} of suggested initial lower range based on profile likelihood. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog=TRUE) #' #' suggestInitialLowerRange("CGNM_log") #' } #' @export suggestInitialLowerRange=function(logLocation, alpha=0.25, numBins=NA){ ParameterNames=NA ReparameterizationDef=NA CGNM_result=NULL boundValue=NULL individual=NULL label=NULL minSSR=NULL negative2LogLikelihood=NULL newvalue=NULL parameterName=NULL reparaXinit=NULL value=NULL if(typeof(logLocation)=="character"){ DirectoryName_vec=c(logLocation) }else if(typeof(logLocation)=="list"){ if(logLocation$runSetting$runName==""){ DirectoryName_vec=c("CGNM_log","CGNM_log_bootstrap") }else{ DirectoryName_vec=c(paste0("CGNM_log_",logLocation$runSetting$runName),paste0("CGNM_log_",logLocation$runSetting$runName,"bootstrap")) } }else{ warning("DirectoryName need to be either the CGNM_result object or a string") } load(paste0(DirectoryName_vec[1],"/iteration_1.RDATA")) data=makeSSRsurfaceDataset(logLocation, TRUE, numBins, NA, ParameterNames, ReparameterizationDef, FALSE) likelihoodSurfacePlot_df=data$likelihoodSurfacePlot_df minSSR=min(likelihoodSurfacePlot_df$negative2LogLikelihood) likelihoodSurfacePlot_df$belowSignificance=(likelihoodSurfacePlot_df$negative2LogLikelihood-qchisq(1-alpha,1)-minSSR<0) paraKind=unique(likelihoodSurfacePlot_df$parameterName) upperBound_vec=c() lowerBound_vec=c() for(para_nu in paraKind){ dataframe_nu=subset(likelihoodSurfacePlot_df,parameterName==para_nu) upperBoundIndex=which(max(dataframe_nu$value[dataframe_nu$belowSignificance])==dataframe_nu$value) lowerBoundIndex=which(min(dataframe_nu$value[dataframe_nu$belowSignificance])==dataframe_nu$value) theoreticalLB=CGNM_result$runSetting$lowerBound[CGNM_result$runSetting$ParameterNames==para_nu] theoreticalUB=CGNM_result$runSetting$upperBound[CGNM_result$runSetting$ParameterNames==para_nu] if(upperBoundIndex==length(dataframe_nu$value)){ if(!is.na(theoreticalUB)){ upperBound=(dataframe_nu$value[upperBoundIndex]+theoreticalUB)/2 }else{ upperBound=dataframe_nu$value[upperBoundIndex]*10 } }else{ upperBound=(dataframe_nu$value[upperBoundIndex]+dataframe_nu$value[upperBoundIndex+1])/2 } if(lowerBoundIndex==1){ if(!is.na(theoreticalLB)){ lowerBound_suggest=(dataframe_nu$value[lowerBoundIndex]+theoreticalLB)/2 }else{ lowerBound_suggest=10^floor(log10(dataframe_nu$value[lowerBoundIndex]))/10 } }else if(lowerBoundIndex>2){ lowerBound_suggest=dataframe_nu$value[lowerBoundIndex-2] }else{ if(!is.na(theoreticalLB)){ lowerBound=(dataframe_nu$value[lowerBoundIndex]+dataframe_nu$value[lowerBoundIndex-1])/2 width=upperBound-lowerBound if((lowerBound-width)>theoreticalLB){ lowerBound_suggest=(lowerBound-width) }else{ lowerBound_suggest=(lowerBound+theoreticalLB)/2 } }else{ lowerBound=(dataframe_nu$value[lowerBoundIndex]+dataframe_nu$value[lowerBoundIndex-1])/2 lowerBound_suggest=10^floor(log10(lowerBound))/10 } } upperBound_vec=c(upperBound_vec,upperBound) lowerBound_vec=c(lowerBound_vec,lowerBound_suggest) } return(lowerBound_vec) } #' @title suggestInitialUpperRange #' @description #' Suggest initial upper range based on the profile likelihood. The user can re-run CGNM with this suggested initial range so that to improve the convergence. #' @param logLocation (required input) \emph{A string or a list of strings} of folder directory where CGNM computation log files exist. #' @param alpha (default: 0.25) \emph{a number between 0 and 1} level of significance used to derive the confidence interval. #' @param numBins (default: NA) \emph{A positive integer} SSR surface is plotted by finding the minimum SSR given one of the parameters is fixed and then repeat this for various values. numBins specifies the number of different parameter values to fix for each parameter. (if set NA the number of bins are set as num_minimizersToFind/10) #' @return \emph{A numerical vector} of suggested initial upper range based on profile likelihood. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' log10(Cp) #'} #' #' observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' num_iter = 10, num_minimizersToFind = 100, saveLog=TRUE) #' #' suggestInitialLowerRange("CGNM_log") #' } #' @export suggestInitialUpperRange=function(logLocation, alpha=0.25, numBins=NA){ ParameterNames=NA ReparameterizationDef=NA CGNM_result=NULL boundValue=NULL individual=NULL label=NULL minSSR=NULL negative2LogLikelihood=NULL newvalue=NULL parameterName=NULL reparaXinit=NULL value=NULL if(typeof(logLocation)=="character"){ DirectoryName_vec=c(logLocation) }else if(typeof(logLocation)=="list"){ if(logLocation$runSetting$runName==""){ DirectoryName_vec=c("CGNM_log","CGNM_log_bootstrap") }else{ DirectoryName_vec=c(paste0("CGNM_log_",logLocation$runSetting$runName),paste0("CGNM_log_",logLocation$runSetting$runName,"bootstrap")) } }else{ warning("DirectoryName need to be either the CGNM_result object or a string") } load(paste0(DirectoryName_vec[1],"/iteration_1.RDATA")) data=makeSSRsurfaceDataset(logLocation, TRUE, numBins, NA, ParameterNames, ReparameterizationDef, FALSE) likelihoodSurfacePlot_df=data$likelihoodSurfacePlot_df minSSR=min(likelihoodSurfacePlot_df$negative2LogLikelihood) likelihoodSurfacePlot_df$belowSignificance=(likelihoodSurfacePlot_df$negative2LogLikelihood-qchisq(1-alpha,1)-minSSR<0) paraKind=unique(likelihoodSurfacePlot_df$parameterName) upperBound_vec=c() lowerBound_vec=c() for(para_nu in paraKind){ dataframe_nu=subset(likelihoodSurfacePlot_df,parameterName==para_nu) upperBoundIndex=which(max(dataframe_nu$value[dataframe_nu$belowSignificance])==dataframe_nu$value) lowerBoundIndex=which(min(dataframe_nu$value[dataframe_nu$belowSignificance])==dataframe_nu$value) theoreticalLB=CGNM_result$runSetting$lowerBound[CGNM_result$runSetting$ParameterNames==para_nu] theoreticalUB=CGNM_result$runSetting$upperBound[CGNM_result$runSetting$ParameterNames==para_nu] if(lowerBoundIndex==1){ if(!is.na(theoreticalLB)){ lowerBound=(dataframe_nu$value[lowerBoundIndex]+theoreticalLB)/2 }else{ lowerBound=dataframe_nu$value[lowerBoundIndex]*10 } }else{ lowerBound=(dataframe_nu$value[lowerBoundIndex]+dataframe_nu$value[lowerBoundIndex+1])/2 } if(upperBoundIndex==length(dataframe_nu$value)){ if(!is.na(theoreticalUB)){ upperBound_suggest=(dataframe_nu$value[upperBoundIndex]+theoreticalUB)/2 }else{ upperBound_suggest=10^ceiling(log10(dataframe_nu$value[upperBoundIndex]))*10 } }else if((upperBoundIndex+2)<=length(dataframe_nu$value)){ upperBound_suggest=dataframe_nu$value[upperBoundIndex+2] }else{ if(!is.na(theoreticalUB)){ upperBound=(dataframe_nu$value[upperBoundIndex]+dataframe_nu$value[upperBoundIndex-1])/2 width=upperBound-lowerBound if((upperBound+width)<theoreticalUB){ upperBound_suggest=(upperBound+width) }else{ upperBound_suggest=(upperBound+theoreticalUB)/2 } }else{ upperBound=(dataframe_nu$value[upperBoundIndex]+dataframe_nu$value[upperBoundIndex-1])/2 upperBound_suggest=10^ceiling(log10(upperBound))*10 } } upperBound_vec=c(upperBound_vec,upperBound_suggest) } return(upperBound_vec) } #' @title plot_simulationWithCI #' @description #' Plot model simulation where the various parameter combinations are provided and conduct simulations and then the confidence interval (or more like a confidence region) is plotted. #' @param simulationFunction (required input) \emph{A function} that maps the parameter vector to the simulation. #' @param parameter_matrix (required input) \emph{A matrix of numbers} where each row contains the parameter combination that will be used for the simulations. #' @param independentVariableVector (default: NA) \emph{A vector of numbers} that represents the independent variables of each points of the simulation (e.g., observation time) where used for the values of x-axis when plotting. If set at NA then sequence of 1,2,3,... will be used. #' @param dependentVariableTypeVector (default: NA) \emph{A vector of strings} specify the kind of variable the simulationFunction simulate out. (i.e., if it simulate both PK and PD then indicate which simulation output is PK and which is PD). #' @param confidenceLevels (default: c(25,75)) \emph{A vector of two numbers between 0 and 1} set the confidence interval that will be used for the plot. Default is inter-quartile range. #' @param observationVector (default: NA) \emph{A vector of numbers} used when wishing to overlay the plot of observations to the simulation. #' @param observationIndpendentVariableVector (default: NA) \emph{A vector of numbers} used when wishing to overlay the plot of observations to the simulation. #' @param observationDependentVariableTypeVector (default: NA) \emph{A vector of numbers} used when wishing to overlay the plot of observations to the simulation. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' (Cp) #'} #' #' observation=(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, num_iteration = 10, num_minimizersToFind = 100, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' lowerBound=rep(0,3), ParameterNames=c("Ka","V1","CL_2"), saveLog = FALSE) #' #' CGNM_bootstrap=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, #' nonlinearFunction=model_analytic_function, num_bootstrapSample=100) #' #' plot_simulationWithCI(model_analytic_function, as.matrix(CGNM_result$bootstrapTheta), #' independentVariableVector=observation_time, observationVector=observation) #' } #' @export #' @import ggplot2 plot_simulationWithCI=function(simulationFunction, parameter_matrix, independentVariableVector=NA, dependentVariableTypeVector=NA, confidenceLevels=c(0.25,0.75), observationVector=NA, observationIndpendentVariableVector=NA, observationDependentVariableTypeVector=NA){ CGNM_result=NULL independentVariable=NULL dependentVariableType=NULL lower_percentile=NULL upper_percentile=NULL observation=NULL lengthSimulation=length(simulationFunction(as.numeric(parameter_matrix[1,]))) ValidIndependentVariableInput=TRUE if(is.na(independentVariableVector[1])){ ValidIndependentVariableInput=FALSE warning("independentVariableVector was not provided so replaced with seq(1,length of simulation)") }else if(length(independentVariableVector)!=lengthSimulation){ ValidIndependentVariableInput=FALSE warning("length of independentVariableVector was not the same length as the output of the simulationFunction so replaced with seq(1,length of output of simulation)") } if(!ValidIndependentVariableInput){ independentVariableVector=seq(1,lengthSimulation) } ValidobservationVectorInput=TRUE if(is.na(observationVector[1])){ ValidobservationVectorInput=FALSE } if(ValidobservationVectorInput&is.na(observationIndpendentVariableVector[1])){ observationIndpendentVariableVector=independentVariableVector warning("since observationIndpendentVariableVector is not provided replace it with independentVariableVector") } if(length(observationVector)!=length(observationIndpendentVariableVector)){ ValidobservationVectorInput=FALSE warning("observationVector and observationIndpendentVariableVector need to be the same length hence observations will not be overlayed") } validDependentVariableTypeVectorInput=TRUE if(is.na(dependentVariableTypeVector[1])){ validDependentVariableTypeVectorInput=FALSE }else if(length(dependentVariableTypeVector)!=lengthSimulation){ dependentVariableTypeVector=NA validDependentVariableTypeVectorInput=FALSE warning("dependentVariableTypeVector was not the same length as the output of the simulationFunction so replaced with NA") } plot_df=data.frame() for(i in seq(1,dim(parameter_matrix)[1] )){ plot_df=rbind(plot_df, data.frame(simulation=simulationFunction(as.numeric(parameter_matrix[i,])), independentVariable=independentVariableVector, dependentVariableType=dependentVariableTypeVector)) } median_vec=c() lower_percentile_vec=c() upper_percentile_vec=c() kind_df=unique(plot_df[,c("independentVariable", "dependentVariableType")]) for(i in seq(1,dim(kind_df)[1])){ kind=kind_df[i,] if(validDependentVariableTypeVectorInput){ now_data_df=subset(plot_df, independentVariable==kind$independentVariable&dependentVariableType==kind$dependentVariableType ) }else{ now_data_df=subset(plot_df, independentVariable==kind$independentVariable ) } nowQuantile=quantile(now_data_df$simulation, probs = c(confidenceLevels[1],0.5,confidenceLevels[2]), na.rm = TRUE) lower_percentile_vec=c(lower_percentile_vec,nowQuantile[1]) median_vec=c(median_vec,nowQuantile[2]) upper_percentile_vec=c(upper_percentile_vec,nowQuantile[3]) } plot_CI_df=kind_df plot_CI_df$lower_percentile=as.numeric(lower_percentile_vec) plot_CI_df$upper_percentile=as.numeric(upper_percentile_vec) plot_CI_df$median=as.numeric(median_vec) g=ggplot2::ggplot(plot_CI_df, aes(x=independentVariable , y=median ))+ggplot2::geom_line()+ggplot2::geom_ribbon(aes(ymin=lower_percentile, ymax=upper_percentile), alpha=0.2)+ ggplot2::labs(caption = paste0("solide line is the median of the model prediction and shaded area is its confidence interval of ",confidenceLevels[1]*100,"-",confidenceLevels[2]*100," percentile")) if(validDependentVariableTypeVectorInput){ g=g+ggplot2::facet_wrap(.~dependentVariableType) } if(ValidobservationVectorInput){ g=g+ggplot2::geom_point(data=data.frame(independentVariable=observationIndpendentVariableVector, observation=observationVector, dependentVariableType=observationDependentVariableTypeVector), colour="red", aes(x=independentVariable,y=observation), inherit.aes = FALSE) } g=g+ggplot2::ylab("Dependent variable") return(g) } #' @title plot_simulationMatrixWithCI #' @description #' Plot simulation that are provided to plot confidence interval (or more like a confidence region). #' @param simulationMatrix (required input) \emph{A matrix of numbers} where each row contains the simulated values that will be plotted. #' @param independentVariableVector (default: NA) \emph{A vector of numbers} that represents the independent variables of each points of the simulation (e.g., observation time) where used for the values of x-axis when plotting. If set at NA then sequence of 1,2,3,... will be used. #' @param dependentVariableTypeVector (default: NA) \emph{A vector of strings} specify the kind of variable the simulation values are. (i.e., if it simulate both PK and PD then indicate which simulation value is PK and which is PD). #' @param confidenceLevels (default: c(25,75)) \emph{A vector of two numbers between 0 and 1} set the confidence interval that will be used for the plot. Default is inter-quartile range. #' @param observationVector (default: NA) \emph{A vector of numbers} used when wishing to overlay the plot of observations to the simulation. #' @param observationIndpendentVariableVector (default: NA) \emph{A vector of numbers} used when wishing to overlay the plot of observations to the simulation. #' @param observationDependentVariableTypeVector (default: NA) \emph{A vector of numbers} used when wishing to overlay the plot of observations to the simulation. #' @return \emph{A ggplot object} including the violin plot, interquartile range and median, minimum and maximum. #' @examples #'\dontrun{ #'model_analytic_function=function(x){ #' #' observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) #' Dose=1000 #' F=1 #' #' ka=x[1] #' V1=x[2] #' CL_2=x[3] #' t=observation_time #' #' Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) #' #' (Cp) #'} #' #' observation=(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) #' #' CGNM_result=Cluster_Gauss_Newton_method( #' nonlinearFunction=model_analytic_function, #' targetVector = observation, num_iteration = 10, num_minimizersToFind = 100, #' initial_lowerRange = c(0.1,0.1,0.1), initial_upperRange = c(10,10,10), #' lowerBound=rep(0,3), ParameterNames=c("Ka","V1","CL_2"), saveLog = FALSE) #' #' CGNM_bootstrap=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, #' nonlinearFunction=model_analytic_function, num_bootstrapSample=100) #' #' #' plot_simulationMatrixWithCI(CGNM_result$bootstrapY, #' independentVariableVector=observation_time, observationVector=observation) #' } #' @export #' @import ggplot2 plot_simulationMatrixWithCI=function(simulationMatrix, independentVariableVector=NA, dependentVariableTypeVector=NA, confidenceLevels=c(0.25,0.75), observationVector=NA, observationIndpendentVariableVector=NA, observationDependentVariableTypeVector=NA){ CGNM_result=NULL independentVariable=NULL dependentVariableType=NULL lower_percentile=NULL upper_percentile=NULL observation=NULL lengthSimulation=dim(simulationMatrix)[2] ValidIndependentVariableInput=TRUE if(is.na(independentVariableVector[1])){ ValidIndependentVariableInput=FALSE warning("independentVariableVector was not provided so replaced with seq(1,length of simulation)") }else if(length(independentVariableVector)!=lengthSimulation){ ValidIndependentVariableInput=FALSE warning("length of independentVariableVector was not the same length as the output of the simulationFunction so replaced with seq(1,length of output of simulation)") } if(!ValidIndependentVariableInput){ independentVariableVector=seq(1,lengthSimulation) } ValidobservationVectorInput=TRUE if(is.na(observationVector[1])){ ValidobservationVectorInput=FALSE } if(ValidobservationVectorInput&is.na(observationIndpendentVariableVector[1])){ observationIndpendentVariableVector=independentVariableVector warning("since observationIndpendentVariableVector is not provided replace it with independentVariableVector") } if(length(observationVector)!=length(observationIndpendentVariableVector)){ ValidobservationVectorInput=FALSE warning("observationVector and observationIndpendentVariableVector need to be the same length hence observations will not be overlayed") } validDependentVariableTypeVectorInput=TRUE if(is.na(dependentVariableTypeVector[1])){ validDependentVariableTypeVectorInput=FALSE }else if(length(dependentVariableTypeVector)!=lengthSimulation){ dependentVariableTypeVector=NA validDependentVariableTypeVectorInput=FALSE warning("dependentVariableTypeVector was not the same length as the output of the simulationFunction so replaced with NA") } plot_df=data.frame() for(i in seq(1,dim(simulationMatrix)[1] )){ plot_df=rbind(plot_df, data.frame(simulation=simulationMatrix[i,], independentVariable=independentVariableVector, dependentVariableType=dependentVariableTypeVector)) } median_vec=c() lower_percentile_vec=c() upper_percentile_vec=c() kind_df=unique(plot_df[,c("independentVariable", "dependentVariableType")]) for(i in seq(1,dim(kind_df)[1])){ kind=kind_df[i,] if(validDependentVariableTypeVectorInput){ now_data_df=subset(plot_df, independentVariable==kind$independentVariable&dependentVariableType==kind$dependentVariableType ) }else{ now_data_df=subset(plot_df, independentVariable==kind$independentVariable ) } nowQuantile=quantile(now_data_df$simulation, probs = c(confidenceLevels[1],0.5,confidenceLevels[2]), na.rm = TRUE) lower_percentile_vec=c(lower_percentile_vec,nowQuantile[1]) median_vec=c(median_vec,nowQuantile[2]) upper_percentile_vec=c(upper_percentile_vec,nowQuantile[3]) } plot_CI_df=kind_df plot_CI_df$lower_percentile=as.numeric(lower_percentile_vec) plot_CI_df$upper_percentile=as.numeric(upper_percentile_vec) plot_CI_df$median=as.numeric(median_vec) g=ggplot2::ggplot(plot_CI_df, aes(x=independentVariable , y=median ))+ggplot2::geom_line()+ggplot2::geom_ribbon(aes(ymin=lower_percentile, ymax=upper_percentile), alpha=0.2)+ ggplot2::labs(caption = paste0("solide line is the median of the model prediction and shaded area is its confidence interval of ",confidenceLevels[1]*100,"-",confidenceLevels[2]*100," percentile")) if(validDependentVariableTypeVectorInput){ g=g+ggplot2::facet_wrap(.~dependentVariableType) } if(ValidobservationVectorInput){ g=g+ggplot2::geom_point(data=data.frame(independentVariable=observationIndpendentVariableVector, observation=observationVector, dependentVariableType=observationDependentVariableTypeVector), colour="red", aes(x=independentVariable,y=observation), inherit.aes = FALSE) } g=g+ggplot2::ylab("Dependent variable")+ggplot2::xlab("Independent variable") return(g) }
/scratch/gouwar.j/cran-all/cranData/CGNM/R/PostProcess.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(CGNM) library(knitr) ## ----define the model function------------------------------------------------ model_function=function(x){ observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) Dose=1000 F=1 ka=x[1] V1=x[2] CL_2=x[3] t=observation_time Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) log10(Cp) } ## ----------------------------------------------------------------------------- observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) ## ---- warning = FALSE--------------------------------------------------------- CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_function, targetVector = observation, initial_lowerRange =rep(0.01,3),initial_upperRange = rep(100,3),lowerBound = rep(0,3), saveLog=TRUE, num_minimizersToFind = 500, ParameterNames = c("Ka","V1","CL")) ## ----------------------------------------------------------------------------- kable(head(acceptedApproximateMinimizers(CGNM_result))) ## ----------------------------------------------------------------------------- kable(table_parameterSummary(CGNM_result)) ## ----------------------------------------------------------------------------- CGNM_bootstrap=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, nonlinearFunction=model_function) ## ----------------------------------------------------------------------------- kable(table_parameterSummary(CGNM_bootstrap)) ## ----------------------------------------------------------------------------- library(ggplot2) ## ---- fig.width=6, fig.height=3.5--------------------------------------------- plot_Rank_SSR(CGNM_result) ## ---- fig.width=6, fig.height=3.5--------------------------------------------- plot_paraDistribution_byHistogram(CGNM_bootstrap, bins = 50)+scale_x_continuous(trans="log10") ## ---- fig.width = 7----------------------------------------------------------- plot_goodnessOfFit(CGNM_result, plotType = 1, independentVariableVector = c(0.1,0.2,0.4,0.6,1,2,3,6,12), plotRank = seq(1,50)) ## ---- fig.width = 7----------------------------------------------------------- plot_goodnessOfFit(CGNM_bootstrap, plotType = 1, independentVariableVector = c(0.1,0.2,0.4,0.6,1,2,3,6,12)) ## ---- fig.width = 7----------------------------------------------------------- plot_profileLikelihood(c("CGNM_log","CGNM_log_bootstrap"))+scale_x_continuous(trans="log10") ## ----------------------------------------------------------------------------- kable(table_profileLikelihoodConfidenceInterval(c("CGNM_log","CGNM_log_bootstrap"), alpha = 0.25)) ## ---- fig.width = 7, fig.height = 6------------------------------------------- plot_2DprofileLikelihood(CGNM_result, showInitialRange=FALSE, alpha = 0.05)+scale_x_continuous(trans="log10")+scale_y_continuous(trans="log10") ## ----------------------------------------------------------------------------- model_matrix_function=function(X){ Y_list=lapply(split(X, rep(seq(1:nrow(X)),ncol(X))), model_function) Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) } testX=t(matrix(c(rep(0.01,3),rep(10,3),rep(100,3)), nrow = 3)) print("testX") print(testX) print("model_matrix_function(testX)") print(model_matrix_function(testX)) print("model_matrix_function(testX)-rbind(model_function(testX[1,]),model_function(testX[2,]),model_function(testX[3,]))") print(model_matrix_function(testX)-rbind(model_function(testX[1,]),model_function(testX[2,]),model_function(testX[3,]))) ## ----------------------------------------------------------------------------- # library(parallel) # # obsLength=length(observation) # ## Given CGNM searches through wide range of parameter combination, it can encounter ## parameter combinations that is not feasible to evaluate. This try catch function ## is implemented within CGNM for regular functions but for the matrix functions ## user needs to implement outside of CGNM # # modelFunction_tryCatch=function(x_in){ # out=tryCatch({model_function(x_in)}, # error=function(cond) {rep(NA, obsLength)} # ) # return(out) # } # # model_matrix_function=function(X){ # Y_list=mclapply(split(X, rep(seq(1:nrow(X)),ncol(X))), modelFunction_tryCatch,mc.cores = (parallel::detectCores()-1), mc.preschedule = FALSE) # # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) # # return(Y) # } ## ----------------------------------------------------------------------------- #library(foreach) #library(doParallel) #numCore=8 #registerDoParallel(numCore-1) #cluster=makeCluster(numCore-1, type = "PSOCK") #registerDoParallel(cl=cluster) # obsLength=length(observation) ## Given CGNM searches through wide range of parameter combination, it can encounter ## parameter combinations that is not feasible to evaluate. This try catch function ## is implemented within CGNM for regular functions but for the matrix functions ## user needs to implement outside of CGNM # modelFunction_tryCatch=function(x_in){ # out=tryCatch({model_function(x_in)}, # error=function(cond) {rep(NA, obsLength)} # ) # return(out) # } #model_matrix_function=function(X){ # Y_list=foreach(i=1:dim(X)[1], .export = c("model_function", "modelFunction_tryCatch"))%dopar%{ #make sure to include all related functions in .export and all used packages in .packages for more information read documentation of dopar # modelFunction_tryCatch((X[i,])) # } # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) #} ## ----------------------------------------------------------------------------- CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_matrix_function, targetVector = observation, initial_lowerRange =rep(0.01,3),initial_upperRange = rep(100,3),lowerBound = rep(0,3), saveLog=TRUE, num_minimizersToFind = 500, ParameterNames = c("Ka","V1","CL")) #stopCluster(cluster) #make sure to close the created cluster if needed ## ----------------------------------------------------------------------------- unlink("CGNM_log", recursive=TRUE) unlink("CGNM_log_bootstrap", recursive=TRUE)
/scratch/gouwar.j/cran-all/cranData/CGNM/inst/doc/CGNM-vignette.R
--- title: "CGNM: Cluster Gauss-Newton Method" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{CGNM: Cluster Gauss-Newton Method} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(CGNM) library(knitr) ``` # When and when not to use CGNM ## Use CGNM - Wish to fit relatively complex parameterized model/curve/function to the data; however, unsure of the appropriate initial guess (e.g., "start" argument in nls function). => CGNM searches the parameter from multiple initial guess so that the use can specify rough initial range instead of a point initial guess. - When the practical identifiability (if there is only one best fit parameter or not) is unknown. => CGNM will find multiple set of best fit parameters; hence if the parameter is not practically identifiable then the multiple best-fit parameters found by CGNM will not converge to a point. - When the model is a blackbox (i.e., cannot be explicitly/easily write out as a "formula") and the model may not be continuous with respect to the parameter. => CGNM makes minimum assumptions on the model so all user need to provide is a function that takes the model parameter and simulation (and what happen in the function, CGNM does not care). ## Not to use CGNM - When the you already know where approximately the best fit parameter is and you just need to find one best fit parameter. => Simply use nls and that will be faster. - When the model is relatively simple and computation cost is not an issue. => CGNM is made to save the number of model evaluation during the parameter estimation, so may not see much advantage compared to the conventional multi-start methods (e.g.repeatedly using nls from various "start"). # How to use CGNM To illustrate the use of CGNM here we illustrate how CGNM can be used to estimate two sets of the best fit parameters of the pharmacokinetics model when the drug is administered orally (known as flip-flop kinetics). ## Prepare the model ($\boldsymbol f$) ```{r define the model function} model_function=function(x){ observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) Dose=1000 F=1 ka=x[1] V1=x[2] CL_2=x[3] t=observation_time Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) log10(Cp) } ``` ## Prepare the data ($\boldsymbol y^*$) ```{r} observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) ``` ## Run Cluster_Gauss_Newton_method Here we have specified the upper and lower range of the initial guess. ```{r, warning = FALSE} CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_function, targetVector = observation, initial_lowerRange =rep(0.01,3),initial_upperRange = rep(100,3),lowerBound = rep(0,3), saveLog=TRUE, num_minimizersToFind = 500, ParameterNames = c("Ka","V1","CL")) ``` ## Obtain the approximate minimizers ```{r} kable(head(acceptedApproximateMinimizers(CGNM_result))) ``` ```{r} kable(table_parameterSummary(CGNM_result)) ``` ## Can run residual resampling bootstrap analyses using CGNM as well ```{r} CGNM_bootstrap=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, nonlinearFunction=model_function) ``` ```{r} kable(table_parameterSummary(CGNM_bootstrap)) ``` ## Visualize the CGNM modelfit analysis result To use the plot functions the user needs to manually load ggplot2. ```{r} library(ggplot2) ``` ### Inspect the distribution of SSR of approximate minimizers found by CGNM Despite the robustness of the algorithm not all approximate minimizers converge so here we visually inspect to see how many of the approximate minimizers we consider to have the similar SSR to the minimum SSR. Currently the algorithm automatically choose "acceptable" approximate minimizer based on Grubbs' Test for Outliers. If for whatever the reason this criterion is not satisfactly the users can manually set the indicies of the acceptable approximat minimizers. ```{r, fig.width=6, fig.height=3.5} plot_Rank_SSR(CGNM_result) ``` ```{r, fig.width=6, fig.height=3.5} plot_paraDistribution_byHistogram(CGNM_bootstrap, bins = 50)+scale_x_continuous(trans="log10") ``` ### visually inspect goodness of fit of top 50 approximate minimizers ```{r, fig.width = 7} plot_goodnessOfFit(CGNM_result, plotType = 1, independentVariableVector = c(0.1,0.2,0.4,0.6,1,2,3,6,12), plotRank = seq(1,50)) ``` ### plot model prediction with uncertainties based on residual resampling bootstrap analysis ```{r, fig.width = 7} plot_goodnessOfFit(CGNM_bootstrap, plotType = 1, independentVariableVector = c(0.1,0.2,0.4,0.6,1,2,3,6,12)) ``` ### plot profile likelihood ```{r, fig.width = 7} plot_profileLikelihood(c("CGNM_log","CGNM_log_bootstrap"))+scale_x_continuous(trans="log10") ``` ```{r} kable(table_profileLikelihoodConfidenceInterval(c("CGNM_log","CGNM_log_bootstrap"), alpha = 0.25)) ``` ### plot profile likelihood surface ```{r, fig.width = 7, fig.height = 6} plot_2DprofileLikelihood(CGNM_result, showInitialRange=FALSE, alpha = 0.05)+scale_x_continuous(trans="log10")+scale_y_continuous(trans="log10") ``` ## Parallel computation Cluster Gauss Newton method implementation in CGNM package (above version 0.6) can use nonlinear function that takes multiple input vectors stored in matrix (each column as the input vector) and output matrix (each column as the output vector). This implementation was to be used to parallelize the computation. See below for the examples of parallelized implementation in various hardware. Cluster Gauss Newton method is embarrassingly parallelizable so the computation speed is almost proportional to the number of computation cores used especially for the nonlinear functions that takes time to compute (e.g. models with numerical method to solve a large system of ODEs). ```{r} model_matrix_function=function(X){ Y_list=lapply(split(X, rep(seq(1:nrow(X)),ncol(X))), model_function) Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) } testX=t(matrix(c(rep(0.01,3),rep(10,3),rep(100,3)), nrow = 3)) print("testX") print(testX) print("model_matrix_function(testX)") print(model_matrix_function(testX)) print("model_matrix_function(testX)-rbind(model_function(testX[1,]),model_function(testX[2,]),model_function(testX[3,]))") print(model_matrix_function(testX)-rbind(model_function(testX[1,]),model_function(testX[2,]),model_function(testX[3,]))) ``` ### an example of parallel implementation for Mac using parallel package ```{r} # library(parallel) # # obsLength=length(observation) # ## Given CGNM searches through wide range of parameter combination, it can encounter ## parameter combinations that is not feasible to evaluate. This try catch function ## is implemented within CGNM for regular functions but for the matrix functions ## user needs to implement outside of CGNM # # modelFunction_tryCatch=function(x_in){ # out=tryCatch({model_function(x_in)}, # error=function(cond) {rep(NA, obsLength)} # ) # return(out) # } # # model_matrix_function=function(X){ # Y_list=mclapply(split(X, rep(seq(1:nrow(X)),ncol(X))), modelFunction_tryCatch,mc.cores = (parallel::detectCores()-1), mc.preschedule = FALSE) # # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) # # return(Y) # } ``` ### an example of parallel implementation for Windows using foreach and doParllel packages ```{r} #library(foreach) #library(doParallel) #numCore=8 #registerDoParallel(numCore-1) #cluster=makeCluster(numCore-1, type = "PSOCK") #registerDoParallel(cl=cluster) # obsLength=length(observation) ## Given CGNM searches through wide range of parameter combination, it can encounter ## parameter combinations that is not feasible to evaluate. This try catch function ## is implemented within CGNM for regular functions but for the matrix functions ## user needs to implement outside of CGNM # modelFunction_tryCatch=function(x_in){ # out=tryCatch({model_function(x_in)}, # error=function(cond) {rep(NA, obsLength)} # ) # return(out) # } #model_matrix_function=function(X){ # Y_list=foreach(i=1:dim(X)[1], .export = c("model_function", "modelFunction_tryCatch"))%dopar%{ #make sure to include all related functions in .export and all used packages in .packages for more information read documentation of dopar # modelFunction_tryCatch((X[i,])) # } # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) #} ``` ```{r} CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_matrix_function, targetVector = observation, initial_lowerRange =rep(0.01,3),initial_upperRange = rep(100,3),lowerBound = rep(0,3), saveLog=TRUE, num_minimizersToFind = 500, ParameterNames = c("Ka","V1","CL")) #stopCluster(cluster) #make sure to close the created cluster if needed ``` ```{r} unlink("CGNM_log", recursive=TRUE) unlink("CGNM_log_bootstrap", recursive=TRUE) ``` # What is CGNM? For the complete description and comparison with the conventional algorithm please see (https: //doi.org/10.1007/s11081-020-09571-2): Aoki, Y., Hayami, K., Toshimoto, K., & Sugiyama, Y. (2020). Cluster Gauss–Newton method. Optimization and Engineering, 1-31. ## The mathematical problem CGNM solves Cluster Gauss-Newton method is an algorithm for obtaining multiple minimisers of nonlinear least squares problems $$ \min_{\boldsymbol{x}}|| \boldsymbol{f}(\boldsymbol x)-\boldsymbol{y}^*||_2^{\,2} $$ which do not have a unique solution (global minimiser), that is to say, there exist $\boldsymbol x^{(1)}\neq\boldsymbol x^{(2)}$ such that $$ \min_{\boldsymbol{x}}|| \boldsymbol{f}(\boldsymbol x)-\boldsymbol{y}^*||_2^{\,2}=|| \boldsymbol{f}(\boldsymbol x^{(1)})-\boldsymbol{y}^*||_2^{\,2}=|| \boldsymbol{f}(\boldsymbol x^{(2)})-\boldsymbol{y}^*||_2^{\,2} \,. $$ Parameter estimation problems of mathematical models can often be formulated as nonlinear least squares problems. Typically these problems are solved numerically using iterative methods. The local minimiser obtained using these iterative methods usually depends on the choice of the initial iterate. Thus, the estimated parameter and subsequent analyses using it depend on the choice of the initial iterate. One way to reduce the analysis bias due to the choice of the initial iterate is to repeat the algorithm from multiple initial iterates (i.e. use a multi-start method). However, the procedure can be computationally intensive and is not always used in practice. To overcome this problem, we propose the Cluster Gauss-Newton method (CGNM), an efficient algorithm for finding multiple approximate minimisers of nonlinear-least squares problems. CGN simultaneously solves the nonlinear least squares problem from multiple initial iterates. Then, CGNM iteratively improves the approximations from these initial iterates similarly to the Gauss-Newton method. However, it uses a global linear approximation instead of the Jacobian. The global linear approximations are computed collectively among all the iterates to minimise the computational cost associated with the evaluation of the mathematical model.
/scratch/gouwar.j/cran-all/cranData/CGNM/inst/doc/CGNM-vignette.Rmd
--- title: "CGNM: Cluster Gauss-Newton Method" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{CGNM: Cluster Gauss-Newton Method} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(CGNM) library(knitr) ``` # When and when not to use CGNM ## Use CGNM - Wish to fit relatively complex parameterized model/curve/function to the data; however, unsure of the appropriate initial guess (e.g., "start" argument in nls function). => CGNM searches the parameter from multiple initial guess so that the use can specify rough initial range instead of a point initial guess. - When the practical identifiability (if there is only one best fit parameter or not) is unknown. => CGNM will find multiple set of best fit parameters; hence if the parameter is not practically identifiable then the multiple best-fit parameters found by CGNM will not converge to a point. - When the model is a blackbox (i.e., cannot be explicitly/easily write out as a "formula") and the model may not be continuous with respect to the parameter. => CGNM makes minimum assumptions on the model so all user need to provide is a function that takes the model parameter and simulation (and what happen in the function, CGNM does not care). ## Not to use CGNM - When the you already know where approximately the best fit parameter is and you just need to find one best fit parameter. => Simply use nls and that will be faster. - When the model is relatively simple and computation cost is not an issue. => CGNM is made to save the number of model evaluation during the parameter estimation, so may not see much advantage compared to the conventional multi-start methods (e.g.repeatedly using nls from various "start"). # How to use CGNM To illustrate the use of CGNM here we illustrate how CGNM can be used to estimate two sets of the best fit parameters of the pharmacokinetics model when the drug is administered orally (known as flip-flop kinetics). ## Prepare the model ($\boldsymbol f$) ```{r define the model function} model_function=function(x){ observation_time=c(0.1,0.2,0.4,0.6,1,2,3,6,12) Dose=1000 F=1 ka=x[1] V1=x[2] CL_2=x[3] t=observation_time Cp=ka*F*Dose/(V1*(ka-CL_2/V1))*(exp(-CL_2/V1*t)-exp(-ka*t)) log10(Cp) } ``` ## Prepare the data ($\boldsymbol y^*$) ```{r} observation=log10(c(4.91, 8.65, 12.4, 18.7, 24.3, 24.5, 18.4, 4.66, 0.238)) ``` ## Run Cluster_Gauss_Newton_method Here we have specified the upper and lower range of the initial guess. ```{r, warning = FALSE} CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_function, targetVector = observation, initial_lowerRange =rep(0.01,3),initial_upperRange = rep(100,3),lowerBound = rep(0,3), saveLog=TRUE, num_minimizersToFind = 500, ParameterNames = c("Ka","V1","CL")) ``` ## Obtain the approximate minimizers ```{r} kable(head(acceptedApproximateMinimizers(CGNM_result))) ``` ```{r} kable(table_parameterSummary(CGNM_result)) ``` ## Can run residual resampling bootstrap analyses using CGNM as well ```{r} CGNM_bootstrap=Cluster_Gauss_Newton_Bootstrap_method(CGNM_result, nonlinearFunction=model_function) ``` ```{r} kable(table_parameterSummary(CGNM_bootstrap)) ``` ## Visualize the CGNM modelfit analysis result To use the plot functions the user needs to manually load ggplot2. ```{r} library(ggplot2) ``` ### Inspect the distribution of SSR of approximate minimizers found by CGNM Despite the robustness of the algorithm not all approximate minimizers converge so here we visually inspect to see how many of the approximate minimizers we consider to have the similar SSR to the minimum SSR. Currently the algorithm automatically choose "acceptable" approximate minimizer based on Grubbs' Test for Outliers. If for whatever the reason this criterion is not satisfactly the users can manually set the indicies of the acceptable approximat minimizers. ```{r, fig.width=6, fig.height=3.5} plot_Rank_SSR(CGNM_result) ``` ```{r, fig.width=6, fig.height=3.5} plot_paraDistribution_byHistogram(CGNM_bootstrap, bins = 50)+scale_x_continuous(trans="log10") ``` ### visually inspect goodness of fit of top 50 approximate minimizers ```{r, fig.width = 7} plot_goodnessOfFit(CGNM_result, plotType = 1, independentVariableVector = c(0.1,0.2,0.4,0.6,1,2,3,6,12), plotRank = seq(1,50)) ``` ### plot model prediction with uncertainties based on residual resampling bootstrap analysis ```{r, fig.width = 7} plot_goodnessOfFit(CGNM_bootstrap, plotType = 1, independentVariableVector = c(0.1,0.2,0.4,0.6,1,2,3,6,12)) ``` ### plot profile likelihood ```{r, fig.width = 7} plot_profileLikelihood(c("CGNM_log","CGNM_log_bootstrap"))+scale_x_continuous(trans="log10") ``` ```{r} kable(table_profileLikelihoodConfidenceInterval(c("CGNM_log","CGNM_log_bootstrap"), alpha = 0.25)) ``` ### plot profile likelihood surface ```{r, fig.width = 7, fig.height = 6} plot_2DprofileLikelihood(CGNM_result, showInitialRange=FALSE, alpha = 0.05)+scale_x_continuous(trans="log10")+scale_y_continuous(trans="log10") ``` ## Parallel computation Cluster Gauss Newton method implementation in CGNM package (above version 0.6) can use nonlinear function that takes multiple input vectors stored in matrix (each column as the input vector) and output matrix (each column as the output vector). This implementation was to be used to parallelize the computation. See below for the examples of parallelized implementation in various hardware. Cluster Gauss Newton method is embarrassingly parallelizable so the computation speed is almost proportional to the number of computation cores used especially for the nonlinear functions that takes time to compute (e.g. models with numerical method to solve a large system of ODEs). ```{r} model_matrix_function=function(X){ Y_list=lapply(split(X, rep(seq(1:nrow(X)),ncol(X))), model_function) Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) } testX=t(matrix(c(rep(0.01,3),rep(10,3),rep(100,3)), nrow = 3)) print("testX") print(testX) print("model_matrix_function(testX)") print(model_matrix_function(testX)) print("model_matrix_function(testX)-rbind(model_function(testX[1,]),model_function(testX[2,]),model_function(testX[3,]))") print(model_matrix_function(testX)-rbind(model_function(testX[1,]),model_function(testX[2,]),model_function(testX[3,]))) ``` ### an example of parallel implementation for Mac using parallel package ```{r} # library(parallel) # # obsLength=length(observation) # ## Given CGNM searches through wide range of parameter combination, it can encounter ## parameter combinations that is not feasible to evaluate. This try catch function ## is implemented within CGNM for regular functions but for the matrix functions ## user needs to implement outside of CGNM # # modelFunction_tryCatch=function(x_in){ # out=tryCatch({model_function(x_in)}, # error=function(cond) {rep(NA, obsLength)} # ) # return(out) # } # # model_matrix_function=function(X){ # Y_list=mclapply(split(X, rep(seq(1:nrow(X)),ncol(X))), modelFunction_tryCatch,mc.cores = (parallel::detectCores()-1), mc.preschedule = FALSE) # # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) # # return(Y) # } ``` ### an example of parallel implementation for Windows using foreach and doParllel packages ```{r} #library(foreach) #library(doParallel) #numCore=8 #registerDoParallel(numCore-1) #cluster=makeCluster(numCore-1, type = "PSOCK") #registerDoParallel(cl=cluster) # obsLength=length(observation) ## Given CGNM searches through wide range of parameter combination, it can encounter ## parameter combinations that is not feasible to evaluate. This try catch function ## is implemented within CGNM for regular functions but for the matrix functions ## user needs to implement outside of CGNM # modelFunction_tryCatch=function(x_in){ # out=tryCatch({model_function(x_in)}, # error=function(cond) {rep(NA, obsLength)} # ) # return(out) # } #model_matrix_function=function(X){ # Y_list=foreach(i=1:dim(X)[1], .export = c("model_function", "modelFunction_tryCatch"))%dopar%{ #make sure to include all related functions in .export and all used packages in .packages for more information read documentation of dopar # modelFunction_tryCatch((X[i,])) # } # Y=t(matrix(unlist(Y_list),ncol=length(Y_list))) #} ``` ```{r} CGNM_result=Cluster_Gauss_Newton_method(nonlinearFunction=model_matrix_function, targetVector = observation, initial_lowerRange =rep(0.01,3),initial_upperRange = rep(100,3),lowerBound = rep(0,3), saveLog=TRUE, num_minimizersToFind = 500, ParameterNames = c("Ka","V1","CL")) #stopCluster(cluster) #make sure to close the created cluster if needed ``` ```{r} unlink("CGNM_log", recursive=TRUE) unlink("CGNM_log_bootstrap", recursive=TRUE) ``` # What is CGNM? For the complete description and comparison with the conventional algorithm please see (https: //doi.org/10.1007/s11081-020-09571-2): Aoki, Y., Hayami, K., Toshimoto, K., & Sugiyama, Y. (2020). Cluster Gauss–Newton method. Optimization and Engineering, 1-31. ## The mathematical problem CGNM solves Cluster Gauss-Newton method is an algorithm for obtaining multiple minimisers of nonlinear least squares problems $$ \min_{\boldsymbol{x}}|| \boldsymbol{f}(\boldsymbol x)-\boldsymbol{y}^*||_2^{\,2} $$ which do not have a unique solution (global minimiser), that is to say, there exist $\boldsymbol x^{(1)}\neq\boldsymbol x^{(2)}$ such that $$ \min_{\boldsymbol{x}}|| \boldsymbol{f}(\boldsymbol x)-\boldsymbol{y}^*||_2^{\,2}=|| \boldsymbol{f}(\boldsymbol x^{(1)})-\boldsymbol{y}^*||_2^{\,2}=|| \boldsymbol{f}(\boldsymbol x^{(2)})-\boldsymbol{y}^*||_2^{\,2} \,. $$ Parameter estimation problems of mathematical models can often be formulated as nonlinear least squares problems. Typically these problems are solved numerically using iterative methods. The local minimiser obtained using these iterative methods usually depends on the choice of the initial iterate. Thus, the estimated parameter and subsequent analyses using it depend on the choice of the initial iterate. One way to reduce the analysis bias due to the choice of the initial iterate is to repeat the algorithm from multiple initial iterates (i.e. use a multi-start method). However, the procedure can be computationally intensive and is not always used in practice. To overcome this problem, we propose the Cluster Gauss-Newton method (CGNM), an efficient algorithm for finding multiple approximate minimisers of nonlinear-least squares problems. CGN simultaneously solves the nonlinear least squares problem from multiple initial iterates. Then, CGNM iteratively improves the approximations from these initial iterates similarly to the Gauss-Newton method. However, it uses a global linear approximation instead of the Jacobian. The global linear approximations are computed collectively among all the iterates to minimise the computational cost associated with the evaluation of the mathematical model.
/scratch/gouwar.j/cran-all/cranData/CGNM/vignettes/CGNM-vignette.Rmd
CGP <- function(X,yobs,nugget_l=0.001,num_starts=5,theta_l=NULL,alpha_l=NULL,kappa_u=NULL){ yobs<-as.numeric(yobs) DD<-as.matrix(X) var_names<-colnames(DD) n<-nrow(DD) p<-ncol(DD) one<-rep(1,n) onem<-rep(1,n-1) #Standardized design matrix Stand_DD<-apply(DD,2,function(x) (x-min(x))/max(x-min(x)) ) #Scales for standardization scales<-apply(DD,2,function(x) max(x)-min(x)) if(length(theta_l)>1) print("Error: Lower bound for theta needs to be specified as a scalar!") if(length(alpha_l)>1) print("Error: Lower bound for alpha needs to be specified as a scalar!") if(length(kappa_u)>1) print("Error: Upper bound for kappa needs to be specified as a scalar!") if(is.null(theta_l)) theta_l<-0.0001 theta_lower<-rep(theta_l,p) #d_avg<-sqrt(1/mean(1/dist(Stand_DD)^2)) if(is.null(alpha_l)) alpha_l<-log(10^2)*mean(1/dist(Stand_DD)^2) theta_upper<-rep(alpha_l,p) kappa_l<-alpha_l if(is.null(kappa_u)) kappa_u<-log(10^6)*mean(1/dist(Stand_DD)^2) if(sum(theta_l>alpha_l)>0) print("Error: Lower bound of theta exceeds the upper bound!") lower=c(nugget_l,theta_lower,kappa_l,0) upper=c(1,theta_upper,kappa_u,1) # Function to construct the (n by n) correlation matrix. PSI<-function(theta){ A<-DD%*%diag(sqrt(theta),ncol=p) A<-as.matrix(dist(A, diag=T, upper=T)) R<-exp(-A^2) return(R) } Stand_PSI<-function(Stand_theta){ A<-Stand_DD%*%diag(sqrt(Stand_theta),ncol=p) A<-as.matrix(dist(A, diag=T, upper=T)) R<-exp(-A^2) return(R) } # Likelihood function var.MLE.DK<-function(ww){ lambda<-ww[1] Stand_theta<-ww[2:(p+1)] kappa<-ww[p+2] Stand_alpha<-kappa+Stand_theta bw<-ww[p+3] G<-Stand_PSI(Stand_theta) L<-Stand_PSI(Stand_alpha) Gbw<-Stand_PSI(Stand_theta*bw) Sig<-diag(n) for(rep in 1:4){ Q<-G+lambda*Sig^(1/2)%*%L%*%Sig^(1/2) invQ <- solve(Q) beta <- (one %*% invQ %*% yobs)/(one %*% invQ %*% one) temp<-invQ%*%(yobs-beta*one) gip<-beta*one+G%*%temp e<-yobs-gip Sig<-diag(c(Gbw%*%e^2/(Gbw%*%one))) Sig2<-mean(diag(Sig)) Sig<-Sig/Sig2 } Q<-G+lambda*Sig^(1/2)%*%L%*%Sig^(1/2) invQ <- solve(Q) beta <- (one %*% invQ %*% yobs)/(one %*% invQ %*% one) tau2<- t(yobs-beta*one)%*%invQ%*%(yobs-beta*one)/n val<- log(det(Q))+ n*log(tau2) if(!is.finite(val)) val<-1000000 return(val) } # Optimize the likelihood function using "num_starts" Latin-hypercube sampled points as random starts. n_par<-p+3 n_candidate<-500+num_starts LHD<-function(N,k){ x<-matrix(rep(1:N,k),ncol=k,nrow=N) x<-apply(x,2,sample) x<-(x-0.5)/N return(x) } starts<-LHD(n_candidate,n_par) #require(lhs) #starts<-maximinLHS(n_candidate,n_par) range_S<-matrix(rep(upper-lower,n_candidate),ncol=n_par,byrow=TRUE) low_S<-matrix(rep(lower,n_candidate),ncol=n_par,byrow=TRUE) starts<-starts*range_S+low_S cand_obj<-apply(starts,1,var.MLE.DK) index<- (rank(cand_obj,ties.method="min")<=num_starts) Starts<-starts[index,] Fop<-function(x) optim(x,var.MLE.DK,lower=lower,upper=upper,method="L-BFGS-B")$val op_obj<-apply(Starts,1,Fop) beststart<-Starts[which.min(op_obj),] op<-optim(beststart,var.MLE.DK,lower=lower,upper=upper,method="L-BFGS-B") objval<-op$val lambda<-op$par[1] Stand_theta<-op$par[2:(p+1)] kappa<-op$par[p+2] Stand_alpha<-kappa+Stand_theta bw<-op$par[p+3] #Adjust the scales of theta and alpha for unstandaridized designs DD. theta<-Stand_theta/scales^2 alpha<-Stand_alpha/scales^2 ###########Leave-one-out Cross Validation Start########################### Yjfp<-rep(0,n) for(jf in 1:n){ G<-PSI(theta)[-jf,-jf] L<-PSI(alpha)[-jf,-jf] Gbw<-PSI(theta*bw)[-jf,-jf] Sig<-diag(n-1) for(rep in 1:4){ Q<-G+lambda*Sig^(1/2)%*%L%*%Sig^(1/2) invQ <- solve(Q) beta <- (onem %*% invQ %*% yobs[-jf])/(onem %*% invQ %*% onem) temp<-invQ%*%(yobs[-jf]-beta*onem) gip<-beta*onem+G%*%temp e<-yobs[-jf]-gip Sig<-diag(c(Gbw%*%e^2/(Gbw%*%onem))) Sig2<-mean(diag(Sig)) Sig<-Sig/Sig2 #print(diag(Sig)) } Q<-G+lambda*Sig^(1/2)%*%L%*%Sig^(1/2) invQ <- solve(Q) beta <- (onem %*% invQ %*% yobs[-jf])/(onem %*% invQ %*% onem) tau2<- t(yobs[-jf]-beta*onem)%*%invQ%*%(yobs[-jf]-beta*onem)/(n-1) temp<-invQ%*%(yobs[-jf]-beta*onem) g<-PSI(theta)[jf,-jf] l<-PSI(alpha)[jf,-jf] gbw<-PSI(theta*bw)[jf,-jf] vjf<-(t(gbw)%*%(e^2)/(t(gbw)%*%onem))/Sig2 vjf<-as.vector(vjf) q<-g+lambda*sqrt(vjf)*Sig^(1/2)%*%l Yjfp[jf]<-beta+t(q)%*%temp } rmscv<- sqrt(sum((yobs-Yjfp)^2)/n) ###############Leave-one-out Cross Validation End################## G<-PSI(theta) L<-PSI(alpha) Gbw<-PSI(theta*bw) # Obtain the local volatility matrix "Sig" Sig<-diag(n) for(rep in 1:4){ Q<-G+lambda*Sig^(1/2)%*%L%*%Sig^(1/2) invQ <- solve(Q) beta <- (one %*% invQ %*% yobs)/(one %*% invQ %*% one) temp<-invQ%*%(yobs-beta*one) gip<-beta*one+G%*%temp e<-yobs-gip res2<-e^2 Sig<-diag(c(Gbw%*%res2/(Gbw%*%one))) sf<-mean(diag(Sig)) Sig<-Sig/sf #print(diag(Sig)) } Q<-G+lambda*Sig^(1/2)%*%L%*%Sig^(1/2) invQ <- solve(Q) beta <- (one %*% invQ %*% yobs)/(one %*% invQ %*% one) tau2<- t(yobs-beta*one)%*%invQ%*%(yobs-beta*one)/n temp<-invQ%*%(yobs-beta*one) theta<-matrix(theta,nrow=1) alpha<-matrix(alpha,nrow=1) if(!is.null(var_names)){ colnames(theta)=var_names colnames(alpha)=var_names } est<-list(X=DD,yobs=yobs,var_names=var_names,lambda=lambda,theta=theta,alpha=alpha,bandwidth=bw,Sig_matrix=Sig,sf=sf,res2=res2,temp_matrix=temp,invQ=invQ,mu=beta,tau2=tau2,beststart=beststart,objval=objval,rmscv=rmscv,Yp_jackknife=Yjfp) est$call<-match.call() class(est)<-"CGP" return(est) }
/scratch/gouwar.j/cran-all/cranData/CGP/R/CGP.R
plotCGP <- function(object){ plot_lim=c(min(object$Yp_jackknife,object$yobs)-0.01*(max(object$yobs)-min(object$yobs)),max(object$Yp_jackknife,object$yobs)+0.01*(max(object$yobs)-min(object$yobs))) plot(object$Yp_jackknife,object$yobs,type="p",pch=20,cex=0.8,xlim=plot_lim,ylim=plot_lim,xlab="Y Jackknife Predicted",ylab="Y Observed",main="Actually by Predicted Plot") }
/scratch/gouwar.j/cran-all/cranData/CGP/R/plotCGP.R
predict.CGP <- function(object,newdata=NULL,PI=FALSE,...){ UU<-newdata DD<-object$X yobs<-object$yobs n<-nrow(DD) p<-ncol(DD) one<-rep(1,n) lambda<-object$lambda theta<-as.vector(object$theta) alpha<-as.vector(object$alpha) bw<-object$bandwidth Sig<-object$Sig_matrix sf<-object$sf res2<-object$res2 temp<-object$temp_matrix invQ<-object$invQ tau2<-object$tau2 beta<-object$mu if(is.null(UU)){ Yp<-NULL gp<-NULL lp<-NULL v<-NULL Y_low<-NULL Y_up<-NULL } if(!is.null(UU)){ UU<-as.matrix(UU) N<-nrow(UU) if(ncol(UU)!=p) print("Predictive location input UU is of wrong dimension!") ppp<-rep(0,N) g<-rep(0,n) gbw<-rep(0,n) l<-rep(0,n) Yp<-rep(0,N) gp<-rep(0,N) lp<-rep(0,N) v<-rep(0,N) for (k in 1:N){ for (r in 1:n){ g[r]<-exp(-(DD[r,]-UU[k,])^2%*%(theta)) gbw[r]<-exp(-(DD[r,]-UU[k,])^2%*%(theta*bw)) l[r]<-exp(-(DD[r,]-UU[k,])^2%*%(alpha)) } v[k]<-(t(gbw)%*%(res2)/(t(gbw)%*%one))/sf q<-g+lambda*sqrt(v[k])*Sig^(1/2)%*%l Yp[k]<-beta+t(q)%*%temp gp[k]<-beta+t(g)%*%temp if(PI){ lp[k]<-lambda*sqrt(v[k])*t(l)%*%Sig^(1/2)%*%temp ppp[k]<-1+lambda*v[k]-t(q)%*%invQ%*%q+(1-t(q)%*%invQ%*%one)^2/(one%*%invQ%*%one) } } if(PI){ ppp[ppp<0]<-0 ka<-1.96 Y_up<-Yp+ka*sqrt(tau2*ppp) Y_low<-Yp-ka*sqrt(tau2*ppp) } if(!PI){ Y_low<-NULL Y_up<-NULL } } val<-list(Yp=Yp,gp=gp,lp=lp,v=v,Y_low=Y_low,Y_up=Y_up) return(val) }
/scratch/gouwar.j/cran-all/cranData/CGP/R/predict.CGP.R
print.CGP <- function(x,...){ cat("Call:\n") print(x$call) cat("\n Lambda:\n") print(x$lambda) cat("\n Theta:\n") print(x$theta) cat("\n Alpha:\n") print(x$alpha) cat("\n Bandwidth:\n") print(x$bandwidth) }
/scratch/gouwar.j/cran-all/cranData/CGP/R/print.CGP.R
summary.CGP <- function(object,...){ val<-list(call=object$call, Lambda=object$lambda, Theta=object$theta, Alpha=object$alpha, Bandwidth=object$bandwidth, rmscv=object$rmscv, mu=object$mu, tau2=object$tau2, best.start=object$beststart, objval=object$objval) class(val)<-"summary.CGP" return(val) }
/scratch/gouwar.j/cran-all/cranData/CGP/R/summary.CGP.R
#' CGPfunctions: A package of miscellaneous functions for teaching statistics. #' #' A package that includes miscellaneous functions useful for teaching statistics as well as actually practicing the art. They typically are not new methods but rather wrappers around either base R or other packages. #' #' @section Functions included: #' \itemize{ #' \item \code{\link{newggslopegraph}} creates a "slopegraph" as conceptualized by Edward Tufte. #' \item \code{\link{Plot2WayANOVA}} which as the name implies conducts a 2 way ANOVA and plots the results using `ggplot2` #' \item \code{\link{PlotXTabs2}} which wraps around ggplot2 to provide Bivariate bar charts for categorical and ordinal data. #' \item \code{\link{chaid_table}} provides tabular summary of CHAID partykit object. #' \item \code{\link{cross2_var_vectors}} helper function to cross a vector of variables. #' \item \code{\link{PlotXTabs}} Plots cross tabulated variables using `ggplot2` #' \item \code{\link{Mode}} which finds the modal value in a vector of data #' \item \code{\link{SeeDist}} which wraps around ggplot2 to provide visualizations of univariate data. #' \item \code{\link{OurConf}} which wraps around ggplot2 to provide visualizations of sampling confidence intervals. #' } #' #' @docType package #' @name CGPfunctions NULL
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/CGPfunctions.R
#' Derive the modal value(s) for a set of data #' #' This function takes a vector and returns one or mode values #' that represent the mode point of the data #' #' @param x a vector #' #' @return a vector containing one or more modal values for the input vector #' @export #' #' @section Warning: #' Be careful the function does some basic error checking but the return to #' \code{Mode(NA)} is \code{NA} and a vector where the majority of entries #' are \code{NA} is also NA #' #' @examples #' Mode(sample(1:100, 1000, replace = TRUE)) #' Mode(mtcars$hp) #' Mode(iris$Sepal.Length) Mode <- function(x) { # error checking if (missing(x)) { stop("Argument \"x\" is missing, with no default") } if (!is.vector(x)) { stop("I can only process a vector of data") } ux <- unique(x) # ux[which.max(tabulate(match(x, ux)))] tab <- tabulate(match(x, ux)) ux[tab == max(tab)] }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/Mode.R
# stable # modified from https://www.rdocumentation.org/packages/BSDA/versions/1.2.0/topics/CIsim #' Plotting random samples of confidence intervals around the mean #' #' This function takes some parameters and simulates random samples and #' their confidence intervals #' #' @param samples The number of times to draw random samples #' @param n The sample size we draw each time #' @param mu The population mean mu #' @param sigma The population standard deviation #' @param conf.level What confidence level to compute 1 - alpha (significance level) #' #' @return A ggplot2 object #' @export #' @importFrom stats qnorm rnorm #' @seealso \code{stats::qnorm}, \code{stats::rnorm}, \code{BSDA::CIsim} #' #' @author Chuck Powell #' #' @examples #' OurConf(samples = 100, n = 30, mu = 0, sigma = 1, conf.level = 0.95) #' OurConf(samples = 2, n = 5) #' OurConf(samples = 25, n = 25, mu = 100, sigma = 20, conf.level = 0.99) OurConf <- function(samples = 100, n = 30, mu = 0, sigma = 1, conf.level = 0.95) { alpha <- 1 - conf.level CL <- conf.level * 100 n <- round(n) N <- round(samples) if (N <= 0 || n <= 1) { stop("Number of random samples and sample size must both be at least 2") } if (!missing(conf.level) && (length(conf.level) != 1 || !is.finite(conf.level) || conf.level <= 0 || conf.level >= 1)) { stop("'conf.level' must be a single number between 0 and 1") } if (sigma <= 0) { stop("Variance must be a positive value") } junk <- rnorm(N * n, mu, sigma) jmat <- matrix(junk, N, n) xbar <- apply(jmat, 1, mean) ll <- xbar - qnorm(1 - alpha / 2) * sigma / sqrt(n) ul <- xbar + qnorm(1 - alpha / 2) * sigma / sqrt(n) notin <- sum((ll > mu) + (ul < mu)) percentage <- round((1 - notin / N) * 100, 2) data <- data.frame(xbar = xbar, ll = ll, ul = ul) data$samplenumb <- factor(as.integer(rownames(data))) data$correct <- "Includes" data$correct[data$ul < mu] <- "Low" data$correct[data$ll > mu] <- "High" bestfit <- function(NN = N) { list( scale_y_continuous(limits = c((mu - 2 * sigma), (mu + 2 * sigma))), if (NN >= 51) { scale_x_discrete(breaks = seq(0, 500, 10)) } ) } p <- ggplot(data, aes(y = xbar, x = samplenumb)) + geom_point() + geom_hline(yintercept = mu) + geom_errorbar(aes(ymin = ll, ymax = ul, color = correct), width = 0.3) + labs( title = bquote(.(N) ~ "random samples with" ~ .(CL) * "% confidence intervals where" ~ mu ~ "=" ~ .(mu) ~ "and" ~ sigma ~ "=" ~ .(sigma)), subtitle = bquote("Note:" ~ .(percentage) * "% of the confidence intervals contain" ~ mu ~ "=" ~ .(mu)), y = expression("Sample mean" ~ (bar(X))), x = paste0("Random samples of size = ", n), caption = ("modified from the CIsim function in package BSDA") ) + bestfit() + guides(color = guide_legend(title = NULL)) + theme_bw() print(p) cat(percentage, "% of the confidence intervals contain Mu =", mu, ".", "\n") }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/OurConfidence.R
#' Plot a 2 Way ANOVA using dplyr and ggplot2 #' #' Takes a formula and a dataframe as input, conducts an analysis of variance #' prints the results (AOV summary table, table of overall model information #' and table of means) then uses ggplot2 to plot an interaction graph (line #' or bar) . Also uses Brown-Forsythe test for homogeneity of #' variance. Users can also choose to save the plot out as a png file. #' #' Details about how the function works in order of steps taken. #' \enumerate{ #' \item Some basic error checking to ensure a valid formula and dataframe. #' Only accepts fully *crossed* formula to check for interaction term #' \item Ensure the dependent (outcome) variable is numeric and that the two #' independent (predictor) variables are or can be coerced to factors -- user #' warned on the console #' \item Remove missing cases -- user warned on the console #' \item Calculate a summarized table of means, sds, standard errors of the #' means, confidence intervals, and group sizes. #' \item Use \code{\link[stats]{aov}} function to execute an Analysis of #' Variance (ANOVA) #' \item Use \code{sjstats::anova_stats} to calculate eta squared #' and omega squared values per factor. If the design is unbalanced warn #' the user and use Type II sums of squares #' \item Produce a standard ANOVA table with additional columns #' \item Use the \code{\link[DescTools]{PostHocTest}} for producing a table #' of post hoc comparisons for all effects that were significant #' \item Testing Homogeneity #' of Variance assumption with Brown-Forsythe test #' \item Use the \code{\link[DescTools]{PostHocTest}} for conducting #' post hoc tests for effects that were significant #' \item Use the \code{\link[stats]{shapiro.test}} for testing normality #' assumption with Shapiro-Wilk #' \item Use \code{ggplot2} to plot an interaction plot of the type the #' user specified.} #' The defaults are deliberately constructed to emphasize the nature #' of the interaction rather than focusing on distributions. So #' while a violin plot of the first factor by level is displayed #' along with dots for individual data points shaded by the second #' factor, the emphasis is on the interaction lines. #' #' @usage Plot2WayANOVA(formula, #' dataframe = NULL, #' confidence=.95, #' plottype = "line", #' errorbar.display = "CI", #' xlab = NULL, #' ylab = NULL, #' title = NULL, #' subtitle = NULL, #' interact.line.size = 2, #' ci.line.size = 1, #' mean.label = FALSE, #' mean.ci = TRUE, #' mean.size = 4, #' mean.shape = 23, #' mean.color = "darkred", #' mean.label.size = 3, #' mean.label.color = "black", #' offset.style = "none", #' overlay.type = NULL, #' posthoc.method = "scheffe", #' show.dots = FALSE, #' PlotSave = FALSE, #' ggtheme = ggplot2::theme_bw(), #' package = "RColorBrewer", #' palette = "Dark2", #' ggplot.component = NULL) #' @param formula a formula with a numeric dependent (outcome) variable, #' and two independent (predictor) variables e.g. \code{mpg ~ am * vs}. #' The independent variables are coerced to factors (with warning) if #' possible. #' @param dataframe a dataframe or an object that can be coerced to a dataframe #' @param confidence what confidence level for confidence intervals #' @param plottype bar or line (quoted) #' @param errorbar.display default "CI" (confidence interval), which type of #' errorbar should be displayed around the mean point? Other options #' include "SEM" (standard error of the mean) and "SD" (standard dev). #' "none" removes it entirely much like \code{\link[stats]{interaction.plot}} #' @param PlotSave a logical indicating whether the user wants to save the plot #' as a png file #' @param xlab,ylab Labels for `x` and `y` axis variables. If `NULL` (default), #' variable names for `x` and `y` will be used. #' @param title The text for the plot title. A generic default is provided. #' @param subtitle The text for the plot subtitle. If `NULL` (default), key #' model information is provided as a subtitle. #' @param interact.line.size Line size for the line connecting the group means #' (Default: `2`). #' @param ci.line.size Line size for the confidence interval bracketing #' the group means (Default: `1`). #' @param mean.label Logical that decides whether the value of the group #' mean is to be displayed (Default: `FALSE`). #' @param mean.ci Logical that decides whether the confidence interval for #' group means is to be displayed (Default: `TRUE`). #' @param mean.color Color for the data point corresponding to mean (Default: #' `"darkred"`). #' @param mean.label.size,mean.label.color Aesthetics for #' the label displaying mean. Defaults: `3`, `"black"`, respectively. #' @param mean.size Point size for the data point corresponding to mean #' (Default: `4`). #' @param mean.shape Shape of the plot symbol for the mean #' (Default: `23` which is a diamond). #' @param offset.style A character string (e.g., `"wide"` or `"narrow"`, #' or `"none"`) which controls whether items are offset from the #' centerline for clarity. Useful when you want to add individual #' datapoints or confdence interval lines overlap. (Default: `"none"`). #' @param overlay.type A character string (e.g., `"box"` or `"violin"`), #' if you wish to overlay that information on factor1 #' @param posthoc.method A character string, one of "hsd", "bonf", "lsd", #' "scheffe", "newmankeuls", defining the method for the pairwise comparisons. #' (Default: `"scheffe"`). #' @param show.dots Logical that decides whether the individual data points #' are displayed (Default: `FALSE`). #' @param package Name of package from which the palette is desired as string #' or symbol. #' @param palette Name of palette as string or symbol. #' @param ggtheme A function, ggplot2 theme name. Default value is ggplot2::theme_bw(). #' Any of the ggplot2 themes, or themes from extension packages are allowed (e.g., #' hrbrthemes::theme_ipsum(), etc.). #' @param ggplot.component A ggplot component to be added to the plot prepared. #' The default is NULL. The argument should be entered as a function. #' for example to change the size and color of the x axis text you use: #' `ggplot.component = theme(axis.text.x = element_text(size=13, color="darkred"))` #' depending on what theme is in use the ggplot component might not work as expected. #' @return A list with 5 elements which is returned invisibly. These items #' are always sent to the console for display but for user convenience #' the function also returns a named list with the following items #' in case the user desires to save them or further process them - #' \code{$ANOVATable}, \code{$ModelSummary}, \code{$MeansTable}, #' \code{$PosthocTable}, \code{$BFTest}, and \code{$SWTest}. #' The plot is always sent to the default plot device #' #' @references: ANOVA: Delacre, Leys, Mora, & Lakens, *PsyArXiv*, 2018 #' #' @author Chuck Powell #' @seealso \code{\link[stats]{aov}}, \code{\link{BrownForsytheTest}}, #' \code{sjstats::anova_stats}, \code{\link[stats]{replications}}, #' \code{\link[stats]{shapiro.test}}, \code{\link[stats]{interaction.plot}} #' @examples #' #' Plot2WayANOVA(mpg ~ am * cyl, mtcars, plottype = "line") #' Plot2WayANOVA(mpg ~ am * cyl, #' mtcars, #' plottype = "line", #' overlay.type = "box", #' mean.label = TRUE #' ) #' #' library(ggplot2) #' Plot2WayANOVA(mpg ~ am * vs, #' mtcars, #' confidence = .99, #' ggplot.component = theme(axis.text.x = element_text(size=13, color="darkred"))) #' #' @import ggplot2 #' @import rlang #' @importFrom methods is #' @importFrom stats anova aov lm pf qt replications sd symnum residuals shapiro.test AIC BIC #' @importFrom dplyr as_tibble case_when group_by summarise %>% n select filter #' @importFrom sjstats anova_stats #' @importFrom DescTools PostHocTest #' @importFrom BayesFactor anovaBF #' @importFrom tidyr complete #' @export #' Plot2WayANOVA <- function(formula, dataframe = NULL, confidence = .95, plottype = "line", errorbar.display = "CI", xlab = NULL, ylab = NULL, title = NULL, subtitle = NULL, interact.line.size = 2, ci.line.size = 1, mean.label = FALSE, mean.ci = TRUE, mean.size = 4, mean.shape = 23, mean.color = "darkred", mean.label.size = 3, mean.label.color = "black", offset.style = "none", overlay.type = NULL, posthoc.method = "scheffe", show.dots = FALSE, PlotSave = FALSE, ggtheme = ggplot2::theme_bw(), package = "RColorBrewer", palette = "Dark2", ggplot.component = NULL) { # -------- error checking ---------------- # set default theme ggplot2::theme_set(ggtheme) if (length(match.call()) - 1 <= 1) { stop("Not enough arguments passed... requires at least a formula with a DV and 2 IV plus a dataframe") } if (missing(formula)) { stop("\"formula\" argument is missing, with no default") } if (!is(formula, "formula")) { stop("\"formula\" argument must be a formula") } if (length(formula) != 3) { stop("invalid value for \"formula\" argument") } vars <- all.vars(formula) chkinter <- all.names(formula) if (length(vars) != 3) { stop("invalid value for \"formula\" argument") } if ("+" %in% chkinter) { stop("Sorry you need to use an asterisk not a plus sign in the formula so the interaction can be plotted") } if ("~" == chkinter[2]) { stop("Sorry you can only have one dependent variable so only one tilde is allowed ~ you have two or more") } # we can trust the basics grab the variable names from formula # these are now of ***class character*** depvar <- vars[1] iv1 <- vars[2] iv2 <- vars[3] # create a filename in case they want to save png potentialfname <- paste0(depvar, "by", iv1, "and", iv2, ".png") if (missing(dataframe)) { stop("You didn't specify a data frame to use") } if (!exists(deparse(substitute(dataframe)))) { stop("That dataframe does not exist\n") } if (!is(dataframe, "data.frame")) { stop("The dataframe name you specified is not valid\n") } if (!(depvar %in% names(dataframe))) { stop(paste0( "'", depvar, "' is not the name of a variable in '", deparse(substitute(dataframe)), "'" )) } if (!(iv1 %in% names(dataframe))) { stop(paste0( "'", iv1, "' is not the name of a variable in '", deparse(substitute(dataframe)), "'" )) } if (!(iv2 %in% names(dataframe))) { stop(paste0( "'", iv2, "' is not the name of a variable in '", deparse(substitute(dataframe)), "'" )) } # force it to a data frame dataframe <- dataframe[, c(depvar, iv1, iv2)] # -------- x & y axis labels ---------------------------- # if `xlab` is not provided, use the variable `x` name if (is.null(xlab)) { xlab <- iv1 } # if `ylab` is not provided, use the variable `y` name if (is.null(ylab)) { ylab <- depvar } # -------- check variable types ---------------- dataframe <- as.data.frame(dataframe) if (!is(dataframe[, depvar], "numeric")) { stop("dependent variable must be numeric") } if (!is(dataframe[, iv1], "factor")) { message(paste0("\nConverting ", iv1, " to a factor --- check your results")) dataframe[, iv1] <- as.factor(dataframe[, iv1]) } if (!is(dataframe[, iv2], "factor")) { message(paste0("\nConverting ", iv2, " to a factor --- check your results")) dataframe[, iv2] <- as.factor(dataframe[, iv2]) } # grab the names of the factor levels factor1.names <- levels(dataframe[, iv1]) factor2.names <- levels(dataframe[, iv2]) if (!is(confidence, "numeric") | length(confidence) != 1 | confidence < .5 | confidence > .9991) { stop("\"confidence\" must be a number between .5 and 1") } if (plottype != "bar") { plottype <- "line" } # -------- Remove missing cases notify user ---------------- missing <- apply(is.na(dataframe), 1, any) if (any(missing)) { warning(paste(sum(missing)), " case(s) removed because of missing data") } dataframe <- dataframe[!missing, ] # -------- Check cell counts ---------------- checkcells <- dataframe %>% group_by(!!sym(iv1), !!sym(iv2)) %>% summarize(count = n()) %>% ungroup() %>% complete(!!sym(iv1), !!sym(iv2), fill = list(count = 0)) if (any(checkcells$count == 0)) { print(checkcells) stop(paste0( "\n--- MAJOR Problem! ---\n", "You have one or more cells with ZERO observations.\n" )) } else if (any(checkcells$count <= 2)){ message(paste0( "\n\t\t\t\t--- WARNING! ---\n", "\t\tYou have one or more cells with less than 3 observations.\n" )) print(checkcells) } # -------- Build summary dataframe ---------------- newdata <- dataframe %>% group_by(!!sym(iv1), !!sym(iv2)) %>% summarise( TheMean = mean(!!sym(depvar), na.rm = TRUE), TheSD = sd(!!sym(depvar), na.rm = TRUE), TheSEM = sd(!!sym(depvar), na.rm = TRUE) / sqrt(n()), CIMuliplier = qt(confidence / 2 + .5, n() - 1), LowerBoundCI = TheMean - TheSEM * CIMuliplier, UpperBoundCI = TheMean + TheSEM * CIMuliplier, LowerBoundSEM = TheMean - TheSEM, UpperBoundSEM = TheMean + TheSEM, LowerBoundSD = TheMean - TheSD, UpperBoundSD = TheMean + TheSD, N = n() ) %>% mutate( LowerBound = case_when( errorbar.display == "SD" ~ LowerBoundSD, errorbar.display == "SEM" ~ LowerBoundSEM, errorbar.display == "CI" ~ LowerBoundCI, TRUE ~ LowerBoundCI), UpperBound = case_when( errorbar.display == "SD" ~ UpperBoundSD, errorbar.display == "SEM" ~ UpperBoundSEM, errorbar.display == "CI" ~ UpperBoundCI, TRUE ~ UpperBoundCI) ) # -------- Run tests and procedures ---------------- # run analysis of variance MyAOV <- aov(formula, dataframe) # force to Type 2 sums of squares MyAOVt2 <- aovtype2(MyAOV) # get more detailed information including effect sizes WithETA <- sjstats::anova_stats(MyAOVt2) # Run Brown-Forsythe BFTest <- BrownForsytheTest(formula, dataframe) # Grab the residuals and run Shapiro-Wilk MyAOV_residuals <- residuals(object = MyAOV) if (nrow(dataframe) < 5000){ SWTest <- shapiro.test(x = MyAOV_residuals) # run Shapiro-Wilk test } else { SWTest <- NULL } # Grab the effects that were significant in omnibuds test sigfactors <- filter(WithETA, p.value <= 1 - confidence) %>% select(term) if (nrow(sigfactors) > 0) { posthocresults <- PostHocTest(MyAOV, method = posthoc.method, conf.level = confidence, which = as.character(sigfactors[, 1]) ) } else { posthocresults <- "No signfiicant effects" } bf_models <- BayesFactor::anovaBF(formula = formula, data = dataframe, progress = FALSE) bf_models <- as_tibble(bf_models, rownames = "model") %>% select(model:error) %>% arrange(desc(bf)) %>% mutate(support = bf_display(bf = bf, display_type = "support")) %>% mutate(margin_of_error = error) %>% select(-error) # return(bf_models) # -------- save the common plot items as a list to be used --------- # Make a default title cipercent <- round(confidence * 100, 2) # if `title` is not provided, use this generic if (is.null(title)) { title <- paste("Interaction plot ", deparse(formula, width.cutoff = 80), collapse="") if (errorbar.display == "CI") { title <- bquote(.(title) * " with" ~ .(cipercent) * "% conf ints") } else if (errorbar.display == "SEM") { title <- bquote(.(title) * " with standard error of the mean") } else if (errorbar.display == "SD") { title <- bquote(.(title) * " with standard deviations") } else { title <- title } } # make pretty labels AICnumber <- round(stats::AIC(MyAOV), 1) BICnumber <- round(stats::BIC(MyAOV), 1) eta2iv1 <- WithETA[1, 7] eta2iv2 <- WithETA[2, 7] eta2interaction <- WithETA[3, 7] # if `subtitle` is not provided, use this generic if (is.null(subtitle)) { subtitle <- bquote( eta^2 * " (" * .(iv1) * ") =" ~ .(eta2iv1) * ", " * eta^2 * " (" * .(iv2) * ") =" ~ .(eta2iv2) * ", " * eta^2 * " (interaction) =" ~ .(eta2interaction) * ", AIC =" ~ .(AICnumber) * ", BIC =" ~ .(BICnumber) # "AIC =" ~ .(AICnumber) * ", BIC =" ~ .(BICnumber) ) } # decide how much to offset things if (offset.style == "wide") { dot.dodge <- .4 ci.dodge <- .15 mean.dodge <- .15 } if (offset.style == "narrow") { dot.dodge <- .1 ci.dodge <- .05 mean.dodge <- .05 } if (offset.style != "narrow" && offset.style != "wide") { dot.dodge <- 0 ci.dodge <- 0 mean.dodge <- 0 } commonstuff <- list( xlab(xlab), ylab(ylab), scale_colour_hue(l = 40), ggtitle(title, subtitle = subtitle), theme(panel.grid.major.x = element_blank()) ) # -------- start the plot --------- p <- newdata %>% ggplot(aes_string( x = iv1, y = "TheMean", colour = iv2, fill = iv2, group = iv2 )) + commonstuff # -------- display individual dots --------- if (plottype == "line" && show.dots == TRUE) { p <- p + geom_point( data = dataframe, mapping = aes( x = !!sym(iv1), y = !!sym(depvar), shape = !!sym(iv2) ), alpha = .4, position = position_dodge(dot.dodge), show.legend = TRUE ) } # -------- switch for bar versus line plot --------- if (errorbar.display != "none") { switch(plottype, bar = p <- p + geom_bar( stat = "identity", position = "dodge" ) + geom_errorbar(aes(ymin = LowerBound, ymax = UpperBound), width = .5, size = ci.line.size, position = position_dodge(0.9), show.legend = FALSE ), line = p <- p + geom_errorbar(aes( ymin = LowerBound, ymax = UpperBound ), width = .2, size = ci.line.size, position = position_dodge(ci.dodge) ) + geom_line( aes_string(linetype = iv2), size = interact.line.size, position = position_dodge(mean.dodge) ) + geom_point(aes(y = TheMean), shape = mean.shape, size = mean.size, color = mean.color, alpha = 1, position = position_dodge(mean.dodge) ) ) } else { switch(plottype, bar = p <- p + geom_bar( stat = "identity", position = "dodge" ), line = p <- p + geom_line( aes_string(linetype = iv2), size = interact.line.size, position = position_dodge(mean.dodge) ) + geom_point(aes(y = TheMean), shape = mean.shape, size = mean.size, color = mean.color, alpha = 1, position = position_dodge(mean.dodge) ) ) } # -------- Add box or violin if needed --------- if (!is.null(overlay.type)) { if (plottype == "line" && overlay.type == "box") { p <- p + geom_boxplot( data = dataframe, mapping = aes( x = !!sym(iv1), y = !!sym(depvar), group = !!sym(iv1) ), color = "gray", width = 0.4, alpha = 0.2, fill = "white", outlier.shape = NA, show.legend = FALSE ) } else if (plottype == "line" && overlay.type == "violin") { p <- p + geom_violin( data = dataframe, mapping = aes( x = !!sym(iv1), y = !!sym(depvar), group = !!sym(iv1) ), color = "gray", width = 0.7, alpha = 0.2, fill = "white", show.legend = FALSE ) } } # -------- Add mean labels if needed --------- if (isTRUE(mean.label && plottype == "line")) { p <- p + ggrepel::geom_label_repel( data = newdata, mapping = aes( x = !!sym(iv1), y = TheMean, label = as.character(round(TheMean, 2)) ), size = mean.label.size, color = mean.label.color, fontface = "bold", alpha = .8, direction = "both", nudge_x = -.2, max.iter = 3e2, box.padding = 0.35, point.padding = 0.5, segment.color = "black", force = 2, inherit.aes = FALSE, seed = 123 ) } if (isTRUE(mean.label && plottype == "bar")) { p <- p + ggrepel::geom_label_repel( data = newdata, mapping = aes( x = !!sym(iv1), y = TheMean, label = as.character(round(TheMean, 2)) ), size = mean.label.size, color = mean.label.color, fontface = "bold", alpha = .8, direction = "both", max.iter = 3e2, box.padding = 0.35, point.padding = 0.5, segment.color = "black", force = 2, position = position_dodge(0.9), inherit.aes = TRUE, show.legend = FALSE, seed = 123 ) } # -------- Warn user of unbalanced design ---------------- if (!all(checkcells$count == checkcells$count[1])) { rsquaredx <- round(1 - (MyAOVt2$`Sum Sq`[4] / sum(MyAOVt2$`Sum Sq`[1:4])), 3) message(paste0( "\n\t\t\t\t--- WARNING! ---\n", "\t\tYou have an unbalanced design. Using Type II sum of squares, to calculate factor effect sizes eta and omega. Your two factors account for ", rsquaredx, " of the type II sum of squares.\n" )) } else { message("\nYou have a balanced design. \n") } # return(checkcells) print(WithETA) # -------- Print tests and tables ---------------- # message("\nMeasures of overall model fit\n") # print(model_summary) message("\nTable of group means\n") print(newdata) message("\nPost hoc tests for all effects that were significant\n") print(posthocresults) message("\nTesting Homogeneity of Variance with Brown-Forsythe \n") if (BFTest$`Pr(>F)`[[1]] <= .05) { message(" *** Possible violation of the assumption ***") } print(BFTest) if(!is.null(SWTest)) { message("\nTesting Normality Assumption with Shapiro-Wilk \n") if (SWTest$p.value <= .05) { message(" *** Possible violation of the assumption. You may want to plot the residuals to see how they vary from normal ***") } print(SWTest) } message("\nBayesian analysis of models in order\n") print(bf_models) # -------- adding optional ggplot.component ---------- p <- p + ggplot.component # -------- Print the plot itself ---------------- message("\nInteraction graph plotted...") print(p) # -------- Return stuff to user ---------------- whattoreturn <- list( ANOVATable = WithETA, # ModelSummary = model_summary, MeansTable = newdata, PosthocTable = posthocresults, BFTest = BFTest, SWTest = SWTest, Bayesian_models = bf_models ) if (PlotSave) { ggsave(potentialfname, device = "png") whattoreturn[["plotfile"]] <- potentialfname } return(invisible(whattoreturn)) }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/Plot2WayANOVA.R
#' Plot a Cross Tabulation of two variables using dplyr and ggplot2 #' #' Takes a dataframe and at least two variables as input, conducts a #' crosstabulation of the variables using dplyr. Removes NAs and then #' plots the results as one of three types of bar (column) graphs #' using ggplot2. The function accepts either bare variable names or #' column numbers as input (see examples for the possibilities) #' #' @usage PlotXTabs(dataframe, xwhich, ywhich, plottype = "side") #' @param dataframe an object that is of class dataframe #' @param xwhich either a bare variable name that is valid in the #' dataframe or one or more column numbers. An attempt will be #' made to coerce the variable to a factor but odd plots will occur #' if you pass it a variable that is by rights continuous in nature. #' @param ywhich either a bare variable name that is valid in the #' dataframe or one or more column numbers that exist in the dataframe. #' An attempt will be #' made to coerce the variable to a factor but odd plots will occur #' if you pass it a variable that is by rights continuous in nature. #' @param plottype one of three options "side", "stack" or "percent" #' #' @return One or more ggplots to the default graphics device as well as #' advisory information in the console #' @export #' @import ggplot2 scales #' @importFrom dplyr group_by summarise %>% count filter mutate #' #' @author Chuck Powell #' @seealso \code{\link[janitor]{janitor}} #' #' @examples #' PlotXTabs(mtcars, am, vs) #' PlotXTabs(mtcars, am, vs, "stack") #' PlotXTabs(mtcars, am, vs, "percent") #' PlotXTabs(mtcars, am, 8, "side") #' PlotXTabs(mtcars, 8, am, "stack") #' PlotXTabs(mtcars, am, c(8, 10), "percent") #' PlotXTabs(mtcars, c(10, 8), am) #' PlotXTabs(mtcars, c(2, 9), c(10, 8), "mispelled") #' \dontrun{ #' PlotXTabs(happy, happy, sex) # baseline #' PlotXTabs(happy, 2, 5, "stack") # same thing using column numbers #' PlotXTabs(happy, 2, c(5:9), plottype = "percent") # multiple columns RHS #' PlotXTabs(happy, c(2, 5), 9, plottype = "side") # multiple columns LHS #' PlotXTabs(happy, c(2, 5), c(6:9), plottype = "percent") #' PlotXTabs(happy, happy, c(6, 7, 9), plottype = "percent") #' PlotXTabs(happy, c(6, 7, 9), happy, plottype = "percent") #' } #' PlotXTabs <- function(dataframe, xwhich, ywhich, plottype = "side") { theme_set(theme_bw()) if (length(match.call()) <= 3) { stop("Not enough arguments passed... requires a dataframe, plus at least two variables") } argList <- as.list(match.call()[-1]) if (!exists(deparse(substitute(dataframe)))) { stop("The first object in your list does not exist. It should be a dataframe") } if (!is(dataframe, "data.frame")) { stop("The first name you passed does not appear to be a data frame") } # process plottype logic -- default is side anything mispelled or not listed is also side switch(plottype, side = list( geom_bar(position = "dodge", stat = "identity"), ylab("Count") ) -> whichbar, stack = list( geom_bar(stat = "identity"), ylab("Count") ) -> whichbar, percent = list( geom_bar(stat = "identity", position = "fill"), ylab("Percent"), scale_y_continuous(labels = scales::percent, breaks = seq(0, 1, by = 0.10)) ) -> whichbar, list( geom_bar(position = "dodge", stat = "identity"), ylab("Count") ) -> whichbar ) PlotMagic <- function(dataframe, aaa, bbb, whichbar, dfname, xname, yname) { dataframe %>% filter(!is.na(!!aaa), !is.na(!!bbb)) %>% mutate(!!quo_name(aaa) := factor(!!aaa), !!quo_name(bbb) := factor(!!bbb)) %>% group_by(!!aaa, !!bbb) %>% count() -> tempdf originalcount <- nrow(dataframe) newcount <- sum(tempdf$n) missingcount <- originalcount - newcount tempdf %>% ggplot(aes_(fill = aaa, y = ~n, x = bbb)) + whichbar + ggtitle(sprintf("Crosstab of %s N = %i after removing %i missing cases", dfname, newcount, missingcount), subtitle = sprintf("Variables %s by %s ", yname, xname) ) -> p print(p) } # If both are bare variables and found in the dataframe immediately print the plot if (deparse(substitute(xwhich)) %in% names(dataframe) & deparse(substitute(ywhich)) %in% names(dataframe)) { # both are names in the dataframe aaa <- enquo(xwhich) bbb <- enquo(ywhich) xname <- deparse(substitute(xwhich)) yname <- deparse(substitute(ywhich)) dfname <- deparse(substitute(dataframe)) PlotMagic(dataframe, aaa, bbb, whichbar, dfname, xname, yname) return(message(paste("Plotted dataset", argList$dataframe, "variables", argList$xwhich, "by", argList$ywhich))) } else { # is at least one in the dataframe? # Is at least one of them a bare variable in the dataframe if (deparse(substitute(xwhich)) %in% names(dataframe)) { # xwhich is in the dataframe aaa <- enquo(xwhich) if (class(try(eval(ywhich))) %in% c("integer", "numeric")) { # ywhich is column numbers indvars <- vector("list", length = length(ywhich)) totalcombos <- 1 # keep track of where we are xname <- deparse(substitute(xwhich)) dfname <- deparse(substitute(dataframe)) message("Creating the variable pairings from dataframe ", dfname) for (k in seq_along(ywhich)) { # for loop indvarsbare <- as.name(colnames(dataframe[ywhich[[k]]])) cat("Plot #", totalcombos, " ", xname, " with ", as.name(colnames(dataframe[ywhich[[k]]])), "\n", sep = "" ) bbb <- enquo(indvarsbare) yname <- deparse(substitute(indvarsbare)) PlotMagic(dataframe, aaa, bbb, whichbar, dfname, xname, yname) totalcombos <- totalcombos + 1 } # end of for loop return(message("Plotting complete")) } else { # ywhich is NOT suitable stop("Sorry I don't understand your ywhich variable(s)") } # } else { # xwhich wasn't try ywhich if (deparse(substitute(ywhich)) %in% names(dataframe)) { # yes ywhich is bbb <- enquo(ywhich) if (class(try(eval(xwhich))) %in% c("integer", "numeric")) { # then xwhich a suitable number # Build one list two ways depvars <- vector("list", length = length(xwhich)) totalcombos <- 1 # keep track of where we are yname <- deparse(substitute(ywhich)) dfname <- deparse(substitute(dataframe)) message("Creating the variable pairings from dataframe ", dfname) for (j in seq_along(xwhich)) { depvarsbare <- as.name(colnames(dataframe[xwhich[[j]]])) cat("Plot #", totalcombos, " ", as.name(colnames(dataframe[xwhich[[j]]])), " with ", yname, "\n", sep = "" ) aaa <- enquo(depvarsbare) xname <- deparse(substitute(depvarsbare)) PlotMagic(dataframe, aaa, bbb, whichbar, dfname, xname, yname) totalcombos <- totalcombos + 1 } # end of for loop return(message("Plotting complete")) } else { # xwhich is NOT suitable stop("Sorry I don't understand your xwhich variable(s)") } # end of else because xwhich not suitable } # end of if } } # If both variables are numeric print the plot(s) if (class(try(eval(xwhich))) %in% c("integer", "numeric") & class(try(eval(ywhich))) %in% c("integer", "numeric")) { indvars <- vector("list", length = length(ywhich)) depvars <- vector("list", length = length(xwhich)) dfname <- deparse(substitute(dataframe)) totalcombos <- 1 # keep track of where we are message("Creating the variable pairings from dataframe ", dfname) for (j in seq_along(xwhich)) { for (k in seq_along(ywhich)) { depvarsbare <- as.name(colnames(dataframe[xwhich[[j]]])) indvarsbare <- as.name(colnames(dataframe[ywhich[[k]]])) cat("Plot #", totalcombos, " ", as.name(colnames(dataframe[xwhich[[j]]])), " with ", as.name(colnames(dataframe[ywhich[[k]]])), "\n", sep = "" ) aaa <- enquo(depvarsbare) bbb <- enquo(indvarsbare) xname <- deparse(substitute(depvarsbare)) yname <- deparse(substitute(indvarsbare)) PlotMagic(dataframe, aaa, bbb, whichbar, dfname, xname, yname) totalcombos <- totalcombos + 1 } # end of inner for loop } # end of outer for loop return(message("Plotting complete")) } # end of if case where all are numeric } # end of function # PackageList <- .packages(all.available = TRUE) # if ("productplots" %in% PackageList) { # data("happy",package = "productplots") # } else { # stop("Can't load productplots can't use the following examples") # } #' \dontrun{ #' PlotXTabs(happy,happy,sex) # baseline #' PlotXTabs(happy,2,5,"stack") # same thing using column numbers #' PlotXTabs(happy, 2, c(5:9), plottype = "percent") # multiple columns RHS #' PlotXTabs(happy, c(2,5), 9, plottype = "side") # multiple columns LHS #' PlotXTabs(happy, c(2,5), c(6:9), plottype = "percent") #' PlotXTabs(happy, happy, c(6,7,9), plottype = "percent") #' PlotXTabs(happy, c(6,7,9), happy, plottype = "percent") #' }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/PlotXTabs.R
#' Bivariate bar (column) charts with statistical tests #' #' Bivariate bar charts for nominal and ordinal data with #' (optionally) statistical details included in the plot as a subtitle. #' #' @param data A dataframe or tibble containing the `x` and `y` variables. #' @param x The variable to plot on the X axis of the chart. #' @param y The variable to segment the **columns** and test for independence. #' @param counts If the dataframe is based upon counts rather than individual #' rows for observations, `counts` must contain the name of variable #' that contains the counts. See `HairEyeColor` example. #' @param results.subtitle Decides whether the results of statistical tests #' are displayed as a subtitle (Default: TRUE). If set to FALSE, no subtitle. #' @param paired Not used yet. #' @param sampling.plan the sampling plan (see details in ?contingencyTableBF). #' @param fixed.margin (see details in ?contingencyTableBF). #' @param prior.concentration (see details in ?contingencyTableBF). #' @param conf.level Scalar between 0 and 1. If unspecified, the defaults return #' lower and upper confidence intervals (0.95). #' @param title The text for the plot title. #' @param subtitle The text for the plot subtitle. **N.B** if statistical #' results are requested through `results.subtitle = TRUE` the results #' will have precedence. #' @param caption The text for the plot caption. Please note the interaction #' with `bf.details`. #' @param plottype one of four options "side", "stack", "mosaic" or "percent" #' @param sample.size.label Logical that decides whether sample size information #' should be displayed for each level of the grouping variable `y` #' (Default: `TRUE`). #' @param palette If a character string (e.g., `"Set1"`), will use that named #' palette. If a number, will index into the list of palettes of appropriate #' type. Default palette is `"Dark2"`. #' @param perc.k Numeric that decides number of decimal places for percentage #' labels (Default: `0`). #' @param labels.legend A character vector with custom labels for levels of #' the `y` variable displayed in the legend. #' @param xlab Custom text for the `x` axis label (Default: `NULL`, which #' will cause the `x` axis label to be the `x` variable). #' @param ylab Custom text for the `y` axis label (Default: `"Percent"`). Set #' to `NULL` for no label. #' @param data.label Character decides what information needs to be displayed #' on the label in each bar segment. Possible options are `"percentage"` #' (default), `"counts"`, `"both"`. #' @param legend.position The position of the legend #' `"none"`, `"left"`, `"right"`, `"bottom"`, `"top"` (Default: `"right"`). #' @param x.axis.orientation The orientation of the `x` axis labels one of #' "slant" or "vertical" to change from the default horizontal #' orientation (Default: `NULL` which is horizontal). #' @param label.text.size Numeric that decides size for bar labels #' (Default: `4`). #' @param label.fill.color Character that specifies fill color for bar labels #' (Default: `white`). #' @param label.fill.alpha Numeric that specifies fill color transparency or #' `"alpha"` for bar labels (Default: `1` range `0` to `1`). #' @param bar.outline.color Character specifying color for bars (default: `"black"`). #' @param package Name of package from which the palette is desired as string #' or symbol. #' @param palette Name of palette as string or symbol. #' @param ggtheme A function, ggplot2 theme name. Default value is ggplot2::theme_bw(). #' Any of the ggplot2 themes, or themes from extension packages are allowed (e.g., #' hrbrthemes::theme_ipsum(), etc.). #' @param ggplot.component A ggplot component to be added to the plot prepared by #' ggstatsplot. Default is NULL. The argument should be entered as a function. #' If the given function has an argument axes.range.restrict and if it has been set #' to TRUE, the added ggplot component might not work as expected. #' @param legend.title Title text for the legend. #' @param k Number of digits after decimal point (should be an integer) #' (Default: k = 2) for statistical results. #' @param direction Either `1` or `-1`. If `-1` the palette will be reversed. #' @param bf.details Logical that decides whether to display additional #' information from the Bayes Factor test in the caption (default:`FALSE`). #' This will take precedence over any text you enter as a `caption`. #' @param bf.display Character that determines how the Bayes factor value is #' is displayed. The default is simply the number rounded to `k`. Other #' options include "sensible", "log" and "support". #' @param mosaic.offset Numeric that decides size of spacing between mosaic #' blocks (Default: `.003` which is very narrow). "reasonable" values #' probably lie between .05 and .001 #' @param mosaic.alpha Numeric that controls the "alpha" level of the mosaic #' plot blocks (Default: `1` which is essentially no "fading"). Values must #' be in the range 0 to 1 see: `ggplot2::aes_colour_fill_alpha` #' #' #' @import ggplot2 #' @import ggmosaic #' #' @importFrom dplyr select group_by summarize n arrange if_else desc #' @importFrom dplyr mutate mutate_at mutate_if filter_all #' @importFrom rlang !! enquo quo_name #' @importFrom paletteer scale_fill_paletteer_d #' @importFrom tidyr uncount drop_na #' @importFrom dplyr as_tibble #' @importFrom scales label_percent #' @importFrom BayesFactor extractBF #' @importFrom BayesFactor contingencyTableBF #' @importFrom sjstats crosstable_statistics #' @importFrom scales label_percent #' #' @author Chuck Powell, Indrajeet Patil #' #' #' @examples #' #' # for reproducibility #' set.seed(123) #' #' # simplest possible call with the defaults #' PlotXTabs2( #' data = mtcars, #' y = vs, #' x = cyl #' ) #' #' # more complex call #' PlotXTabs2( #' data = datasets::mtcars, #' y = vs, #' x = cyl, #' bf.details = TRUE, #' labels.legend = c("0 = V-shaped", "1 = straight"), #' legend.title = "Engine Style", #' legend.position = "right", #' title = "The perenial mtcars example", #' palette = "Pastel1" #' ) #' #' PlotXTabs2( #' data = as.data.frame(HairEyeColor), #' y = Eye, #' x = Hair, #' counts = Freq #' ) #' #'\dontrun{ #' # mosaic plot requires ggmosaic 0.2.2 or higher from github #' PlotXTabs2( #' data = mtcars, #' x = vs, #' y = am, #' plottype = "mosaic", #' data.label = "both", #' mosaic.alpha = .9, #' bf.display = "support", #' title = "Motorcars Mosaic Plot VS by AM" #' ) #'} #' #' @export PlotXTabs2 <- function(data, x, y, counts = NULL, results.subtitle = TRUE, title = NULL, subtitle = NULL, caption = NULL, plottype = "percent", xlab = NULL, ylab = "Percent", legend.title = NULL, legend.position = "right", labels.legend = NULL, sample.size.label = TRUE, data.label = "percentage", label.text.size = 4, label.fill.color = "white", label.fill.alpha = 1, bar.outline.color = "black", x.axis.orientation = NULL, conf.level = 0.95, k = 2, perc.k = 0, mosaic.offset = .003, mosaic.alpha = 1, bf.details = FALSE, bf.display = "regular", sampling.plan = "jointMulti", fixed.margin = "rows", prior.concentration = 1, paired = FALSE, ggtheme = ggplot2::theme_bw(), package = "RColorBrewer", palette = "Dark2", direction = 1, ggplot.component = NULL) { # set default theme ggplot2::theme_set(ggtheme) ### ----- input checking ----------- if (base::missing(data)) { stop("You must specify a data source") } if (base::missing(x)) { stop("You must specify a x variable") } if (base::missing(y)) { stop("You must specify a y variable") } ### ----- x label and legend title ============== # if legend title is not provided, use the variable name for 'y' if (is.null(legend.title)) { legend.title <- rlang::as_name(rlang::enquo(y)) } # if not specified, use the variable name for 'x' if (is.null(xlab)) { xlab <- rlang::as_name(rlang::enquo(x)) } ### ----- create temp local dataframe ==================== # creating a dataframe based on whether counts if (base::missing(counts)) { data <- dplyr::select( .data = data, y = {{ y }}, x = {{ x }} ) } else { data <- dplyr::select( .data = data, y = !!rlang::enquo(y), x = !!rlang::quo_name(rlang::enquo(x)), counts = !!rlang::quo_name(rlang::enquo(counts)) ) data <- data %>% tidyr::uncount( data = ., weights = counts, .remove = TRUE, .id = "id" ) } original_N <- nrow(data) ### ----- calculate counts and percents ------- # y and x need to be a factor or ordered factor # also drop the unused levels of the factors and NAs data <- data %>% dplyr::mutate_if(.tbl = ., not_a_factor, as.factor) %>% dplyr::mutate_if(.tbl = ., is.factor, droplevels) %>% dplyr::filter_all(.tbl = ., all_vars(!is.na(.))) valid_N <- nrow(data) missing_N <- original_N - valid_N # converting to tibble data <- data %>% dplyr::as_tibble(x = .) # convert the data into percentages; group by conditional variable df <- data %>% dplyr::group_by(.data = ., x, y) %>% dplyr::summarize(.data = ., counts = n()) %>% dplyr::mutate(.data = ., perc = (counts / sum(counts)) * 100) %>% dplyr::ungroup(x = .) %>% dplyr::arrange(.data = ., dplyr::desc(x = y)) %>% dplyr::filter(.data = ., counts != 0L) ### ----- bar segment labels ------------ # checking what needs to be displayed on bar segments as labels and # the text size for the label; if both counts and percentages are going to # be displayed, then use a bit smaller text size if (data.label == "percentage") { # only percentage df <- df %>% dplyr::mutate( .data = ., data.label = paste0(round(x = perc, digits = perc.k), "%") ) } else if (data.label == "counts") { # only raw counts df <- df %>% dplyr::mutate( .data = ., data.label = paste0("", counts) ) } else if (data.label == "both") { # both raw counts and percentages df <- df %>% dplyr::mutate( .data = ., data.label = paste0( "", counts, "\n(", round(x = perc, digits = perc.k), "%)" ) ) } ### ----- sample size label ===================== # if labels are to be displayed on the bottom of the charts # for each bar/column if (isTRUE(sample.size.label)) { df_n_label <- data %>% dplyr::group_by(.data = ., x) %>% dplyr::summarize(.data = ., N = n()) %>% dplyr::mutate(.data = ., N = paste0("(n = ", N, ")", sep = "")) } ### ----- preparing names for legend ====================== # getting labels for all levels of the 'y' variable factor if (is.null(labels.legend)) { legend.labels <- levels(df$y) } else if (!missing(labels.legend)) { legend.labels <- labels.legend } ### ----- start main plot ============================ # plot if (plottype == "side") { p <- ggplot2::ggplot( data = df, mapping = ggplot2::aes(fill = y, y = counts, x = x) ) + ggplot2::geom_bar( stat = "identity", position = position_dodge2(reverse = TRUE), color = bar.outline.color, na.rm = TRUE ) + ggplot2::geom_label( mapping = ggplot2::aes(label = data.label, group = y), show.legend = FALSE, position = position_dodge2(width = .9, reverse = TRUE), size = label.text.size, fill = label.fill.color, alpha = label.fill.alpha, na.rm = TRUE ) } else if (plottype == "stack") { p <- ggplot2::ggplot( data = df, mapping = ggplot2::aes(fill = y, y = counts, x = x) ) + ggplot2::geom_bar( stat = "identity", color = bar.outline.color, na.rm = TRUE, position = position_stack(reverse = TRUE) ) + ggplot2::geom_label( mapping = ggplot2::aes(label = data.label, group = y), show.legend = FALSE, position = position_stack(vjust = 0.5, reverse = TRUE), size = label.text.size, fill = label.fill.color, alpha = label.fill.alpha, na.rm = TRUE ) } else if (plottype == "mosaic") { p <- ggplot2::ggplot(data = df) + ggmosaic::geom_mosaic(aes(weight = counts, x = ggmosaic::product(x), fill = y), offset = mosaic.offset, alpha = mosaic.alpha) + scale_y_continuous(labels = scales::label_percent(accuracy = 1.0), breaks = seq(from = 0, to = 1, by = 0.10), minor_breaks = seq(from = 0.05, to = 0.95, by = 0.10)) ### ---- Extract mosaic info and calculate cell pcts mosaicgeominfo <- ggplot2::ggplot_build(p)$data[[1]] %>% group_by_at(vars(ends_with("__x"))) %>% mutate(NN = sum(.wt)) %>% mutate(pct = (.wt/NN)) if (data.label == "percentage") { # only percentage mosaicgeominfo <- mosaicgeominfo %>% dplyr::mutate( .data = ., data.label = paste0(round(x = pct*100, digits = perc.k), "%") ) } else if (data.label == "counts") { # only raw counts mosaicgeominfo <- mosaicgeominfo %>% dplyr::mutate( .data = ., data.label = paste0("", .wt) ) } else if (data.label == "both") { # both raw counts and percentages mosaicgeominfo <- mosaicgeominfo %>% dplyr::mutate( .data = ., data.label = paste0( "", .wt, "\n(", round(x = pct*100, digits = perc.k), "%)" ) ) } p <- p + geom_label(data = mosaicgeominfo, aes(x = (xmin + xmax)/2, y = (ymin + ymax)/2, label = data.label ), size = label.text.size, fill = label.fill.color, alpha = label.fill.alpha ) } else { p <- ggplot2::ggplot( data = df, mapping = ggplot2::aes(fill = y, y = perc, x = x) ) + ggplot2::geom_bar( stat = "identity", position = ggplot2::position_fill(reverse = TRUE), color = bar.outline.color, na.rm = TRUE ) + ggplot2::scale_y_continuous( labels = scales::label_percent(accuracy = 1.0), breaks = seq(from = 0, to = 1, by = 0.10), minor_breaks = seq(from = 0.05, to = 0.95, by = 0.10) ) + ggplot2::geom_label( mapping = ggplot2::aes(label = data.label, group = y), show.legend = FALSE, position = ggplot2::position_fill(reverse = TRUE, vjust = 0.5), size = label.text.size, fill = label.fill.color, alpha = label.fill.alpha, na.rm = TRUE ) } p <- p + ggplot2::theme( panel.grid.major.x = ggplot2::element_blank(), legend.position = legend.position ) + ggplot2::guides(fill = ggplot2::guide_legend(title = legend.title, reverse = TRUE) ) + paletteer::scale_fill_paletteer_d( palette = paste0(package, "::", palette), direction = direction, name = "", labels = unique(legend.labels) ) ### ----- chi-square test (with Bayes) for caption and subtitle ============= if (isTRUE(results.subtitle)) { chi.results <- sjstats::crosstable_statistics(data = data, x1 = y, x2 = x) chivalue <- round(chi.results$statistic, k) chidf <- chi.results$df ppvalue <- pvalr(chi.results$p.value) effecttype <- chi.results$method effectvalue <- round(chi.results$estimate, k) bf10_results <- BayesFactor::extractBF( BayesFactor::contingencyTableBF( x = table(data$y, data$x), sampleType = sampling.plan, fixedMargin = fixed.margin, priorConcentration = prior.concentration ), onlybf = TRUE) bf_dtext <- bf_display(bf10_results, k = k, display_type = bf.display) bf10_results <- round(bf10_results, k) bf01_results = round((1 / bf10_results), k) if (bf10_results >= 1) { subtitle <- bquote(~ chi['Ind']^2 * "[" * .(chidf) * "]=" * .(chivalue) * ", " * .(effecttype) * "=" * bold(.(effectvalue)) * ", p=" * .(ppvalue) * ", " * BF['10'] * .(bf_dtext) * ", N=" *.(valid_N) * ", missing=" *.(missing_N) ) if (isTRUE(bf.details)) { caption <- bquote(~ BF['01'] * "=" * .(bf01_results) * ", Sampling plan = " * .(sampling.plan) * ", Prior concentration = " * .(prior.concentration) ) } } else { subtitle <- bquote(~ chi['Ind']^2 * "[" * .(chidf) * "]=" * .(chivalue) * ", " * .(effecttype) * "=" * bold(.(effectvalue)) * ", p=" * .(ppvalue) * ", " * BF['01'] * .(bf_dtext) * ", N=" *.(valid_N) * ", missing=" *.(missing_N) ) if (isTRUE(bf.details)) { caption <- bquote(~ BF['10'] * "=" * .(bf10_results) * ", Sampling plan = " * .(sampling.plan) * ", Prior concentration = " * .(prior.concentration) ) } } } ### ----- adding sample size info on x axis ------- if (plottype == "percent" || plottype == "mosaic") { y_adjustment <- -0.05 } else { y_adjustment <- -0.05 * max(df$counts) if (!is.null(ylab) && ylab == "Percent") { ylab <- "Counts" } } if (plottype != "mosaic") { if (isTRUE(sample.size.label)) { p <- p + ggplot2::geom_text( data = df_n_label, mapping = ggplot2::aes( x = x, y = y_adjustment, label = N, fill = NULL ), size = 4, na.rm = TRUE ) } } else { if (isTRUE(sample.size.label)) { # Compute mosaic x axis label tick positions xNlabelpos <- mosaicgeominfo %>% distinct(xNlabelpos = ((xmax - xmin)/2) + xmin) %>% pull(xNlabelpos) p <- p + ggplot2::geom_text( data = df_n_label, mapping = ggplot2::aes( x = xNlabelpos, y = y_adjustment, label = N, fill = NULL ), size = 4, na.rm = TRUE ) } } ### ----- if we need to modify `x`-axis orientation ---- if (!base::missing(x.axis.orientation)) { if (x.axis.orientation == "slant") { p <- p + ggplot2::theme( axis.text.x = ggplot2::element_text( angle = 45, vjust = 1, hjust = 1, face = "bold" ) ) } else if (x.axis.orientation == "vertical") { p <- p + ggplot2::theme( axis.text.x = ggplot2::element_text( angle = 90, vjust = 0.5, hjust = 1, face = "bold" ) ) } } else { p <- p + ggplot2::theme( axis.text.x = ggplot2::element_text( face = "bold" ) ) } ### ----- add titles, captions and labels to plot ------ p <- p + ggplot2::labs( x = xlab, y = ylab, subtitle = subtitle, title = title, caption = caption ) ### ----- adding optional ggplot.component ---------- p <- p + ggplot.component ### ----- return the final plot ------- return(p) }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/PlotXTabs2.R
#' Anova Tables for Type 2 sums of squares #' #' Calculates and displays type-II analysis-of-variance tables for model objects #' produced by aov. This is a vastly reduced version of the Anova function from #' package car #' #' Details about how the function works in order of steps taken. #' Type-II tests are invariant with respect to (full-rank) contrast coding. #' Type-II tests are calculated according to the principle of marginality, #' testing each term after all others, except ignoring the term's higher-order #' relatives. This definition of Type-II tests corresponds to the tests #' produced by SAS for analysis-of-variance models, where all of the #' predictors are factors, but not more generally (i.e., when there are #' quantitative predictors). #' #' @usage aovtype2(mod) #' @param mod aov model object from base R. #' @return An object of class "anova", which usually is printed. #' #' @references: Fox, J. (2016) Applied Regression Analysis and Generalized Linear Models, Third Edition. Sage. #' #' @author John Fox [email protected]; as modified by Chuck Powell #' @seealso \code{\link[stats]{aov}} #' @examples #' #' mtcars$cyl <- factor(mtcars$cyl) #' mtcars$am <- factor(mtcars$am) #' mod <- aov(hp ~ cyl * am, data = mtcars) #' aovtype2(mod) #' #' @export #' aovtype2 <- function(mod) { if (class(mod)[[1]] != "aov") stop("Function is only for aov models") else class(mod) <- "lm" if (df.residual(mod) == 0) stop("residual df = 0") if (deviance(mod) < sqrt(.Machine$double.eps)) stop("residual sum of squares is 0 (within rounding error)") SS.term <- function(term){ which.term <- which(term == names) subs.term <- which(assign == which.term) relatives <- relatives(term, names, fac) subs.relatives <- NULL for (relative in relatives) subs.relatives <- c(subs.relatives, which(assign == relative)) hyp.matrix.1 <- I.p[subs.relatives,,drop=FALSE] hyp.matrix.1 <- hyp.matrix.1[, not.aliased, drop=FALSE] hyp.matrix.2 <- I.p[c(subs.relatives,subs.term),,drop=FALSE] hyp.matrix.2 <- hyp.matrix.2[, not.aliased, drop=FALSE] hyp.matrix.term <- if (nrow(hyp.matrix.1) == 0) hyp.matrix.2 else t(ConjComp(t(hyp.matrix.1), t(hyp.matrix.2), vcov(mod, complete=FALSE))) hyp.matrix.term <- hyp.matrix.term[!apply(hyp.matrix.term, 1, function(x) all(x == 0)), , drop=FALSE] if (nrow(hyp.matrix.term) == 0) return(c(SS=NA, df=0)) lh <- linearHypothesis(mod, hyp.matrix.term, singular.ok = TRUE) abs(c(SS=lh$"Sum of Sq"[2], df=lh$Df[2])) } not.aliased <- !is.na(coef(mod)) if (!all(not.aliased)) stop("there are aliased coefficients in the model") fac <- attr(terms(mod), "factors") intercept <- has.intercept(mod) I.p <- diag(length(coefficients(mod))) assign <- mod$assign assign[!not.aliased] <- NA names <- term.names(mod) if (intercept) names <-names[-1] n.terms <- length(names) p <- df <- f <- SS <- rep(0, n.terms + 1) sumry <- summary(mod, corr = FALSE) SS[n.terms + 1] <- sumry$sigma^2*mod$df.residual df[n.terms + 1] <- mod$df.residual p[n.terms + 1] <- f[n.terms + 1] <- NA for (i in 1:n.terms){ ss <- SS.term(names[i]) SS[i] <- ss["SS"] df[i] <- ss["df"] f[i] <- df[n.terms+1]*SS[i]/(df[i]*SS[n.terms + 1]) p[i] <- pf(f[i], df[i], df[n.terms + 1], lower.tail = FALSE) } result <- data.frame(SS, df, f, p) row.names(result) <- c(names,"Residuals") names(result) <- c("Sum Sq", "Df", "F value", "Pr(>F)") class(result) <- c("anova", "data.frame") attr(result, "heading") <- c("Anova Table (Type II tests)\n", paste("Response:", responseName(mod))) result }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/aovtype2.R
# Utility functions fom car package by J. Fox ConjComp <- function(X, Z = diag( nrow(X)), ip = diag(nrow(X))) { xq <- qr(t(Z) %*% ip %*% X) if (xq$rank == 0) return(Z) Z %*% qr.Q(xq, complete = TRUE) [ ,-(1:xq$rank)] } relatives <- function(term, names, factors){ is.relative <- function(term1, term2) { all(!(factors[,term1]&(!factors[,term2]))) } if(length(names) == 1) return(NULL) which.term <- which(term==names) (1:length(names))[-which.term][sapply(names[-which.term], function(term2) is.relative(term, term2))] } print.univaov <- function(x, digits = max(getOption("digits") - 2L, 3L), style=c("wide", "long"), by=c("response", "term"), ...){ style <- match.arg(style) if (style == "wide") { cat("\n Type", x$type, "Sums of Squares\n") print(x$SS, digits=digits) cat("\n F-tests\n") F <- x$F print(round(F, 2)) cat("\n p-values\n") p <- format.pval(x$p) p <- matrix(p, nrow=nrow(F)) rownames(p) <- rownames(F) colnames(p) <- colnames(F) print(p, quote=FALSE) if (!is.null(x$p.adjust)){ cat("\n p-values adjusted (by term) for simultaneous inference by", x$p.adjust.method, "method\n") p.adjust <- format.pval(x$p.adjust) p.adjust <- matrix(p.adjust, nrow=nrow(F)) rownames(p.adjust) <- rownames(F) colnames(p.adjust) <- colnames(F) print(p.adjust, quote=FALSE) } } else { x.df <- as.data.frame(x, by=by) x.df$F <- round(x.df$F, 2) x.df$p <- format.pval(x.df$p) if (!is.null(x$p.adjust)) x.df$"adjusted p" <- format.pval(x.df$"adjusted p") cat("\n Type", x$type, "Sums of Squares and F tests\n") print(x.df, quote=FALSE, digits=digits) } invisible(x) } as.data.frame.univaov <- function(x, row.names, optional, by=c("response", "term"), ...) { melt <- function(data, varnames = names(dimnames(data)), value.name = "value") { dn <- dimnames(data) labels <- expand.grid( dn[[1]], dn[[2]]) colnames(labels) <- varnames value_df <- setNames(data.frame(as.vector(data)), value.name) cbind(labels, value_df) } nv <- ncol(x$F) nt <- nrow(x$F) by <- match.arg(by) if (by=="response") { vn <- c("term", "response") df <- matrix(x$SS[1:nt, "df", drop=FALSE], nrow=nt, ncol=nv) SS <- melt(x$SS[1:nt, -1, drop=FALSE], varnames=vn, value.name="SS") F <- melt(x$F, varnames=vn, value.name="F") p <- melt(x$p, varnames=vn, value.name="p") if (!is.null(x$p.adjust)) p.adjust <- melt(x$p.adjust, varnames=vn, value.name="adjusted p") } else { vn <- rev(c("term", "response")) df <- t(matrix(x$SS[1:nt, "df", drop=FALSE], nrow=nt, ncol=nv)) SS <- melt(t(x$SS[1:nt, -1, drop=FALSE]), varnames=vn, value.name="SS") F <- melt(t(x$F), varnames=vn, value.name="F") p <- melt(t(x$p), varnames=vn, value.name="p") if (!is.null(x$p.adjust)) p.adjust <- melt(t(x$p.adjust), varnames=vn, value.name="adjusted p") } result <- cbind(SS[,c(2,1,3)], df=c(df), F=F[,"F"], p=p[,"p"]) if (!is.null(x$p.adjust)) result <- cbind(result, "adjusted p"=p.adjust[, "adjusted p"]) result } assignVector <- function(model){ m <- model.matrix(model) assign <- attr(m, "assign") if (!is.null(assign)) return (assign) m <- model.matrix(formula(model), data=model.frame(model)) assign <- attr(m, "assign") if (!has.intercept(model)) assign <- assign[assign != 0] assign } has.intercept <- function (model, ...) { UseMethod("has.intercept") } has.intercept.default <- function(model, ...) any(names(coefficients(model))=="(Intercept)") term.names <- function (model, ...) { UseMethod("term.names") } term.names.default <- function (model, ...) { term.names <- labels(terms(model)) if (has.intercept(model)) c("(Intercept)", term.names) else term.names } predictor.names <- function(model, ...) { UseMethod("predictor.names") } predictor.names.default <- function(model, ...){ predictors <- attr(terms(model), "variables") as.character(predictors[3:length(predictors)]) } responseName <- function (model, ...) { UseMethod("responseName") } responseName.default <- function (model, ...) deparse(attr(terms(model), "variables")[[2]]) response <- function(model, ...) { UseMethod("response") } response.default <- function (model, ...) model.response(model.frame(model)) is.aliased <- function(model){ !is.null(alias(model)$Complete) } df.terms <- function(model, term, ...){ UseMethod("df.terms") } df.terms.default <- function(model, term, ...){ if (is.aliased(model)) stop("Model has aliased term(s); df ambiguous.") if (!missing(term) && 1 == length(term)){ assign <- attr(model.matrix(model), "assign") which.term <- which(term == labels(terms(model))) if (0 == length(which.term)) stop(paste(term, "is not in the model.")) sum(assign == which.term) } else { terms <- if (missing(term)) labels(terms(model)) else term result <- numeric(0) for (term in terms) result <- c(result, Recall(model, term)) names(result) <- terms result } } inv <- function(x) solve(x) coefnames2bs <- function(g, para.names, parameterPrefix="b"){ metas <- c("(", ")", "[", "]", "{", "}", ".", "*", "+", "^", "$", ":", "|") metas2 <- paste("\\", metas, sep="") metas3 <- paste("\\\\", metas, sep="") for (i in seq(along=metas)) para.names <- gsub(metas2[i], metas3[i], para.names) # fix up metacharacters para.order <- order(nchar(para.names), decreasing=TRUE) para.names <- para.names[para.order] # avoid partial-name substitution std.names <- if ("(Intercept)" %in% para.names) paste(parameterPrefix, 0:(length(para.names) - 1), sep = "") else paste(parameterPrefix, 1:length(para.names), sep = "") std.names.ordered <- std.names[para.order] for (i in seq(along=para.names)){ g <- gsub(para.names[i], std.names.ordered[i], g) } list(g=g, std.names=std.names) } has.intercept.matrix <- function (model, ...) { "(Intercept)" %in% colnames(model) } printHypothesis <- function(L, rhs, cnames){ hyp <- rep("", nrow(L)) for (i in 1:nrow(L)){ sel <- L[i,] != 0 h <- L[i, sel] h <- ifelse(h < 0, as.character(h), paste("+", h, sep="")) nms <- cnames[sel] h <- paste(h, nms) h <- gsub("-", " - ", h) h <- gsub("+", " + ", h, fixed=TRUE) h <- paste(h, collapse="") h <- gsub(" ", " ", h, fixed=TRUE) h <- sub("^\\ \\+", "", h) h <- sub("^\\ ", "", h) h <- sub("^-\\ ", "-", h) h <- paste(" ", h, sep="") h <- paste(h, "=", rhs[i]) h <- gsub(" 1([^[:alnum:]_.]+)[ *]*", "", gsub("-1([^[:alnum:]_.]+)[ *]*", "-", gsub("- +1 +", "-1 ", h))) h <- sub("Intercept)", "(Intercept)", h) h <- gsub("-", " - ", h) h <- gsub("+", " + ", h, fixed=TRUE) h <- gsub(" ", " ", h, fixed=TRUE) h <- sub("^ *", "", h) hyp[i] <- h } hyp } linearHypothesis <- function (model, ...) UseMethod("linearHypothesis") lht <- function (model, ...) UseMethod("linearHypothesis") linearHypothesis.nlsList <- function(model, ..., vcov., coef.){ vcov.nlsList <- function(object, ...) { vlist <- lapply(object, vcov) ng <- length(vlist) nv <- dim(vlist[[1]])[1] v <- matrix(0, nrow=ng*nv, ncol=ng*nv) for (j in 1:ng){ cells <- ((j-1)*nv + 1):(j*nv) v[cells, cells] <- vlist[[j]] } v } linearHypothesis.default(model, vcov.=vcov.nlsList(model), coef.=unlist(lapply(model, coef)), ...)} linearHypothesis.default <- function(model, hypothesis.matrix, rhs=NULL, test=c("Chisq", "F"), vcov.=NULL, singular.ok=FALSE, verbose=FALSE, coef. = coef(model), ...){ df <- df.residual(model) if (is.null(df)) df <- Inf ## if no residual df available if (df == 0) stop("residual df = 0") V <- if (is.null(vcov.)) vcov(model, complete=FALSE) else if (is.function(vcov.)) vcov.(model) else vcov. b <- coef. if (any(aliased <- is.na(b)) && !singular.ok) stop("there are aliased coefficients in the model") b <- b[!aliased] if (is.null(b)) stop(paste("there is no coef() method for models of class", paste(class(model), collapse=", "))) if (is.character(hypothesis.matrix)) { L <- makeHypothesis(names(b), hypothesis.matrix, rhs) if (is.null(dim(L))) L <- t(L) rhs <- L[, NCOL(L)] L <- L[, -NCOL(L), drop = FALSE] rownames(L) <- hypothesis.matrix } else { L <- if (is.null(dim(hypothesis.matrix))) t(hypothesis.matrix) else hypothesis.matrix if (is.null(rhs)) rhs <- rep(0, nrow(L)) } q <- NROW(L) value.hyp <- L %*% b - rhs vcov.hyp <- L %*% V %*% t(L) if (verbose){ cat("\nHypothesis matrix:\n") print(L) cat("\nRight-hand-side vector:\n") print(rhs) cat("\nEstimated linear function (hypothesis.matrix %*% coef - rhs)\n") print(drop(value.hyp)) cat("\n") if (length(vcov.hyp) == 1) cat("\nEstimated variance of linear function\n") else cat("\nEstimated variance/covariance matrix for linear function\n") print(drop(vcov.hyp)) cat("\n") } SSH <- as.vector(t(value.hyp) %*% solve(vcov.hyp) %*% value.hyp) test <- match.arg(test) if (!(is.finite(df) && df > 0)) test <- "Chisq" name <- try(formula(model), silent = TRUE) if (inherits(name, "try-error")) name <- substitute(model) title <- "Linear hypothesis test\n\nHypothesis:" topnote <- paste("Model 1: restricted model","\n", "Model 2: ", paste(deparse(name), collapse = "\n"), sep = "") note <- if (is.null(vcov.)) "" else "\nNote: Coefficient covariance matrix supplied.\n" rval <- matrix(rep(NA, 8), ncol = 4) colnames(rval) <- c("Res.Df", "Df", test, paste("Pr(>", test, ")", sep = "")) rownames(rval) <- 1:2 rval[,1] <- c(df+q, df) if (test == "F") { f <- SSH/q p <- pf(f, q, df, lower.tail = FALSE) rval[2, 2:4] <- c(q, f, p) } else { p <- pchisq(SSH, q, lower.tail = FALSE) rval[2, 2:4] <- c(q, SSH, p) } if (!(is.finite(df) && df > 0)) rval <- rval[,-1] result <- structure(as.data.frame(rval), heading = c(title, printHypothesis(L, rhs, names(b)), "", topnote, note), class = c("anova", "data.frame")) attr(result, "value") <- value.hyp attr(result, "vcov") <- vcov.hyp result } linearHypothesis.lm <- function(model, hypothesis.matrix, rhs=NULL, test=c("F", "Chisq"), vcov.=NULL, singular.ok=FALSE, ...){ if (df.residual(model) == 0) stop("residual df = 0") if (deviance(model) < sqrt(.Machine$double.eps)) stop("residual sum of squares is 0 (within rounding error)") if (!singular.ok && is.aliased(model)) stop("there are aliased coefficients in the model.") test <- match.arg(test) rval <- linearHypothesis.default(model, hypothesis.matrix, rhs = rhs, test = test, vcov. = vcov., singular.ok=singular.ok, ...) if (is.null(vcov.)) { rval2 <- matrix(rep(NA, 4), ncol = 2) colnames(rval2) <- c("RSS", "Sum of Sq") SSH <- rval[2,test] if (test == "F") SSH <- SSH * abs(rval[2, "Df"]) df <- rval[2, "Res.Df"] error.SS <- deviance(model) rval2[,1] <- c(error.SS + SSH * error.SS/df, error.SS) rval2[2,2] <- abs(diff(rval2[,1])) rval2 <- cbind(rval, rval2)[,c(1, 5, 2, 6, 3, 4)] class(rval2) <- c("anova", "data.frame") attr(rval2, "heading") <- attr(rval, "heading") attr(rval2, "value") <- attr(rval, "value") attr(rval2, "vcov") <- attr(rval, "vcov") rval <- rval2 } rval }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/aovtype2_helpers.R
#' Produce CHAID results tables from a partykit CHAID model #' #' @param chaidobject An object of type `constparty` or `party` which #' was produced by `CHAID::chaid` see simple example below. #' @return A tibble containing the results. #' #' @import dplyr #' @import partykit #' #' @importFrom purrr map_dfr #' @importFrom stringr str_replace_all str_split str_trim #' @importFrom dplyr as_tibble #' @importFrom utils getFromNamespace #' @importFrom tidyr pivot_wider separate #' @importFrom grid depth #' @importFrom stats complete.cases formula #' #' @author Chuck Powell #' #' @examples #' library(CGPfunctions) #' chaid_table(chaidUS) #' #' @export #' chaid_table <- function(chaidobject) { # circumventing the fact that partykit doesn't export a function I need .list.rules.party = getFromNamespace(".list.rules.party", "partykit") # extract the formula from the object model.formula <- formula(chaidobject) # extract the name of the outcome variable # all.vars(model.formula)[[1]] outcome.variable <- all.vars(model.formula)[[1]] # get all the nodeids as a vector all_nodes <- partykit::nodeids(chaidobject) # get the terminal nodes as a vector terminal_nodes <- partykit::nodeids(chaidobject, terminal = TRUE) # get the split points or inner nodes or non-terminal nodes as a vector inner_nodes <- all_nodes[!(all_nodes %in% nodeids(chaidobject, terminal = TRUE))] # partykit:::.list.rules.party extracts the split rule that generates # the prediction for a single node we've pulled it in above with # getFromNamespace(".list.rules.party", "partykit") node_rules <- .list.rules.party(chaidobject, 1:length(chaidobject)) # create an empty tibble to start populating the node table node_table <- tibble::tibble() # rejoin the oucome variable to the rest of the data frame # since chaid separated them original_df <- cbind(chaidobject$data, outcome = chaidobject$fitted$`(response)`) # a simple for loop to iterate through all the nodes # logic for the top node #1 is slightly different since # it has no split rule since it was never split # Complete cases is probably unnecessary # .drop = FLASE keeps us from losing counts to NA if there are no cases # eval(parse(text = node_rules[[i]])) uses valid filter conditions for (i in all_nodes) { if (i == 1) { xxx <- original_df %>% filter(complete.cases(.)) %>% group_by(outcome) %>% summarise(N = n()) %>% tidyr::pivot_wider( names_from = outcome, values_from = N ) xxx$splitrule <- NA } else { xxx <- original_df %>% filter(complete.cases(.)) %>% group_by(outcome, .drop = FALSE) %>% filter(eval(parse(text = node_rules[[i]]))) %>% summarise(N = n()) %>% pivot_wider( names_from = outcome, values_from = N ) xxx$splitrule <- gsub("\"", "'", node_rules[i], fixed = TRUE ) } xxx$nodeID <- i node_table <- rbind(node_table, xxx) } # technically may be more than 2 must test outcome.levels <- nlevels(original_df$outcome) node_table <- tidyr::separate( data = node_table, col = splitrule, sep = "&", into = paste0("split", 1:depth(chaidobject)), remove = FALSE, fill = "right") %>% mutate(NodeN = rowSums(.[1:outcome.levels])) %>% select(nodeID, NodeN, everything()) %>% mutate_at(vars(starts_with("split")), str_trim) find_my_parent <- function(node) { # depth-first walk on partynode structure (recursive function) # decision rules are extracted for every branch # parents and children are linked # because or recursion using <<- which isn't my favorite if (!is.terminal(node)) { for (i in 1:length(node)) { child <- node$kids[[i]]$id parent <- node$id node_table[node_table$nodeID == child, "parent"] <<- parent find_my_parent(node[[i]]) } } } find_my_parent(chaidobject$node) # splitrule is hard to read make ruletext as more plain text node_table$ruletext <- str_replace_all(node_table$splitrule, c("%in%" = "is", "c\\('" = "'", "'\\)" = "'") ) # give the inner nodes names to use later on so we don't lose track # during map_dfr operation names(inner_nodes) <- inner_nodes # Create an empty split table split_table <- tibble::tibble() # build the split table with relevant stats split_table <- map_dfr( .x = inner_nodes, ~ node_table %>% filter(parent == .x) %>% select(levels(original_df$outcome)) %>% chisq.test(correct = FALSE) %>% newbroom(), .id = "nodeID") %>% rename( chisq = statistic, rawpvalue = p.value, df = parameter) %>% select(-method) split_table$nodeID <- as.integer(split_table$nodeID) split_table$adjustedp <- NA_real_ split_table$split.variable <- NA_character_ for (i in inner_nodes) { split_table[split_table$nodeID == i, "adjustedp"] <- min(unlist(nodeapply(chaidobject, ids = all_nodes, FUN = function(n) n$info)[[i]] ) ) split_table[split_table$nodeID == i, "split.variable"] <- attr(which.min(unlist(nodeapply(chaidobject, ids = all_nodes, FUN = function(n) n$info)[[i]] ) ), "names" ) } split_table$split.variable <- str_split(split_table$split.variable, "\\.", n = 2, simplify = TRUE)[,2] node_table <- full_join(node_table, split_table, by = "nodeID") node_table <- node_table %>% select(nodeID, parent, NodeN, levels(original_df$outcome), ruletext, split.variable, chisq, df, adjustedp, rawpvalue, everything()) node_table }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/chaid_table.R
#' Cross two vectors of variable names from a dataframe #' #' @param data the dataframe or tibble the variables are contained in. #' @param x,y These are either character or integer vectors containing #' the names, e.g. "am" or the column numbers e.g. 9 #' @param verbose the default is FALSE, setting to TRUE will cat additional #' output to the screen #' #' @return a list with two sublists `lista` and `listb`. Very handy for #' feeding the lists to `purrr` for further processing. #' @author Chuck Powell #' @export #' #' @examples #' cross2_var_vectors(mtcars, 9, c(2, 10:11)) #' cross2_var_vectors(mtcars, "am", c("cyl", "gear", "carb")) #' x2 <- c("am", "carb") #' y2 <- c("vs", "cyl", "gear") #' cross2_var_vectors(mtcars, x2, y2, verbose = TRUE) #' #' \dontrun{ #' variables_list <- cross2_var_vectors(mtcars, x2, y2) #' mytitles <- stringr::str_c( #' stringr::str_to_title(variables_list$listb), #' " by ", #' stringr::str_to_title(variables_list$lista), #' " in mtcars data" #' ) #' purrr::pmap( #' .l = list( #' x = variables_list[[1]], # variables_list$lista #' y = variables_list[[2]], # variables_list$listb #' title = mytitles #' ), #' .f = CGPfunctions::PlotXTabs2, #' data = mtcars, #' ylab = NULL, #' perc.k = 1, #' palette = "Set2" #' ) #' #' } #' cross2_var_vectors <- function(data, x, y, verbose = FALSE) { # some quick sanity checks if (!is.data.frame(data)) { stop("data must be a dataframe or tibble") } if (!is.character(y) && !is.numeric(y)) { stop("x and y need to be either character or numeric vectors") } if (!is.character(x) && !is.numeric(x)) { stop("x and y need to be either character or numeric vectors") } ######## if (is.numeric(x) && (max(x) > ncol(data) || min(x) < 1)) { stop("x contains one or more items that are not a valid column number") } if (is.numeric(y) && (max(y) > ncol(data) || min(y) < 1)) { stop("y contains one or more items that are not a valid column number") } ######## if (is.character(x) && !all(x %in% colnames(data))) { stop("x contains one or more items that are not columns in data") } if (is.character(y) && !all(y %in% colnames(data))) { stop("y contains one or more items that are not columns in data") } if (any(colnames(data[x]) %in% colnames(data[y]))) { stop("x and y cannot contain a common variable") } # initialize two empty lists of the proper length x * y listb <- lista <- vector( mode = "list", length = (length(x) * length(y)) ) # do the work by looping through both vectors current_combo <- 1 for (j in seq_along(x)) { for (k in seq_along(y)) { listb[[current_combo]] <- colnames(data[x[[j]]]) lista[[current_combo]] <- colnames(data[y[[k]]]) if (verbose) { cat("Pair ", current_combo, " lista = ", lista[[current_combo]], " listb = ", listb[[current_combo]], "\n", sep = "" ) } current_combo <- current_combo + 1 } } # return a list with two sublists return(list(lista = lista, listb = listb)) }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/cross2_var_vectors.R
#' @rdname newcancer #' @title Tufte dataset on cancer survival rates #' @aliases newcancer #' #' @description A dataset containing cancer survival rates for different types of cancer #' over a 20 year period. #' #' @format A data frame with 96 rows and 3 variables: #' \describe{ #' \item{Year}{ordered factor for the 5, 10, 15 and 20 year survival rates} #' \item{Type}{factor containing the name of the cancer type} #' \item{Survival}{numeric for this data a whole number corresponding to the percent survival rate} #' #' } #' @source \url{https://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0003nk} #' @keywords datasets "newcancer" #' @rdname newgdp #' @title Tufte dataset on Gross Domestic Product, 1970 and 1979 #' @aliases newgdp #' @description Current receipts of fifteen national governments as a percentage of gross domestic product #' #' @format A data frame with 30 rows and 3 variables: #' \describe{ #' \item{Year}{character for 1970 and 1979} #' \item{Country}{factor country name} #' \item{GDP}{numeric a percentage of gross domestic product} #' #' } #' @source Edward Tufte. \emph{Beautiful Evidence}. Graphics Press, 174-176. #' @keywords datasets "newgdp" #' @rdname USvoteS #' @title U.S. 2000 Election Data (short) #' @aliases USvoteS #' @description Data from a post-election survey following the year 2000 U.S. #' presidential elections. This is a subset from package `CHAID`. #' #' @format A data frame with 1000 observations on the following 6 variables.: #' \describe{ #' \item{vote3}{candidate voted for Gore or Bush} #' \item{gender}{gender, a factor with levels male and female} #' \item{ager}{age group, an ordered factor with levels 18-24 < 25-34 < 35-44 < 45-54 < 55-64 < 65+} #' \item{empstat}{status of employment, a factor with levels yes, no or retired} #' \item{educr}{status of education, an ordered factor with levels <HS < HS < >HS < College < Post Coll} #' \item{marstat}{status of living situation, a factor with levels married, widowed, divorced or never married} #' #' } #' @source https://r-forge.r-project.org/R/?group_id=343 #' @keywords datasets "USvoteS" #' @rdname chaidUS #' @title U.S. 2000 Election Data (short) #' @aliases chaidUS #' @description Data from a post-election survey following the year 2000 U.S. #' presidential elections. This is a subset from package `CHAID`. #' #' @format A partykit on the following 6 variables.: #' \describe{ #' \item{vote3}{candidate voted for Gore or Bush} #' \item{gender}{gender, a factor with levels male and female} #' \item{ager}{age group, an ordered factor with levels 18-24 < 25-34 < 35-44 < 45-54 < 55-64 < 65+} #' \item{empstat}{status of employment, a factor with levels yes, no or retired} #' \item{educr}{status of education, an ordered factor with levels <HS < HS < >HS < College < Post Coll} #' \item{marstat}{status of living situation, a factor with levels married, widowed, divorced or never married} #' #' } #' @source https://r-forge.r-project.org/R/?group_id=343 #' @keywords datasets "chaidUS"
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/data.R
# defining global variables and functions to appease R CMD Check utils::globalVariables( names = c( ".", ".wt", "perc", "N", "NN", "n", "samplenumb", "correct", "TheMean", "TheSEM", "TheSD", "CIMuliplier", "LowerBound", "UpperBound", "p.value", "term", "outcome", "splitrule", "df", "chisq", "method", "NodeN", "nodeID", "adjustedp", "parent", "ruletext", "split.variable", "rawpvalue", "statistic", "parameter", "support", "logged", "sensible", "astext", "xmin", "xmax", "ymin", "ymax", "pct", ".", "alias", "coef", "coefficients", "deviance", "df.residual", "makeHypothesis", "model.frame", "model.matrix", "model.response", "pchisq", "setNames", "terms", "vcov", "model", "error", "bf" ), package = "CGPfunctions", add = FALSE )
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/global_vars.R
#' @title Justification for titles, subtitles and captions. #' @name justifyme #' @author Chuck Powell #' #' @param x A numeric or character vector. #' @return a numeric value suitable for `ggplot2` `hjust` value. #' #' @keywords internal justifyme <- function(x) { if (tolower(stringr::str_sub(x, 1, 1)) %in% c("l", "c", "r")) { whichletter <- tolower(stringr::str_sub(x, 1, 1)) justification <- dplyr::case_when( whichletter == "l" ~ 0, whichletter == "c" ~ .5, whichletter == "r" ~ 1, TRUE ~ .5 ) } else if (x >= 0 && x <= 1) { justification <- x } else { justification <- 0.5 } # return the changed plot return(justification) } #' Test whether a vector or df column is not of type factor #' @param x an integer #' @keywords internal #' @noRd not_a_factor <- function(x){ !is.factor(x) } #' @title Choose display type for BF formatting. #' @name bf_display #' @author Chuck Powell #' #' @param bf A numeric vector containing one or more BF values. #' @param display_type A string containing which option one of #' "support", "logged", or "sensible". #' @param k A numeric for the number of rounded digits. #' @return a formatted character string. #' bf_display <- function(bf = NULL, display_type = "bf", k = 2) { results <- tibble::enframe(bf, name = NULL, value = "bf") results <- results %>% mutate( support = case_when( bf < .01 ~ " data support is extreme", bf < .03 & bf >= .01 ~ " data support is very strong", bf < .1 & bf >= .03 ~ " data support is strong", bf < 1 / 3 & bf >= .1 ~ " data support is moderate", bf < 1 & bf >= 1 / 3 ~ " data support is anecdotal", bf >= 1 & bf < 3 ~ " data support is anecdotal", bf >= 3 & bf < 10 ~ " data support is moderate", bf >= 10 & bf < 30 ~ " data support is strong", bf >= 30 & bf < 100 ~ " data support is very strong", bf >= 100 ~ " data support is extreme" ) ) %>% mutate(logged = case_when( bf < 1 ~ paste0(" log(BF01)=", round(log(1 / bf), k)), bf >= 1 ~ paste0(" log(BF10)=", round(log(bf), k)) )) %>% mutate(sensible = case_when( bf < 1 ~ paste0(" is ", number_to_word(1 / bf), " to 1"), bf >= 1 ~ paste0(" is ", number_to_word(bf), " to 1") )) %>% mutate(astext = case_when( bf < 1 ~ paste0("=", round((1 / bf), k)), bf >= 1 ~ paste0("=", round(bf, k)) )) if (display_type == "support") { return(pull(results, support)) } else if (display_type == "log") { return(pull(results, logged)) } else if (display_type == "sensible") { return(pull(results, sensible)) } else { return(pull(results, astext)) } return(results) } #### ----- internal function to format p values ----- #### #' Internal function to format p values #' @param pvals a vector of p values #' @keywords internal #' @noRd pvalr <- function(pvals, sig.limit = .001, digits = 3, html = FALSE) { roundr <- function(x, digits = 1) { res <- sprintf(paste0('%.', digits, 'f'), x) zzz <- paste0('0.', paste(rep('0', digits), collapse = '')) res[res == paste0('-', zzz)] <- zzz res } sapply(pvals, function(x, sig.limit) { if (x < sig.limit) if (html) return(sprintf('&lt; %s', format(sig.limit))) else return(sprintf('< %s', format(sig.limit))) if (x > .1) return(roundr(x, digits = 2)) else return(roundr(x, digits = digits)) }, sig.limit = sig.limit) } #' @name number_to_word #' @title Convert a vector of numbers to large-number word representation #' @description Converts a vector of numbers to a character string approximation #' using the "short scale" version of large number names. e.g. 312e6 returns #' as '300 million.' Simultaneously returns a numeric representation of the #' approximation. #' @author Tom Hopper #' @param x A vector of numbers to convert. #' @param nsmall Optional. An integer number of digits to include to the right of the the leading digit #' @return A string representation of the number #' @keywords internal number_to_word <- function(x, nsmall = 0) { # provide the short scale version (used in American English) lookup <- tibble(expon = c(33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, -3, -6, -9, -12), word = c("decillion", "nonillian", "octillian", "septillion", "sextillion", "quintillion", "quadrillion", "trillion", "billion", "million", "thousand", "", "thousandth", "millionth", "billionth", "trillionth")) # Get the exponent and round to the nearest multiple of 3 so # we can look up values in our lookup table and return the number # with the correct digits. x_exp <- exponent(x) x_exp <- ifelse(x_exp != 0, floor(x_exp / 3.0) * 3, 0) # Look up the word for the number x_name <- rep(NA, times = length(x_exp)) for (i in 1:length(x_exp)) { if (is.na(x_exp[i]) | is.infinite(abs(x_exp[i]))) { x_name[i] <- "" } else { x_name[i] <- ifelse(x_exp[i] != 0, lookup$word[lookup$expon == x_exp[i]], "") } } # Convert x to a number with -3 < exponent() < 3 # then combine the number and x_name. # e.g. 200,000,000,000 should return # "200 billion" x_n <- rep(NA, times = length(x_exp)) for (i in 1:length(x_exp)) { if (is.na(x_exp[i])) { x_n[i] <- NA } else { if (is.infinite(x_exp[i])) { x_n[i] <- ifelse(x_exp[i] > 0, x[i], 0) } else { if (abs(x_exp[i]) >= 3) { x_n[i] <- x[i] / 10^x_exp[i] x_n[i] <- round(x_n[i] / 10^exponent(x_n[i]), nsmall) * 10^exponent(x_n[i]) } else { if (is.na(x_exp[i])) { x_n[i] <- NA } else { x_n[i] <- round(x[i] / 10^(exponent(x[i])-1), nsmall) * 10^(exponent(x[i]) - 1) } } } } } # Create word equivalent of approximate number x_name <- paste0(as.character(x_n), ifelse(nchar(x_name > 0), " ", ""), x_name) x_name <- trimws(x_name) x_name <- ifelse(x_name == "NA", NA, x_name) x_n <- x_n * 10 ^ x_exp # Return string representation return(x_name) } ## Extract mantissa and exponent from vector #### #' @name exponent #' @title Exponent of a number in scientific notation #' @description Returns the exponent of a number as it is written in scientific #' notation (powers of 10). #' @references Thanks to Stackoverflow answer by Paul McMurdie \url{https://stackoverflow.com/a/25555105} #' @author Tom Hopper #' @param x (required) numeric. A number. #' @return the exponent of the scientific notation representation of the number \code{x} #' @keywords internal #' exponent <- function(x) { # check missing if (!missing(x)) { if (is.numeric(x)) { expon <- floor(log10(abs(x))) return(expon) } else { if (is.complex(x)) { invisible(NaN) #warning("x may not be a complex number.") stop("x may not be a complex number.") } else { invisible(NaN) stop("x must be numeric.") } } } else { invisible(NaN) stop("The numeric vector x must be supplied. e.g. exponent(x = 5753).") } } #' @title Brown-Forsythe Test for Homogeneity of Variance using median #' @name BrownForsytheTest #' @author J. Fox, Chuck Powell #' #' @param formula A fully crossed anova formula. #' @param data A datafram containing the data. #' @return a table containing the results. #' #' @keywords internal ## moved from Rcmdr 13 July 2004 ## levene.test.default function slightly modified and generalized from Brian Ripley via R-help ## the original generic version was contributed by Derek Ogle ## last modified 2019-02-01 by J. Fox ## simplified and moved into package July 2020 BrownForsytheTest <- function(formula, data) { mf <- model.frame(formula, data) y <- mf[,1] group <- interaction(mf[,2:dim(mf)[2]]) valid <- complete.cases(y, group) meds <- tapply(y[valid], group[valid], median) resp <- abs(y - meds[group]) table <- anova(lm(resp ~ group))[, c(1, 4, 5)] rownames(table)[2] <- " " attr(table, "heading") <- paste("Brown-Forsythe Test for Homogeneity of Variance using median", sep="") table } #' @title Tidy Tables for htest objects #' @name newbroom #' #' @description Produces tidy tibbles of results from htest objects. #' This is a vastly reduced version of the tidy.htest function from #' package broom #' #' @usage newbroom(x) #' @param x An `htest` object, such as those created by [stats::cor.test()], #' [stats::t.test()], [stats::wilcox.test()], [stats::chisq.test()], etc. #' @return An object of class "tibble". #' #' @examples #' #' chit <- chisq.test(xtabs(Freq ~ Sex + Class, data = as.data.frame(Titanic))) #' CGPfunctions:::newbroom(chit) #' @seealso [stats::t.test()], [stats::oneway.test()] #' [stats::wilcox.test()], [stats::chisq.test()] #' @keywords internal newbroom <- function(x) { ret <- x[c("estimate", "statistic", "p.value", "parameter")] # estimate may have multiple values if (length(ret$estimate) > 1) { names(ret$estimate) <- paste0("estimate", seq_along(ret$estimate)) ret <- c(ret$estimate, ret) ret$estimate <- NULL # special case: in a t-test, estimate = estimate1 - estimate2 if (x$method %in% c("Welch Two Sample t-test", " Two Sample t-test")) { ret <- c(estimate = ret$estimate1 - ret$estimate2, ret) } } # parameter may have multiple values as well, such as oneway.test if (length(x$parameter) > 1) { ret$parameter <- NULL if (is.null(names(x$parameter))) { warning("Multiple unnamed parameters in hypothesis test; dropping them") } else { message( "Multiple parameters; naming those columns ", paste(make.names(names(x$parameter)), collapse = ", ") ) # rename num df to num.df and denom df to denom.df np <- names(x$parameter) np <- stringr::str_replace(np, "num df", "num.df") np <- stringr::str_replace(np, "denom df", "den.df") names(x$parameter) <- np ret <- append(ret, x$parameter, after = 1) } } ret <- purrr::compact(ret) if (!is.null(x$conf.int)) { ret <- c(ret, conf.low = x$conf.int[1], conf.high = x$conf.int[2]) } if (!is.null(x$method)) { ret <- c(ret, method = as.character(x$method)) } if (!is.null(x$alternative)) { ret <- c(ret, alternative = as.character(x$alternative)) } as_tibble(ret) }
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/helpers.R
#' Plot a Slopegraph a la Tufte using dplyr and ggplot2 #' #' Creates a "slopegraph" as conceptualized by Edward Tufte. Slopegraphs are minimalist #' and efficient presentations of your data that can simultaneously convey the relative rankings, #' the actual numeric values, and the changes and directionality of the data over time. #' Takes a dataframe as input, with three named columns being used to draw the plot. #' Makes the required adjustments to the ggplot2 parameters and returns the plot. #' #' @param dataframe a dataframe or an object that can be coerced to a dataframe. #' Basic error checking is performed, to include ensuring that the named columns #' exist in the dataframe. See the \code{\link{newcancer}} dataset for an example of #' how the dataframe should be organized. #' @param Times a column inside the dataframe that will be plotted on the x axis. #' Traditionally this is some measure of time. The function accepts a column of class #' ordered, factor or character. NOTE if your variable is currently a "date" class #' you must convert before using the function with \code{as.character(variablename)}. #' @param Measurement a column inside the dataframe that will be plotted on the y axis. #' Traditionally this is some measure such as a percentage. Currently the function #' accepts a column of type integer or numeric. The slopegraph will be most effective #' when the measurements are not too disparate. #' @param Grouping a column inside the dataframe that will be used to group and #' distinguish measurements. #' @param Data.label an optional column inside the dataframe that will be used #' as the label for the data points plotted. Can be complex strings and #' have `NA` values but must be of class `chr`. By default `Measurement` is #' converted to `chr` and used. #' @param Title Optionally the title to be displayed. Title = NULL will remove it #' entirely. Title = "" will provide an empty title but retain the spacing. #' @param SubTitle Optionally the sub-title to be displayed. SubTitle = NULL #' will remove it entirely. SubTitle = "" will provide and empty title but retain #' the spacing. #' @param Caption Optionally the caption to be displayed. Caption = NULL will remove #' it entirely. Caption = "" will provide and empty title but retain the spacing. #' @param XTextSize Optionally the font size for the X axis labels to be displayed. XTextSize = 12 is the default must be a numeric. Note that X & Y axis text are on different scales #' @param YTextSize Optionally the font size for the Y axis labels to be displayed. #' YTextSize = 3 is the default must be a numeric. Note that X & Y axis text are on #' different scales #' @param TitleTextSize Optionally the font size for the Title to be displayed. #' TitleTextSize = 14 is the default must be a numeric. #' @param SubTitleTextSize Optionally the font size for the SubTitle to be displayed. #' SubTitleTextSize = 10 is the default must be a numeric. #' @param CaptionTextSize Optionally the font size for the Caption to be displayed. #' CaptionTextSize = 8 is the default must be a numeric. #' @param TitleJustify Justification of title can be either a character "L", #' "R" or "C" or use the \code{hjust = } notation from \code{ggplot2} with #' a numeric value between `0` (left) and `1` (right). #' @param SubTitleJustify Justification of subtitle can be either a character "L", #' "R" or "C" or use the \code{hjust = } notation from \code{ggplot2} with #' a numeric value between `0` (left) and `1` (right). #' @param CaptionJustify Justification of caption can be either a character "L", #' "R" or "C" or use the \code{hjust = } notation from \code{ggplot2} with #' a numeric value between `0` (left) and `1` (right). #' @param LineThickness Optionally the thickness of the plotted lines that #' connect the data points. LineThickness = 1 is the default must be a numeric. #' @param DataTextSize Optionally the font size of the plotted data points. DataTextSize = 2.5 #' is the default must be a numeric. #' @param DataTextColor Optionally the font color of the plotted data points. `"black"` #' is the default can be either `colors()` or hex value e.g. "#FF00FF". #' @param DataLabelPadding Optionally the amount of space between the plotted #' data point numbers and the label "box". By default very small = 0.05 to #' avoid overlap. Must be a numeric. Too large a value will risk "hiding" #' datapoints. #' @param DataLabelLineSize Optionally how wide a line to plot around the data #' label box. By default = 0 to have no visible border line around the #' label. Must be a numeric. #' @param DataLabelFillColor Optionally the fill color or background of the #' plotted data points. `"white"` is the default can be any of the `colors()` #' or hex value e.g. "#FF00FF". #' @param LineColor Optionally the color of the plotted lines. By default it will use #' the ggplot2 color palette for coloring by \code{Grouping}. The user may override #' with \bold{one} valid color of their choice e.g. "black" (see colors() for choices) #' \bold{OR} #' they may provide a vector of colors such as c("gray", "red", "green", "gray", "blue") #' \bold{OR} a named vector like c("Green" = "gray", "Liberal" = "red", "NDP" = "green", #' "Others" = "gray", "PC" = "blue"). Any input must be character, and the length #' of a vector \bold{should} equal the number of levels in \code{Grouping}. If the #' user does not provide enough colors they will be recycled. #' @param WiderLabels logical, set this value to \code{TRUE} if your "labels" or #' \code{Grouping} variable values tend to be long as they are in the \code{newcancer} #' dataset. This setting will give them more room in the same plot size. #' @param ReverseYAxis logical, set this value to \code{TRUE} if you want #' to reverse the Y scale, especially useful for rankings when you want #1 on #' top. #' @param ReverseXAxis logical, set this value to \code{TRUE} if you want #' to reverse the **factor levels** on the X scale. #' @param RemoveMissing logical, by default set to \code{TRUE} so that if any \code{Measurement} #' is missing \bold{all rows} for that \code{Grouping} are removed. If set to \code{FALSE} then #' the function will try to remove and graph what data it does have. \bold{N.B.} missing values #' for \code{Times} and \code{Grouping} are never permitted and will generate a fatal error with #' a warning. #' @param ThemeChoice character, by default set to \bold{"bw"} the other #' choices are \bold{"ipsum"}, \bold{"econ"}, \bold{"wsj"}, \bold{"gdocs"}, #' and \bold{"tufte"}. #' #' #' @return a plot of type ggplot to the default plot device #' @export #' @import ggplot2 #' @importFrom dplyr filter mutate group_by summarise %>% n case_when #' @importFrom ggrepel geom_text_repel geom_label_repel #' @importFrom forcats fct_rev #' @importFrom methods hasArg #' #' @author Chuck Powell #' @seealso \code{\link{newcancer}} and \code{\link{newgdp}} #' @references Based on: Edward Tufte, Beautiful Evidence (2006), pages 174-176. #' @examples #' # the minimum command to generate a plot #' newggslopegraph(newcancer, Year, Survival, Type) #' #' # adding a title which is always recommended #' newggslopegraph(newcancer, Year, Survival, Type, #' Title = "Estimates of Percent Survival Rates", #' SubTitle = NULL, #' Caption = NULL #' ) #' #' # simple formatting changes #' newggslopegraph(newcancer, Year, Survival, Type, #' Title = "Estimates of Percent Survival Rates", #' LineColor = "darkgray", #' LineThickness = .5, #' SubTitle = NULL, #' Caption = NULL #' ) #' #' # complex formatting with recycling and wider labels see vignette for more examples #' newggslopegraph(newcancer, Year, Survival, Type, #' Title = "Estimates of Percent Survival Rates", #' SubTitle = "Based on: Edward Tufte, Beautiful Evidence, 174, 176.", #' Caption = "https://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0003nk", #' LineColor = c("black", "red", "grey"), #' LineThickness = .5, #' WiderLabels = TRUE #' ) #' #' # not a great example but demonstrating functionality #' newgdp$rGDP <- round(newgdp$GDP) #' #' newggslopegraph(newgdp, #' Year, #' rGDP, #' Country, #' LineColor = c(rep("grey", 3), "red", rep("grey", 11)), #' DataTextSize = 3, #' DataLabelFillColor = "gray", #' DataLabelPadding = .2, #' DataLabelLineSize = .5 #' ) newggslopegraph <- function(dataframe, Times, Measurement, Grouping, Data.label = NULL, Title = "No title given", SubTitle = "No subtitle given", Caption = "No caption given", XTextSize = 12, YTextSize = 3, TitleTextSize = 14, SubTitleTextSize = 10, CaptionTextSize = 8, TitleJustify = "left", SubTitleJustify = "left", CaptionJustify = "right", LineThickness = 1, LineColor = "ByGroup", DataTextSize = 2.5, DataTextColor = "black", DataLabelPadding = 0.05, DataLabelLineSize = 0, DataLabelFillColor = "white", WiderLabels = FALSE, ReverseYAxis = FALSE, ReverseXAxis = FALSE, RemoveMissing = TRUE, ThemeChoice = "bw") { # ---------------- theme selection ---------------------------- if (ThemeChoice == "bw") { theme_set(theme_bw()) } else if (ThemeChoice == "ipsum") { theme_set(hrbrthemes::theme_ipsum_rc()) } else if (ThemeChoice == "econ") { theme_set(ggthemes::theme_economist()) ## background = "#d5e4eb" if (DataLabelFillColor == "white") { DataLabelFillColor <- "#d5e4eb" } } else if (ThemeChoice == "wsj") { theme_set(ggthemes::theme_wsj()) ## background = "#f8f2e4" if (DataLabelFillColor == "white") { DataLabelFillColor <- "#f8f2e4" } TitleTextSize <- TitleTextSize - 1 SubTitleTextSize <- SubTitleTextSize + 1 } else if (ThemeChoice == "gdocs") { theme_set(ggthemes::theme_gdocs()) } else if (ThemeChoice == "tufte") { theme_set(ggthemes::theme_tufte()) } else { theme_set(theme_bw()) } # ---------------- ggplot setup work ---------------------------- # Since ggplot2 objects are just regular R objects, put them in a list MySpecial <- list( # Format tweaks scale_x_discrete(position = "top"), # move the x axis labels up top theme(legend.position = "none"), # Remove the legend theme(panel.border = element_blank()), # Remove the panel border theme(axis.title.y = element_blank()), # Remove just about everything from the y axis theme(axis.text.y = element_blank()), theme(panel.grid.major.y = element_blank()), theme(panel.grid.minor.y = element_blank()), theme(axis.title.x = element_blank()), # Remove a few things from the x axis theme(panel.grid.major.x = element_blank()), theme(axis.text.x.top = element_text(size = XTextSize, face = "bold")), # and increase font size theme(axis.ticks = element_blank()), # Remove x & y tick marks theme(plot.title = element_text( size = TitleTextSize, face = "bold", hjust = justifyme(TitleJustify) )), theme(plot.subtitle = element_text( size = SubTitleTextSize, hjust = justifyme(SubTitleJustify) )), theme(plot.caption = element_text( size = CaptionTextSize, hjust = justifyme(CaptionJustify) )) ) # ---------------- input checking ---------------------------- # error checking and setup if (length(match.call()) <= 4) { stop("Not enough arguments passed requires a dataframe, plus at least three variables") } argList <- as.list(match.call()[-1]) if (!hasArg(dataframe)) { stop("You didn't specify a dataframe to use", call. = FALSE) } NTimes <- deparse(substitute(Times)) # name of Times variable NMeasurement <- deparse(substitute(Measurement)) # name of Measurement variable NGrouping <- deparse(substitute(Grouping)) # name of Grouping variable if(is.null(argList$Data.label)) { NData.label <- deparse(substitute(Measurement)) Data.label <- argList$Measurement } else { NData.label <- deparse(substitute(Data.label)) # Data.label <- argList$Data.label } Ndataframe <- argList$dataframe # name of dataframe if (!is(dataframe, "data.frame")) { stop(paste0("'", Ndataframe, "' does not appear to be a data frame")) } if (!NTimes %in% names(dataframe)) { stop(paste0("'", NTimes, "' is not the name of a variable in the dataframe"), call. = FALSE) } if (anyNA(dataframe[[NTimes]])) { stop(paste0("'", NTimes, "' can not have missing data please remove those rows!"), call. = FALSE) } if (!NMeasurement %in% names(dataframe)) { stop(paste0("'", NMeasurement, "' is not the name of a variable in the dataframe"), call. = FALSE) } if (!NGrouping %in% names(dataframe)) { stop(paste0("'", NGrouping, "' is not the name of a variable in the dataframe"), call. = FALSE) } if (!NData.label %in% names(dataframe)) { stop(paste0("'", NData.label, "' is not the name of a variable in the dataframe"), call. = FALSE) } if (anyNA(dataframe[[NGrouping]])) { stop(paste0("'", NGrouping, "' can not have missing data please remove those rows!"), call. = FALSE) } if (!class(dataframe[[NMeasurement]]) %in% c("integer", "numeric")) { stop(paste0("Sorry I need the measured variable '", NMeasurement, "' to be a number"), call. = FALSE) } if (!"ordered" %in% class(dataframe[[NTimes]])) { # keep checking if (!"character" %in% class(dataframe[[NTimes]])) { # keep checking if ("factor" %in% class(dataframe[[NTimes]])) { # impose order message(paste0("\nConverting '", NTimes, "' to an ordered factor\n")) dataframe[[NTimes]] <- factor(dataframe[[NTimes]], ordered = TRUE) } else { stop(paste0("Sorry I need the variable '", NTimes, "' to be of class character, factor or ordered"), call. = FALSE) } } } Times <- enquo(Times) Measurement <- enquo(Measurement) Grouping <- enquo(Grouping) Data.label <- enquo(Data.label) # ---------------- handle some special options ---------------------------- if (ReverseXAxis) { dataframe[[NTimes]] <- forcats::fct_rev(dataframe[[NTimes]]) } NumbOfLevels <- nlevels(factor(dataframe[[NTimes]])) if (WiderLabels) { MySpecial <- c(MySpecial, expand_limits(x = c(0, NumbOfLevels + 1))) } if (ReverseYAxis) { MySpecial <- c(MySpecial, scale_y_reverse()) } if (length(LineColor) > 1) { if (length(LineColor) < length(unique(dataframe[[NGrouping]]))) { message(paste0("\nYou gave me ", length(LineColor), " colors I'm recycling colors because you have ", length(unique(dataframe[[NGrouping]])), " ", NGrouping, "s\n")) LineColor <- rep(LineColor, length.out = length(unique(dataframe[[NGrouping]]))) } LineGeom <- list(geom_line(aes_(color = Grouping), size = LineThickness), scale_color_manual(values = LineColor)) } else { if (LineColor == "ByGroup") { LineGeom <- list(geom_line(aes_(color = Grouping, alpha = 1), size = LineThickness)) } else { LineGeom <- list(geom_line(aes_(), size = LineThickness, color = LineColor)) } } # logic to sort out missing values if any if (anyNA(dataframe[[NMeasurement]])) { # are there any missing if (RemoveMissing) { # which way should we handle them dataframe <- dataframe %>% group_by(!!Grouping) %>% filter(!anyNA(!!Measurement)) %>% droplevels() } else { dataframe <- dataframe %>% filter(!is.na(!!Measurement)) } } # ---------------- main ggplot routine ---------------------------- dataframe %>% ggplot(aes_(group = Grouping, y = Measurement, x = Times)) + LineGeom + # left side y axis labels geom_text_repel( data = . %>% filter(!!Times == min(!!Times)), aes_(label = Grouping), hjust = "left", box.padding = 0.10, point.padding = 0.10, segment.color = "gray", segment.alpha = 0.6, fontface = "bold", size = YTextSize, nudge_x = -1.95, direction = "y", force = .5, max.iter = 3000 ) + # right side y axis labels geom_text_repel( data = . %>% filter(!!Times == max(!!Times)), aes_(label = Grouping), hjust = "right", box.padding = 0.10, point.padding = 0.10, segment.color = "gray", segment.alpha = 0.6, fontface = "bold", size = YTextSize, nudge_x = 1.95, direction = "y", force = .5, max.iter = 3000 ) + # data point labels geom_label(aes_string(label = NData.label), size = DataTextSize, # label.padding controls fill padding label.padding = unit(DataLabelPadding, "lines"), # label.size controls width of line around label box # 0 = no box line label.size = DataLabelLineSize, # color = text color of label color = DataTextColor, # fill background color for data label fill = DataLabelFillColor ) + MySpecial + labs( title = Title, subtitle = SubTitle, caption = Caption ) # implicitly return plot object } # end of function
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/newggslopegraph.R
#' SeeDist -- See The Distribution #' #' This function takes a vector of numeric data and returns one or more ggplot2 #' plots that help you visualize the data. Meant to be a useful wrapper for #' exploring univariate data. Has a plethora of options including type of #' visualization (histogram, boxplot, density, violin) as well as commonly #' desired overplots like mean and median points, z and t curves etc.. Common #' descriptive statistics are provided as a subtitle if desired and sent to the #' console as well. #' #' @param x the data to be visualized. Must be numeric. #' @param title Optionally replace the default title displayed. title = NULL #' will remove it entirely. title = "" will provide an empty title but #' retain the spacing. A sensible default is provided otherwise. #' @param subtitle Optionally replace the default subtitle displayed. subtitle = NULL #' will remove it entirely. subtitle = "" will provide an empty subtitle but #' retain the spacing. A sensible default is provided otherwise. #' @param whatplots what type of plots? The default is whatplots = c("d", "b", #' "h", "v") for a density, a boxplot, a histogram, and a violin plot #' @param numbins the number of bins to use for any plots that bin. If nothing is #' specified the function will calculate a rational number using Freedman-Diaconis #' via the \code{nclass.FD} function #' @param var_explain additional contextual information about the variable as a string #' such as "Miles Per Gallon" which is appended to the default title information. #' @param data.fill.color Character string that specifies fill color for the main data #' area (Default: `deepskyblue`). #' @param mean.line.color,median.line.color,mode.line.color Character string that #' specifies line color (Default: `darkgreen`, `yellow`, `orange`). #' @param mean.line.type,median.line.type,mode.line.type Character string that #' specifies line color (Default: `longdash`, `dashed`, `dashed`). #' @param mean.line.size,median.line.size,mode.line.size Numeric that #' specifies line size (Default: `1.5`, `1.5`, `1`). You can set to `0` to make #' any of the lines "disappear". #' @param mean.point.shape,median.point.shape Integer in 0 - 25 #' specifies shape of mean or median point mark on the violin plot #' (Default: `21`, `23`). #' @param mean.point.size,median.point.size Integer #' specifies size of mean or median point mark on the violin plot #' (Default: `4`). You can set to `0` to make any of the points "disappear". #' @param zcurve.color,tcurve.color Character string that #' specifies line color (Default: `red`, `black`). #' @param zcurve.type,tcurve.type Character string that #' specifies line color (Default: `twodash`, `dotted`). #' @param zcurve.size,tcurve.size Numeric that #' specifies line size (Default: `1`). You can set to `0` to make #' any of the lines "disappear". #' @param xlab Custom text for the `x` axis label (Default: `NULL`, which #' will cause the `x` axis label to be the `x` variable). #' @param k Number of digits after decimal point (should be an integer) #' (Default: k = 2) for statistical results. #' @param add_jitter Logical (Default: `TRUE`) controls whether jittered data #' ponts are added to violin plot. #' @param add_rug Logical (Default: `TRUE`) controls whether "rug" data #' points are added to density plot and histogram. #' @param xlim_left,xlim_right Logical. For density plots can be used to #' override the default which is 3 std deviations left and right of #' the mean of x. Useful for theoretical reasons like horsepower < 0 #' or when `ggplot2` warns you that it has removed rows containing #' non-finite values (stat_density). #' @param ggtheme A function, ggplot2 theme name. Default value is ggplot2::theme_bw(). #' Any of the ggplot2 themes, or themes from extension packages are allowed (e.g., #' hrbrthemes::theme_ipsum(), etc.). #' #' @return from 1 to 4 plots depending on what the user specifies as well as an #' extensive summary courtesy `DescTools::Desc` printed to the console #' #' @export #' @import ggplot2 #' @importFrom grDevices nclass.FD #' @importFrom stats dnorm dt median sd #' @importFrom DescTools Desc #' #' @section Warning: #' If the data has more than 3 modal values only the first three of them are plotted. #' The rest are ignored and the user is warned on the console. #' #' Missing values are removed with a warning to the user #' #' @seealso \code{\link[grDevices]{nclass}} #' #' @examples #' SeeDist(rnorm(100, mean = 100, sd = 20), numbins = 15, var_explain = "A Random Sample") #' SeeDist(mtcars$hp, var_explain = "Horsepower", whatplots = c("d", "b")) #' SeeDist(iris$Sepal.Length, var_explain = "Sepal Length", whatplots = "d") #' @author Chuck Powell #' SeeDist <- function(x, title = "Default", subtitle = "Default", numbins = 0, xlab = NULL, var_explain = NULL, data.fill.color = "deepskyblue", mean.line.color = "darkgreen", median.line.color = "yellow", mode.line.color = "orange", mean.line.type = "longdash", median.line.type = "dashed", mode.line.type = "dashed", mean.line.size = 1.5, median.line.size = 1.5, mean.point.shape = 21, median.point.shape = 23, mean.point.size = 4, median.point.size = 4, zcurve.color = "red", zcurve.type = "twodash", zcurve.size = 1, tcurve.color = "black", tcurve.type = "dotted", tcurve.size = 1, mode.line.size = 1, whatplots = c("d", "b", "h", "v"), k = 2, add_jitter = TRUE, add_rug = TRUE, xlim_left = NULL, xlim_right = NULL, ggtheme = ggplot2::theme_bw() ) { #### Basic setup #### # set default theme ggplot2::theme_set(ggtheme) if (!is.numeric(x)) { stop("Sorry the data must be numeric") } x_name <- deparse(substitute(x)) # get the variable name # if not specified, use the variable name for x axis if (is.null(xlab)) { xlab <- x_name } # figure you what binwidth we'll use binnumber <- nclass.FD(x) # default binnumber <- ifelse(numbins == 0, binnumber, numbins) #### Get descriptives #### desc.output <- DescTools::Desc(x, plotit = FALSE, main = xlab, digits = k) if (sum(is.na(x)) != 0) { missing_count <- sum(is.na(x)) warning(paste("Removing", missing_count, "missing values"), call. = FALSE) x <- x[!is.na(x)] } x_mean <- desc.output[[1]]$mean x_sd <- desc.output[[1]]$sd x_median <- desc.output[[1]]$quant['median'] x_mode <- CGPfunctions::Mode(x) x_skew <- desc.output[[1]]$skew x_kurtosis <- desc.output[[1]]$kurt if (length(x_mode) >= 4) { warning(paste("There are", length(x_mode)), " modal values displaying just the first 3", call. = FALSE) x_mode <- x_mode[c(1, 2, 3)] } #### Custom geoms #### my_jitter_geom <- list() if (add_jitter) { my_jitter_geom <- list( geom_jitter(aes(x = "", y = x), width = 0.05, height = 0, alpha = .5) ) } my_rug_geom <- list() if (add_rug) { my_rug_geom <- list( geom_rug(aes(y = 0), sides = "b") ) } if (is.null(xlim_left)) { xlim_left <- -3 * x_sd + x_mean } if (is.null(xlim_right)) { xlim_right <- +3 * x_sd + x_mean } #### Title, subtitle and caption #### if (!is.null(title) && title == "Default") { my_title <- paste0("Distribution of the variable ", x_name, " ", var_explain ) } else { my_title <- title } make_subtitle <- function(x, mean_x, sd_x, median_x, Skew_x, Kurtosis_x, k = k) { ret_subtitle <- bquote("N =" ~ .(length(x)) * "," ~ bar(X) ~ "=" ~ .(round(mean_x, k)) * ", SD =" ~ .(round(sd_x, k)) * ", Median =" ~ .(round(median_x, k)) * ", Skewness =" ~ .(round(Skew_x, k)) * ", Kurtosis =" ~ .(round(Kurtosis_x, k) ) ) } if (!is.null(subtitle) && subtitle == "Default") { my_subtitle <- make_subtitle(x, x_mean, x_sd, x_median, x_skew, x_kurtosis, k) } else { my_subtitle <- subtitle } mycaption <- bquote(bar(X) ~ "is" ~ .(mean.line.color) ~ ", Median is" ~ .(median.line.color) ~ ", Mode is" ~ .(mode.line.color) ~ ", z curve is" ~ .(zcurve.color) ~ ", t curve is" ~ .(tcurve.color) ) #### custom function to plot t curve #### custom_t_function <- function(x, mu, nu, df, ncp) { dt((x - mu)/nu, df, ncp) / nu } #### build the density plot #### if ("d" %in% tolower(whatplots)) { p <- ggplot(data.frame(x)) + aes(x) + geom_density(fill = data.fill.color, ) + stat_function(fun = dnorm, color = zcurve.color, linetype = zcurve.type, size = zcurve.size, args = list(mean = x_mean, sd = x_sd) ) + stat_function(fun = custom_t_function, color = tcurve.color, linetype = tcurve.type, size = tcurve.size, args = list(mu = x_mean, nu = x_sd, df = length(x) - 1, ncp = 0) ) + geom_vline(xintercept = x_mean, colour = mean.line.color, linetype = mean.line.type, size = mean.line.size) + geom_vline(xintercept = x_median, colour = median.line.color, linetype = median.line.type, size = median.line.size) + geom_vline(xintercept = x_mode, colour = mode.line.color, linetype = mode.line.type, size = mode.line.size) + my_rug_geom + labs( title = my_title, subtitle = my_subtitle, x = xlab, caption = mycaption ) + xlim(xlim_left, xlim_right) + theme( axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank() ) print(p) } #### build the boxplot #### if ("b" %in% tolower(whatplots)) { pp <- ggplot(data.frame(x)) + aes(x) + labs( title = my_title, subtitle = my_subtitle, y = xlab, caption = mycaption ) + stat_boxplot(aes(x = "", y = x), geom = "errorbar", width = 0.2) + geom_boxplot(aes(x = "", y = x), fill = data.fill.color, outlier.color = data.fill.color) + coord_flip() + geom_point(aes(x = "", y = x_mean), shape = mean.point.shape, size = mean.point.size, fill = mean.line.color) + theme( axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), panel.grid.major.y = element_blank() ) print(pp) } #### build the histogram plot #### if ("h" %in% tolower(whatplots)) { ppp <- ggplot(data.frame(x)) + aes(x) + labs( title = my_title, subtitle = my_subtitle, x = xlab, caption = mycaption ) + geom_histogram(bins = binnumber, color = "black", fill = data.fill.color) + my_rug_geom + geom_vline(xintercept = x_mean, colour = mean.line.color, linetype = mean.line.type, size = mean.line.size) + geom_vline(xintercept = x_median, colour = median.line.color, linetype = median.line.type, size = median.line.size) + geom_vline(xintercept = x_mode, colour = mode.line.color, linetype = mode.line.type, size = mode.line.size) print(ppp) } #### build the violin plot #### if ("v" %in% tolower(whatplots)) { pppp <- ggplot(data.frame(x)) + aes(x) + labs( title = my_title, subtitle = my_subtitle, y = xlab, caption = mycaption ) + geom_violin(aes(x = "", y = x), fill = data.fill.color) + my_jitter_geom + coord_flip() + geom_point(aes(x = "", y = x_mean), shape = mean.point.shape, size = mean.point.size, fill = mean.line.color) + geom_point(aes(x = "", y = x_median), shape = median.point.shape, size = median.point.size, fill = median.line.color) + theme( axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.line.y = element_blank(), panel.grid.major.y = element_blank() ) print(pppp) } #### return output to console #### return(desc.output) } # end function
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/R/seedist.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----eval = FALSE------------------------------------------------------------- # # Install from CRAN # install.packages("CGPfunctions") # # # Or the development version from GitHub # # install.packages("devtools") # devtools::install_github("ibecav/CGPfunctions") ## ----LoadLibrary, warning = FALSE--------------------------------------------- library(CGPfunctions) ## ----Plot2WayANOVA, echo=TRUE, message=TRUE, warning=FALSE, fig.width=7, fig.height=4---- Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars) ## ----Plot2WayANOVA2, echo=TRUE, fig.height=4, fig.width=7, message=FALSE, warning=FALSE---- Plot2WayANOVA(formula = mpg ~ cyl * am, dataframe = mtcars, confidence = .99, title = "MPG by cylinders and type transmission", xlab = "Cylinders", ylab = "Miles per gallon", mean.label = TRUE, mean.shape = 22, posthoc.method = "lsd", errorbar.display = "SEM" ) ## ----Plot2WayANOVA3, echo=TRUE, fig.height=4, fig.width=7, message=FALSE, warning=FALSE---- # Create a new dataset library(dplyr) library(ggplot2) library(stringi) newmpg <- mpg %>% filter(cyl != 5) %>% mutate(am = stringi::stri_extract(trans, regex = "auto|manual")) Plot2WayANOVA(formula = hwy ~ am * cyl, dataframe = newmpg, ylab = "Highway mileage", xlab = "Transmission type", plottype = "line", offset.style = "wide", overlay.type = "box", mean.label = TRUE, mean.shape = 20, mean.size = 3, mean.label.size = 3, show.dots = TRUE, errorbar.display = "SD", ggtheme = ggplot2::theme_minimal(), ggplot.component = theme(axis.text.x = element_text(size=14, color="darkblue")) )
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-Plot2WayANOVA.R
--- title: "Using Plot2WayAnova" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using Plot2WayAnova} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## Background The CGPfunctions package includes functions that I find useful for teaching statistics especially to novices (as well as an opportunity to sharpen my own R skills). I only write functions when I have a real need -- no theory -- just help for actually practicing the art. They typically are not "new" methods but rather wrappers around either base R or other packages and are very task focused. This vignette covers one function from the package that tries to help users (especially students) do one thing well by pulling together pieces from a variety of places in `R`. `Plot2WayANOVA`, which as the name implies conducts a 2 way ANOVA and plots the results. I always try and find the right balance between keeping the number of dependencies to a minimum and not reinventing the wheel and writing functions that others have done for me. The function makes use of the following non base r packages. - `ggplot2` as the work horse for all the actual plotting - `car` for it's ability to compute Type II sums of squares, we'll address why that's important in more detail later in the scenario. We'll also make use of it's `leveneTest`. - `sjstats` which takes out ANOVA table and gives us other important information such as the effect sizes ($\eta^2$ and $\omega^2$ ) through use of its `anova_stats` function. Prior to this version I had been using my own local function but this runs rings around what I could do. - `broomExtra::glance` will also help us grab very important results like $R^2$ and display them - `DescTool::PostHocTest` for accomplishing post hoc tests ## Vignette Info The ANOVA (Analysis of Variance) family of statistical techniques allow us to compare mean differences of one outcome (dependent) variable across two or more groups (levels) of one or more independent variables (factor). It is also true that ANOVA is a special case of the GLM or regression models so as the number of levels increase it might make more sense to try one of those approaches. The 2 Way ANOVA allows for comparisons of mean differences across 2 independent variables `factors` with a varying numbers of `levels` in each `factor`. If you prefer a more regression based approach with a very similar plotted result I highly recommend the `interactions` package which I was unaware of until just recently. It is [available through CRAN](https://CRAN.R-project.org/package=interactions). The `Plot2WayANOVA` function conducts a classic analysis of variance (ANOVA) in a sane and defensible, albeit opinionated, manner, not necessarily the only one. It's real strength (*I hope*) lies in the fact that it is pulled together in one function and more importantly allows you to visualize the results concurrently with no additional work. ## Scenario and data Imagine that you are interested in understanding whether a car's fuel efficiency (mpg) varies based upon the type of transmission (automatic or manual) and the number of cylinders the engine has. Let's imagine that the `mtcars` data set is actually a random sample of 32 cars from different manufacturers and use the mean `mpg` grouped by `am` and `cyl` to help inform our thinking. While we expect variation across our sample we're interested in whether the differences between the means by grouping of transmission type and cylinders is significantly different than what we would expect in random variation across the data. In simplistic terms we want to know whether `am` matters, `cyl` matters or if it depends on the interaction of the two. It's this interaction term that typically confuses novices or is difficult to "see". That's where a good interaction graph can hopefully play a key role, and that's what the `Plot2WayANOVA` focuses on. There's no lack or tools or capabilities in base R or in the many packages to do this task. What this function tries to do is pull together the disparate pieces with a set of sane defaults and a simple interface to work with it. At its simplest you would require the library and then enter this command: `Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars)` which lays our question out in R's vernacular with a formula and a dataframe. Optionally we can specify a different confidence level and choose a line or a bar graph. Over time the function has gained a plethora of formatting options. "Under the hood", however there's a lot of nice features at work. 1. Some basic error checking to ensure a valid formula and dataframe. The function accepts only a fully crossed formula to check for an interaction term 1. It ensures the dependent (outcome) variable is numeric and that the two independent (predictor) variables already are or can be coerced to factors – the user is warned on the console if there are problems. 1. A check is conducted to see if any of the variables of interest have missing cases – the user is warned on the console if there are problems. 1. Balance is checked, that is whether the number of observations per cell when we cross `am` and `cyl` is equal. There's some debate as to how much imbalance is permissible. But you'll be given fair warning if there is any. 1. In addition to the classic ANOVA table information available in `aov` or `Anova` you'll be presented with information about effect sizes like eta squared $\eta^2$. They're calculated and appended as additional columns. If you're unfamiliar with them and want to know more especially where the numbers come from I recommend a good introductory stats text. I recommend *Learning Statistics with R* [LSR](https://learningstatisticswithr.com/) see Table 14-1 on page 432. 1. A summarized table of means, standard deviations, standard errors of the means, confidence intervals, and group sizes for each of the crossed combinations in our example that's 6 groupings 3 levels of cylinder and 2 levels of automatic or manual. 1. Some measures of overall fit including $R^2$ 1. If any of the effect terms (main or interaction) are significant you'll be presented with a post-hoc comparison of the means. By default a Scheffe test is run but the user can choose from several supported options. 1. The Homogeneity of Variance assumption is tested with Brown-Forsythe 1. The normality assumption is tested with Shapiro-Wilk ## Installation ```{r eval = FALSE} # Install from CRAN install.packages("CGPfunctions") # Or the development version from GitHub # install.packages("devtools") devtools::install_github("ibecav/CGPfunctions") ``` then load the library. ```{r LoadLibrary, warning = FALSE} library(CGPfunctions) ``` ## Example of using the function The only two required parameters are a formula and a dataframe (like) object. If we run the function in its simplest form here's what we get. ```{r Plot2WayANOVA, echo=TRUE, message=TRUE, warning=FALSE, fig.width=7, fig.height=4} Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars) ``` In the console you'll receive a series of messages chronicling your progress and any diagnostic information. In this case `am` and `cyl` are being coerced to factors and you're being prompted to make sure that's what is intended. Next you receive a warning because you have a very unbalanced design. There are only two 8 cylinder cars with a manual transmission and twelve 8 cylinder cars with automatics. Whereas there are eight 4 cylinders with manual and only three that are automatics. Imbalance in our design worries us for two reasons. One is that it causes a lack of statistical power and creates some math challenges in deciding how to divide up the sums of the squared differences. This data set causes the more troublesome worry. Are the number of cylinders and manual versus automatic related systematically which would call our whole design into question. Make sure you can answer questions about which is at work here, or make sure you have a balanced design. A table follows that is intended to summarize the findings. We'll discuss it more later when we examine the plot. The overall measures table can be very handy for comparing numerous models. For example how does the AIC number change if we were to eliminate `am` ? The table of group means is useful for looking at summary by group. Want the best gas mileage? Buy a 4 cylinder manual car. In our simple example the only statistically significant effect is for the main effect of number of cylinders. Accordingly the Scheffe test is run against the three types of cars with 4, 6, or 8 cylinders and we can see that with a difference of 7.3 mpg eight and four cylinder cars are statistically significant even as we control for the multiple simultaneous comparisons. The next step is to test homogeneity of variance also known as (homoscedasticity). Since the math in our ANOVA rely on the assumption that the variance for the different groupings of cars is more or less equal, we need to check that assumption. We'll use the Brown-Forsythe test. When you run the `leveneTest` in R the default is actually a Brown-Forsythe, to get a true Levene you must specify `center = mean`. Brown-Forsythe is actually more robust since it tests differences from the median. Not surprisingly when we consult out table of group results we have some reason for concern sine the standard deviations vary widely. Finally, let’s address the assumption that our errors or residuals are normally distributed. We’re looking for evidence that our residuals are skewed or tailed or otherwise misshapen in a way that would influence our results. Surprisingly, there is actually quite a bit of controversy on this point since on the one hand we have strong reason to believe that our sample will be imperfect and that our population will not necessarily be “perfectly normal” either. Some argue that some simple plotting is all that is necessary looking for an unspecifiable amount of non normality that will trigger a search for the source. Other prefer a more formal approach using one or more statistical tests. `Plot2WayANOVA` runs the most common test of the normality assumption (there are many) the Shapiro-Wilk test The statistics look good, no strong evidence in the data we have. The default settings for the resultant plot are deliberately minimalistic, allowing you to focus visually on the pattern of means and the connecting lines. If you're already used to looking at this sort of plot it is immediately apparent from the separation between the lines that the number of cylinders is having a significant impact on mileage. Automatic versus manual transmission seems to have less impact (judged by the relative lack of slope except for 4 cylinder models) and there does seem to be at least the start of an interaction between the two. (bear in mind this is a small data set and we are very unbalanced). One other easy tip is warranted. Order matters and sometimes it is helpful to run the command simply reversing the order of the independent variables to help you better "see" the results, e.g. `Plot2WayANOVA(formula = mpg ~ cyl * am, dataframe = mtcars)` **Note that if you want to "save" all these tables of data and information all you need to do is store the results in an object as in `MyResults <- Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars)` then `MyResults` can be accessed as a list.** ### Some common tweaks Let's make some changes that are likely to be quite common: 1. Change the order of the factors 1. Change to p < .01 or 99% CI 1. Add title and axis labels 1. Add a label with the actual group mean values 1. **New** display the standard error of the mean (SEM) instead of confidence intervals 1. Change the plotted shape for the group mean to a square not a diamond 1. Change our post hoc test method to something less conservative than Scheffe ```{r Plot2WayANOVA2, echo=TRUE, fig.height=4, fig.width=7, message=FALSE, warning=FALSE} Plot2WayANOVA(formula = mpg ~ cyl * am, dataframe = mtcars, confidence = .99, title = "MPG by cylinders and type transmission", xlab = "Cylinders", ylab = "Miles per gallon", mean.label = TRUE, mean.shape = 22, posthoc.method = "lsd", errorbar.display = "SEM" ) ``` **Please don't fail to notice how liberal Fisher's LSD is compared to Scheffe especially given we've demanded more confidence ** ### Less common more custom tweaks Although the defaults are minimalistic to allow you to focus on the interaction pattern the function also has any number of optional ways of increasing complexity and showing more information. Let's make some custom changes that are more uncommon: 1. Display standard deviation errorbars 1. Show individual data points 1. Superimpose a boxplot 1. **New** use an entirely different theme (minimal) 1. **New** custom text for the factor labels (bigger and blue) ```{r Plot2WayANOVA3, echo=TRUE, fig.height=4, fig.width=7, message=FALSE, warning=FALSE} # Create a new dataset library(dplyr) library(ggplot2) library(stringi) newmpg <- mpg %>% filter(cyl != 5) %>% mutate(am = stringi::stri_extract(trans, regex = "auto|manual")) Plot2WayANOVA(formula = hwy ~ am * cyl, dataframe = newmpg, ylab = "Highway mileage", xlab = "Transmission type", plottype = "line", offset.style = "wide", overlay.type = "box", mean.label = TRUE, mean.shape = 20, mean.size = 3, mean.label.size = 3, show.dots = TRUE, errorbar.display = "SD", ggtheme = ggplot2::theme_minimal(), ggplot.component = theme(axis.text.x = element_text(size=14, color="darkblue")) ) ``` ## Credits Many thanks to Danielle Navarro and the book * [Learning Statistics with R](https://learningstatisticswithr.com/).* ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-Plot2WayANOVA.Rmd
## ----setup, echo = FALSE, warning=FALSE, message=FALSE------------------------ knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(CGPfunctions) ## ----LoadLibrary-------------------------------------------------------------- library(productplots) str(happy) ## ----vignette1, fig.width=6.0, fig.height=2.5--------------------------------- # who's happier by gender PlotXTabs(happy,happy,sex) # same thing using column numbers and a stacked bar PlotXTabs(happy,2,5,"stack") # happiness by a variety of possible factors as a percent PlotXTabs(happy, 2, c(5:9), plottype = "percent") # turn the numbers around and change them up basically just showing all # the permutations PlotXTabs(happy, c(2,5), 9, plottype = "side") PlotXTabs(happy, c(2,5), c(6:9), plottype = "percent") PlotXTabs(happy, happy, c(6,7,9), plottype = "percent") PlotXTabs(happy, c(6,7,9), happy, plottype = "percent")
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-PlotXTabs.R
--- title: "Using PlotXTabs" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using PlotXTabs} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, echo = FALSE, warning=FALSE, message=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(CGPfunctions) ``` This function is designed to automate and make efficient a relatively common task in some branches of science. The task of cross tabulating and displaying certain types of variables. It makes use of `dplyr` and `ggplot2` to achieve those ends. Imagine that you want to take two of the `mtcars` variables, for example `am` and `cyl`, and conduct a cross tabulation and then plot it. Since it's the sort of thing I'm likely to do often seemed like a good candidate to write a function for. Then I decided that I might very well want the function to allow me to input more than two variables at a time. It would be very tedious to execute the command 25 times if I had 5 dependent variables and 5 independent variables and needed to fully cross them. It provides visually appealing and sensibly labelled charts quickly and efficiently. It does some basic error checking and allows the user some choice as to exact style without having to know any underlying syntax or semantics. ## Possible cases The function is designed to handle four possible scenarios. Take the user's input and parse it into one of four known possibilities and then take appropriate action. The possibilities are: 1. If both are `bare` variables and found in the dataframe immediately print the plot 2. At least one of the variables is `bare` and found in the dataframe (variable x) and the other is one or more column numbers (variable y) 3. At least one of the variables is `bare` and found in the dataframe (variable y) and the other is one or more column numbers (variable x) 4. Both the variables were passed to us as numbers. Could be one or more numbers for either variable. ## Example scenario ... What makes us happy? The documentation examples use the `mtcars` built-in dataset. It's handy, convenient, and it's installed by default. To actually show the function in action, however, I'm going to use a different dataset. Something that should allow you to better see the value of making plots of the crosstabs rather than simple tables. It also has the happy property of being much much larger than `mtcars` so we can see if there are lags in performance due to the number of rows. Rather than provide my own or make anyone work too hard I selected that `happy` dataset that comes bundled with several `R` packages including `productplots` and `GGally`. From the description: > The data is a small sample of variables related to happiness from the general social survey (GSS). The GSS is a yearly cross-sectional survey of Americans, run from 1976. We combine data for 25 years to yield 51,020 observations, and of the over 5,000 variables, we select nine related to happiness. We'll load the library and take a quick look at the structure of the data. ```{r LoadLibrary} library(productplots) str(happy) ``` We'll be focusing on the non numeric variables. I certainly can't claim to do a detailed analysis here but at least the questions will be fun I hope... ```{r vignette1, fig.width=6.0, fig.height=2.5} # who's happier by gender PlotXTabs(happy,happy,sex) # same thing using column numbers and a stacked bar PlotXTabs(happy,2,5,"stack") # happiness by a variety of possible factors as a percent PlotXTabs(happy, 2, c(5:9), plottype = "percent") # turn the numbers around and change them up basically just showing all # the permutations PlotXTabs(happy, c(2,5), 9, plottype = "side") PlotXTabs(happy, c(2,5), c(6:9), plottype = "percent") PlotXTabs(happy, happy, c(6,7,9), plottype = "percent") PlotXTabs(happy, c(6,7,9), happy, plottype = "percent") ``` I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck (ibecav at gmail dot com) ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>. > "He who gives up [code] safety for [code] speed deserves neither." ([via](https://twitter.com/hadleywickham/status/504368538874703872))
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-PlotXTabs.Rmd
## ----setup, echo = FALSE, warning=FALSE, message=FALSE------------------------ knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(CGPfunctions) ## ----simple, fig.width=7.0, fig.height=3.5------------------------------------ # simplest possible call with the defaults PlotXTabs2( data = mtcars, y = am, x = cyl ) ## ----simple2, fig.width=7.0, fig.height=3.5----------------------------------- # more complex call PlotXTabs2( data = datasets::mtcars, y = am, x = cyl, bf.details = TRUE, xlab = "Number of cylinders", ylab = NULL, data.label = "both", label.fill.alpha = .3, labels.legend = c("0 = Manual", "1 = Automatic"), legend.title = "Transmission Type", legend.position = "left", title = "The perenial mtcars example", palette = "Pastel1" ) ## ----LoadLibrary-------------------------------------------------------------- library(dplyr) library(purrr) library(productplots) library(tidyselect) str(happy) ## ----vignette1, fig.width=7.0, fig.height=3.5--------------------------------- # who's happier by gender PlotXTabs2(happy,happy,sex) ## ----vignette2, fig.width=7.0, fig.height=3.5--------------------------------- myvariables <- happy %>% select_if(is.factor) %>% select(-happy) %>% names mytitles <- stringr::str_c("Happiness by ", stringr::str_to_title(myvariables), " status") myvariables mytitles purrr::map2(.x = myvariables, .y = mytitles, .f = ~ PlotXTabs2(x = all_of(.x), title = .y, data = happy, y = happy, legend.title = "Rating", xlab = stringr::str_to_title(.x), ylab = NULL, perc.k = 1, palette = "Set2" ) )
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-PlotXTabs2.R
--- title: "Using PlotXTabs2" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using PlotXTabs2} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, echo = FALSE, warning=FALSE, message=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(CGPfunctions) ``` Like `PlotXTabs` this function is designed to automate and make efficient a relatively common task in some branches of science. The task of cross tabulating and displaying certain nominal and ordinal variables. It makes use of the `tidyverse` and to achieve those ends and is optimized to work with `purrr`. Imagine that you want to take two of the `mtcars` variables, for example `am` and `cyl`, and conduct a cross tabulation, get some basic statistics about whether they are "independent" and then plot it. Since it's the sort of thing I'm likely to do often seemed like a good candidate for a function. The function should allow us to efficiently repeat across more than two variables at a time. It would be very tedious to execute the command 25 times if I had 1 dependent variables and 25 independent variables. It provides visually appealing and sensibly labelled charts quickly and efficiently. It does some basic error checking and allows the user some choice as to exact style without having to know any underlying syntax or semantics. ```{r simple, fig.width=7.0, fig.height=3.5} # simplest possible call with the defaults PlotXTabs2( data = mtcars, y = am, x = cyl ) ``` ## Important considerations 1. The variables may be `bare` or quoted text. 2. By default a simple summary of key frequentist and bayesian information is supplied but this subtitle can be suppressed. 3. Thanks to `ggstatsplot` there are a plethora of formatting options. To demonstrate just a few... ```{r simple2, fig.width=7.0, fig.height=3.5} # more complex call PlotXTabs2( data = datasets::mtcars, y = am, x = cyl, bf.details = TRUE, xlab = "Number of cylinders", ylab = NULL, data.label = "both", label.fill.alpha = .3, labels.legend = c("0 = Manual", "1 = Automatic"), legend.title = "Transmission Type", legend.position = "left", title = "The perenial mtcars example", palette = "Pastel1" ) ``` ## Example scenario ... What makes us happy? The documentation examples use the `mtcars` and `HairEyeColor` built-in datasets. They are handy, convenient, and available by default. To demonstrate the function in action, however, I'm going to use a different dataset. Something that should allow you to better see the value of making plots of the crosstabs rather than simple tables. It also has the happy property of being much much larger than `mtcars` so we can see if there are lags in performance due to the number of rows. Rather than provide my own or make anyone work too hard I selected that `happy` dataset that comes bundled with several `R` packages including `productplots` and `GGally`. From the description: > The data is a small sample of variables related to happiness from the general social survey (GSS). The GSS is a yearly cross-sectional survey of Americans, run from 1976. We combine data for 25 years to yield 51,020 observations, and of the over 5,000 variables, we select nine related to happiness. We'll load the library and take a quick look at the structure of the data. ```{r LoadLibrary} library(dplyr) library(purrr) library(productplots) library(tidyselect) str(happy) ``` We'll be focusing on the non numeric variables. I certainly can't claim to do a detailed analysis here but at least the questions will be fun I hope... Here's the shortest possible call. ```{r vignette1, fig.width=7.0, fig.height=3.5} # who's happier by gender PlotXTabs2(happy,happy,sex) ``` That's useful, especially when you consider the variety of formatting options, but far more useful in my work flows when we make use of `purrr` `map` operators. Let's imagine a scenario where we want to see how happiness is related to all the other `factor` (categorical - be they nomainal or ordinal) variables in our dataset. For each of them (`sex`, `marital`, `degree`, `finrela` and `health`) we want to plot consistent graphs and have the same information available. Rather than the tedium of cutting and pasting five times and then changing the variable name let's let `purrr` handles as much of the workflow as possible. Using a simple set of `dplyr` verbs we'll create a simple list of the variables we are interested in. Technically it's a vector but `purrr` will coerce it to a list. Since I dislike plots without titles we can also create a vector of titles by prepending "Happiness by " to the capitalized variable name. After checking our handiwork in creating the vectors we can then feed them to `purrr:map2`. We could conceivably have used any `map` depending on complexity. Just for a little "twist" we'll actually use the `myvariables` list twice. Once as the variable name for the x variable and then again after capitalizing it as the X axis label. ```{r vignette2, fig.width=7.0, fig.height=3.5} myvariables <- happy %>% select_if(is.factor) %>% select(-happy) %>% names mytitles <- stringr::str_c("Happiness by ", stringr::str_to_title(myvariables), " status") myvariables mytitles purrr::map2(.x = myvariables, .y = mytitles, .f = ~ PlotXTabs2(x = all_of(.x), title = .y, data = happy, y = happy, legend.title = "Rating", xlab = stringr::str_to_title(.x), ylab = NULL, perc.k = 1, palette = "Set2" ) ) ``` ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-PlotXTabs2.Rmd
## ----setup, echo = FALSE, warning=FALSE, message=FALSE------------------------ knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----one, fig.width=7.0, fig.height=5.5, warning=FALSE, message=FALSE--------- library(CGPfunctions) # library(CHAID) library(dplyr) library(knitr) ### fit tree to subsample see ?chaid ## set.seed(290875) ## USvoteS <- USvote[sample(1:nrow(USvote), 1000),] ## ctrl <- chaid_control(minsplit = 200, minprob = 0.1) ## chaidUS <- chaid(vote3 ~ ., data = USvoteS, control = ctrl) print(chaidUS) plot(chaidUS) ## ----simple2, fig.width=7.0, fig.height=3.5----------------------------------- # simplest use --- chaidUS is included in the package class(chaidUS) chaid_table(chaidUS) mychaidtable <- chaid_table(chaidUS) ## ----simple3------------------------------------------------------------------ mychaidtable %>% select(nodeID:ruletext) %>% kable() # Just node #2 show percentage mychaidtable %>% select(nodeID:ruletext) %>% filter(nodeID == 2) %>% mutate(pctBush = Bush/NodeN * 100) %>% kable(digits = 1) # Just the children of node #5 mychaidtable %>% select(nodeID:ruletext) %>% filter(parent == 5) %>% kable() # stats for all splits including raw (unadjusted) p value mychaidtable %>% select(nodeID, NodeN, split.variable:rawpvalue) %>% filter(!is.na(split.variable)) %>% kable()
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-chaid_table.R
--- title: "Using chaid_table" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using chaid_table} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, echo = FALSE, warning=FALSE, message=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` **Chi-square automatic interaction detection (CHAID)** is a decision tree technique, based on adjusted significance testing (Bonferroni testing). The technique was developed in South Africa and was published in 1980 by Gordon V. Kass, who had completed a PhD thesis on this topic. [Wikipedia](https://en.wikipedia.org/wiki/Chi-square_automatic_interaction_detection) I've [written a few blog posts](https://ibecav.netlify.app/tags/chaid/) about using this venerable technique. The default output using `print()` and `plot()` is sparse, elegant and useful as is, and can be adjusted in many ways that [I have documented here](https://ibecav.github.io/chaidtutor1/). The code chunk below is taken straight from the example in the help page for `CHAID::chaid` > The dataset is based on data from a post-election survey on persons who voted for either Bush or Gore in the 2000 U.S. election. The specific variables are related to the publication of Magidson and Vermunt (2005). > Further information (and datasets) about the 2000 U.S. election and other National Election Studies is available on the American National Election Studies Web site (https://electionstudies.org/). ```{r one, fig.width=7.0, fig.height=5.5, warning=FALSE, message=FALSE} library(CGPfunctions) # library(CHAID) library(dplyr) library(knitr) ### fit tree to subsample see ?chaid ## set.seed(290875) ## USvoteS <- USvote[sample(1:nrow(USvote), 1000),] ## ctrl <- chaid_control(minsplit = 200, minprob = 0.1) ## chaidUS <- chaid(vote3 ~ ., data = USvoteS, control = ctrl) print(chaidUS) plot(chaidUS) ``` ## Getting more detailed But what happens if you want to investigate your results more closely? I actually had at least one reader of my blog posts point out that [some other statistical packages](https://www.ibm.com/support/knowledgecenter/en/SSLVMB_23.0.0/spss/tutorials/tree_credit_treetable.html#tree_credit_treetable) produce more detailed information in a tabular format. Some additional things you may want to know that are actually contained in `chaidUS` but aren't especially easy to see from the default plot and print and aren't necessarily easy to ferret out of the `chaidUS` object: 1. It's clear from our call that we fed `chaid` 1,000 random rows of the dataset `USvote`. It must be safe to assume that's how many valid cases there were right? The documentation is mute on how it handles missing cases. 2. There's information about counts and frequencies in the terminal nodes (3, 4, 6, 8, 9) and we could manually calculate the answers to other questions like how many people voted for Bush in node #9 (115 * 40.9% = 47)? How many total voters are in node #2 (311 + 249 = 560)? But getting more information gets increasingly tedious. At node #2 what was the breakdown of votes for Bush -v- Gore (hint 245 -v- 315 respectively). 3. It would also be nice to have easy access to the results of the $\chi^2$ tests that are the inherent workhorse of CHAID. We know that `marstat` was selected as the first split by virtue of having the smallest `p value` after a Bonferroni adjustment, but what were the results? `chaid_table` attempts to provide much more granular information in a tibble and also make it possible for you to derive even more nuanced questions through piping operations. The simplest call is just to feed it the name of the object after it has been processed by `CHAID`. That object will be of class "constparty" "party". ```{r simple2, fig.width=7.0, fig.height=3.5} # simplest use --- chaidUS is included in the package class(chaidUS) chaid_table(chaidUS) mychaidtable <- chaid_table(chaidUS) ``` I debated the wisdom of providing tables as output in the manner I found most useful and aesthetically pleasing but in the end decided to simply provide the tibble and let the user decide what and how to format. ## Example uses Some easy examples using `kable` and `dplyr`. ```{r simple3} mychaidtable %>% select(nodeID:ruletext) %>% kable() # Just node #2 show percentage mychaidtable %>% select(nodeID:ruletext) %>% filter(nodeID == 2) %>% mutate(pctBush = Bush/NodeN * 100) %>% kable(digits = 1) # Just the children of node #5 mychaidtable %>% select(nodeID:ruletext) %>% filter(parent == 5) %>% kable() # stats for all splits including raw (unadjusted) p value mychaidtable %>% select(nodeID, NodeN, split.variable:rawpvalue) %>% filter(!is.na(split.variable)) %>% kable() ``` Hopefully those are enough examples to get your creative juices going. ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-chaid_table.Rmd
## ----setup-------------------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) # Install from CRAN # install.packages("CGPfunctions") # Or the development version from GitHub # install.packages("devtools") # devtools::install_github("ibecav/CGPfunctions") library(CGPfunctions) library(tidyr) library(dplyr) ## ----ggslope1, fig.height=10, fig.width=7------------------------------------- newggslopegraph(newcancer,Year,Survival,Type) ## ----ggslope2, fig.height=10, fig.width=7------------------------------------- newggslopegraph(dataframe = newcancer, Times = Year, Measurement = Survival, Grouping = Type, Title = "Estimates of Percent Survival Rates", SubTitle = "Based on: Edward Tufte, Beautiful Evidence, 174, 176.", Caption = NULL ) ## ----ggslope3, fig.height=5, fig.width=5-------------------------------------- moredata <- structure(list(Date = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("11-May-18", "18-May-18", "25-May-18"), class = "factor"), Party = structure(c(5L, 3L, 2L, 1L, 4L, 5L, 3L, 2L, 1L, 4L, 5L, 3L, 2L, 1L, 4L), .Label = c("Green", "Liberal", "NDP", "Others", "PC"), class = "factor"), Pct = c(42.3, 28.4, 22.1, 5.4, 1.8, 41.9, 29.3, 22.3, 5, 1.4, 41.9, 26.8, 26.8, 5, 1.4)), class = "data.frame", row.names = c(NA, -15L)) #tail(moredata) newggslopegraph(moredata,Date,Pct,Party, Title = "Notional data", SubTitle = NULL, Caption = NULL) ## ----ggslope4, fig.height=5, fig.width=5-------------------------------------- newggslopegraph(moredata, Date, Pct, Party, Title = "Notional data", SubTitle = "none", Caption = "imaginary", LineColor = "gray", LineThickness = .5, YTextSize = 4 ) ## ----ggslope5, fig.height=5, fig.width=5-------------------------------------- newggslopegraph(moredata, Date, Pct, Party, Title = "Notional data", SubTitle = "none", Caption = "imaginary", LineColor = c("Green" = "gray", "Liberal" = "green", "NDP" = "red", "Others" = "gray", "PC" = "gray"), LineThickness = .5, YTextSize = 4 ) ## ----ggslope6, fig.height=12, fig.width=6------------------------------------- newggslopegraph(newgdp, Year, GDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = c(rep("gray",3), "red", rep("gray",3), "red", rep("gray",10)) ) ## ----ggslope7, fig.height=7, fig.width=6-------------------------------------- newgdp$rGDP <- signif(newgdp$GDP, 2) newggslopegraph(newgdp, Year, rGDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = c(rep("gray",6), rep("red",2), "red", rep("gray",10)) ) custom_colors <- tidyr::pivot_wider(newgdp, id_cols = Country, names_from = Year, values_from = GDP) %>% mutate(difference = Year1979 - Year1970) %>% mutate(trend = case_when( difference >= 2 ~ "green", difference <= -1 ~ "red", TRUE ~ "gray" ) ) %>% select(Country, trend) %>% tibble::deframe() custom_colors newggslopegraph(newgdp, Year, rGDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = custom_colors )
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-newggslopegraph.R
--- title: "Using newggslopegraph" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using newggslopegraph} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- This function is designed to automate the process of producing a [Tufte style slopegraph](https://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0003nk) using `ggplot2`. I've been aware of slopegraphs and bumpcharts for quite some time, and I certainly am aware of [Tufte's work](https://www.edwardtufte.com/tufte/). As an amateur military historian I've always loved, for example, [his poster](https://www.edwardtufte.com/tufte/posters) depicting Napoleon's Russian Campaign. So when I saw the article from [Murtaza Haider](https://www.r-bloggers.com/author/murtaza-haider/) titled *"Edward Tufte’s Slopegraphs and political fortunes in Ontario"* I just had to take a shot at writing a function. To make it a little easier to get started with the function I have taken the liberty of providing the cancer data in a format where it is immediately usable. Please see `?newcancer`. ## Installation and setup Long term I'll try and ensure the version on `CRAN` is well maintained but for now you're better served by grabbing the current version from GITHUB. ```{r setup} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) # Install from CRAN # install.packages("CGPfunctions") # Or the development version from GitHub # install.packages("devtools") # devtools::install_github("ibecav/CGPfunctions") library(CGPfunctions) library(tidyr) library(dplyr) ``` ## Simple examples If you're unfamiliar with slopegraphs or just want to see what the display is all about the dataset I've provided can get you started in one line ```{r ggslope1, fig.height=10, fig.width=7} newggslopegraph(newcancer,Year,Survival,Type) ``` Optionally you can provide important label information through `Title`, `Subtitle`, and `Caption` arguments. You can suppress them all together by setting them `= NULL` but since I think they are very important the default is to gently remind you, that you have not provided any information. Let's provide a title and sub-title but skip the caption. ```{r ggslope2, fig.height=10, fig.width=7} newggslopegraph(dataframe = newcancer, Times = Year, Measurement = Survival, Grouping = Type, Title = "Estimates of Percent Survival Rates", SubTitle = "Based on: Edward Tufte, Beautiful Evidence, 174, 176.", Caption = NULL ) ``` ## How it all works It's all well and good to get the little demo to work, but it might be useful for you to understand how to extend it out to data you're interested in. You'll need a dataframe with at least three columns. The function will do some basic error checking and complain if you don't hit the essentials. 1. `Times` is the column in the dataframe that corresponds to the x axis of the plot and is normally a set of moments in time expressed as either characters, factors or ordered factors (in our case `newcancer$Year`. If it is truly time series data (especially with a lot of dates you're much better off using an R function purpose built for that). In `newcancer` it's an ordered factor, mainly because if we fed the information in as character the sort order would be `Year 10, Year 15, Year 20, Year 5` which is very suboptimal. A command like `newcancer$Year <- factor(newcancer$Year,levels = c("Year.5", "Year.10", "Year.15", "Year.20"), labels = c("5 Year","10 Year","15 Year","20 Year"), ordered = TRUE)` would be the way to force things they way you want them. 2. `Measurement` is the column that has the actual numbers you want to display along the y axis. Frequently that's a percentage but it could just as easily be any number. Watch out for scaling issues here you'll want to ensure that its not disparate. In our case `newcancer$Survival` is the percentage of patients surviving at that point in time, so the maximum scale is 0 to 100. 3. `Grouping` is what controls how many individual lines are portrayed. Every attempt is made to color them and label them in ways that lead to clarity but eventually you can have too many. In our example case the column is `newcancer$Type` for the type of cancer or location. ## Another quick example This is loosely based off a blog post from [Murtaza Haider titled “Edward Tufte’s Slopegraphs and political fortunes in Ontario”](https://www.r-bloggers.com/author/murtaza-haider/) that led to my developing this function [chronicled here](https://ibecav.github.io/slopegraph/). In this case we're going to plot the percent of the vote captured by some Canadian political parties. > The data is loosely based on real data but is not actually accurate. `moredata$Date` is the hypothetical polling date as a factor (in this case `character` would work equally well). `moredata$Party` is the various political parties and `moredata$Pct` is the percentage of the vote they are estimated to have. ```{r ggslope3, fig.height=5, fig.width=5} moredata <- structure(list(Date = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("11-May-18", "18-May-18", "25-May-18"), class = "factor"), Party = structure(c(5L, 3L, 2L, 1L, 4L, 5L, 3L, 2L, 1L, 4L, 5L, 3L, 2L, 1L, 4L), .Label = c("Green", "Liberal", "NDP", "Others", "PC"), class = "factor"), Pct = c(42.3, 28.4, 22.1, 5.4, 1.8, 41.9, 29.3, 22.3, 5, 1.4, 41.9, 26.8, 26.8, 5, 1.4)), class = "data.frame", row.names = c(NA, -15L)) #tail(moredata) newggslopegraph(moredata,Date,Pct,Party, Title = "Notional data", SubTitle = NULL, Caption = NULL) ``` There are a plethora of formatting options. See `?newggslopegraph` for all of them. Here's a few. ```{r ggslope4, fig.height=5, fig.width=5} newggslopegraph(moredata, Date, Pct, Party, Title = "Notional data", SubTitle = "none", Caption = "imaginary", LineColor = "gray", LineThickness = .5, YTextSize = 4 ) ``` The most complex is `LineColor` where you can do the following if you want to highlight the difference between the Liberal and NDP parties while making the other three less prominent... ```{r ggslope5, fig.height=5, fig.width=5} newggslopegraph(moredata, Date, Pct, Party, Title = "Notional data", SubTitle = "none", Caption = "imaginary", LineColor = c("Green" = "gray", "Liberal" = "green", "NDP" = "red", "Others" = "gray", "PC" = "gray"), LineThickness = .5, YTextSize = 4 ) ``` ## Slopegraph Best Practices 1. Scaling -- this function plots to scale on an actual scale. 2. If the datapoints or labels are bunching up, expand the vertical size of the plot as necessary. 3. Names of the items on both the left-hand and right-hand axes are aligned, to make vertical scanning of the items’ names easier. 4. Many suggest using a thin, light gray line to connect the data. A too-heavy line is unnecessary and will make the chart harder to read. 4. When a chart features many slope intersections, judicious use of color can avoid what Ben Fry describes as the "pile of sticks" phenomenon (Visualizing Data, 121). 5. A table (with more statistical detail) might be a good complement to use alongside the slopegraph. As Tufte notes: “The data table and the slopegraph are colleagues in explanation not competitors. One display can serve some but not all functions.” ## One last set of data Also from Tufte, this is data about a select group of countries Gross Domestic Product (GDP). I'll use it to show you a tricky way to highlight certain countries without making a named vector with `LineColor = c(rep("gray",3), "red", rep("gray",3), "red", rep("gray",10))` the excess vector entries are silently dropped... The bottom line is that `LineColor` is simply a character vector that you can fill any way you choose. ```{r ggslope6, fig.height=12, fig.width=6} newggslopegraph(newgdp, Year, GDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = c(rep("gray",3), "red", rep("gray",3), "red", rep("gray",10)) ) ``` Finally, let me take a moment about crowding and labeling. I've made every effort to try and deconflict the labels on the left and right axis (in this example the `Country`) and that should work automatically as you resize your plot dimensions. ** pro tip - if you use `RStudio` you can press the `zoom` icon and then use the rescaling of the window to see best choices **. But the numbers (`GDP`) are a different matter and there's no easy way to ensure separation in a case like this data. There's a decent total spread from 57.4 to 20.7 and some really close measurements like France, Belgium, and Germany on the right side. My suggestion is in a case like this one you create a new column in your dataframe with two significant places. So specifically it would be `newgdp$rGDP <- signif(newgdp$GDP, 2)`. In my testing, at least, I've found this helps without creating inaccuracy and not causing you to try and "stretch" vertically to disambiguate the numbers. This time I'll also use `LineColor` to highlight how Canada, Finland and Belgium fare from 1970 to 1979. Then to demonstrate how flexible `LineColor` really is I'll use some `tidyverse` tools to build a named list of countries and colors. The country's line color will be determined by whether the difference between 1979 is positive, near neutral or negative. ```{r ggslope7, fig.height=7, fig.width=6} newgdp$rGDP <- signif(newgdp$GDP, 2) newggslopegraph(newgdp, Year, rGDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = c(rep("gray",6), rep("red",2), "red", rep("gray",10)) ) custom_colors <- tidyr::pivot_wider(newgdp, id_cols = Country, names_from = Year, values_from = GDP) %>% mutate(difference = Year1979 - Year1970) %>% mutate(trend = case_when( difference >= 2 ~ "green", difference <= -1 ~ "red", TRUE ~ "gray" ) ) %>% select(Country, trend) %>% tibble::deframe() custom_colors newggslopegraph(newgdp, Year, rGDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = custom_colors ) ``` ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/inst/doc/Using-newggslopegraph.Rmd
--- title: "Using Plot2WayAnova" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using Plot2WayAnova} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## Background The CGPfunctions package includes functions that I find useful for teaching statistics especially to novices (as well as an opportunity to sharpen my own R skills). I only write functions when I have a real need -- no theory -- just help for actually practicing the art. They typically are not "new" methods but rather wrappers around either base R or other packages and are very task focused. This vignette covers one function from the package that tries to help users (especially students) do one thing well by pulling together pieces from a variety of places in `R`. `Plot2WayANOVA`, which as the name implies conducts a 2 way ANOVA and plots the results. I always try and find the right balance between keeping the number of dependencies to a minimum and not reinventing the wheel and writing functions that others have done for me. The function makes use of the following non base r packages. - `ggplot2` as the work horse for all the actual plotting - `car` for it's ability to compute Type II sums of squares, we'll address why that's important in more detail later in the scenario. We'll also make use of it's `leveneTest`. - `sjstats` which takes out ANOVA table and gives us other important information such as the effect sizes ($\eta^2$ and $\omega^2$ ) through use of its `anova_stats` function. Prior to this version I had been using my own local function but this runs rings around what I could do. - `broomExtra::glance` will also help us grab very important results like $R^2$ and display them - `DescTool::PostHocTest` for accomplishing post hoc tests ## Vignette Info The ANOVA (Analysis of Variance) family of statistical techniques allow us to compare mean differences of one outcome (dependent) variable across two or more groups (levels) of one or more independent variables (factor). It is also true that ANOVA is a special case of the GLM or regression models so as the number of levels increase it might make more sense to try one of those approaches. The 2 Way ANOVA allows for comparisons of mean differences across 2 independent variables `factors` with a varying numbers of `levels` in each `factor`. If you prefer a more regression based approach with a very similar plotted result I highly recommend the `interactions` package which I was unaware of until just recently. It is [available through CRAN](https://CRAN.R-project.org/package=interactions). The `Plot2WayANOVA` function conducts a classic analysis of variance (ANOVA) in a sane and defensible, albeit opinionated, manner, not necessarily the only one. It's real strength (*I hope*) lies in the fact that it is pulled together in one function and more importantly allows you to visualize the results concurrently with no additional work. ## Scenario and data Imagine that you are interested in understanding whether a car's fuel efficiency (mpg) varies based upon the type of transmission (automatic or manual) and the number of cylinders the engine has. Let's imagine that the `mtcars` data set is actually a random sample of 32 cars from different manufacturers and use the mean `mpg` grouped by `am` and `cyl` to help inform our thinking. While we expect variation across our sample we're interested in whether the differences between the means by grouping of transmission type and cylinders is significantly different than what we would expect in random variation across the data. In simplistic terms we want to know whether `am` matters, `cyl` matters or if it depends on the interaction of the two. It's this interaction term that typically confuses novices or is difficult to "see". That's where a good interaction graph can hopefully play a key role, and that's what the `Plot2WayANOVA` focuses on. There's no lack or tools or capabilities in base R or in the many packages to do this task. What this function tries to do is pull together the disparate pieces with a set of sane defaults and a simple interface to work with it. At its simplest you would require the library and then enter this command: `Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars)` which lays our question out in R's vernacular with a formula and a dataframe. Optionally we can specify a different confidence level and choose a line or a bar graph. Over time the function has gained a plethora of formatting options. "Under the hood", however there's a lot of nice features at work. 1. Some basic error checking to ensure a valid formula and dataframe. The function accepts only a fully crossed formula to check for an interaction term 1. It ensures the dependent (outcome) variable is numeric and that the two independent (predictor) variables already are or can be coerced to factors – the user is warned on the console if there are problems. 1. A check is conducted to see if any of the variables of interest have missing cases – the user is warned on the console if there are problems. 1. Balance is checked, that is whether the number of observations per cell when we cross `am` and `cyl` is equal. There's some debate as to how much imbalance is permissible. But you'll be given fair warning if there is any. 1. In addition to the classic ANOVA table information available in `aov` or `Anova` you'll be presented with information about effect sizes like eta squared $\eta^2$. They're calculated and appended as additional columns. If you're unfamiliar with them and want to know more especially where the numbers come from I recommend a good introductory stats text. I recommend *Learning Statistics with R* [LSR](https://learningstatisticswithr.com/) see Table 14-1 on page 432. 1. A summarized table of means, standard deviations, standard errors of the means, confidence intervals, and group sizes for each of the crossed combinations in our example that's 6 groupings 3 levels of cylinder and 2 levels of automatic or manual. 1. Some measures of overall fit including $R^2$ 1. If any of the effect terms (main or interaction) are significant you'll be presented with a post-hoc comparison of the means. By default a Scheffe test is run but the user can choose from several supported options. 1. The Homogeneity of Variance assumption is tested with Brown-Forsythe 1. The normality assumption is tested with Shapiro-Wilk ## Installation ```{r eval = FALSE} # Install from CRAN install.packages("CGPfunctions") # Or the development version from GitHub # install.packages("devtools") devtools::install_github("ibecav/CGPfunctions") ``` then load the library. ```{r LoadLibrary, warning = FALSE} library(CGPfunctions) ``` ## Example of using the function The only two required parameters are a formula and a dataframe (like) object. If we run the function in its simplest form here's what we get. ```{r Plot2WayANOVA, echo=TRUE, message=TRUE, warning=FALSE, fig.width=7, fig.height=4} Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars) ``` In the console you'll receive a series of messages chronicling your progress and any diagnostic information. In this case `am` and `cyl` are being coerced to factors and you're being prompted to make sure that's what is intended. Next you receive a warning because you have a very unbalanced design. There are only two 8 cylinder cars with a manual transmission and twelve 8 cylinder cars with automatics. Whereas there are eight 4 cylinders with manual and only three that are automatics. Imbalance in our design worries us for two reasons. One is that it causes a lack of statistical power and creates some math challenges in deciding how to divide up the sums of the squared differences. This data set causes the more troublesome worry. Are the number of cylinders and manual versus automatic related systematically which would call our whole design into question. Make sure you can answer questions about which is at work here, or make sure you have a balanced design. A table follows that is intended to summarize the findings. We'll discuss it more later when we examine the plot. The overall measures table can be very handy for comparing numerous models. For example how does the AIC number change if we were to eliminate `am` ? The table of group means is useful for looking at summary by group. Want the best gas mileage? Buy a 4 cylinder manual car. In our simple example the only statistically significant effect is for the main effect of number of cylinders. Accordingly the Scheffe test is run against the three types of cars with 4, 6, or 8 cylinders and we can see that with a difference of 7.3 mpg eight and four cylinder cars are statistically significant even as we control for the multiple simultaneous comparisons. The next step is to test homogeneity of variance also known as (homoscedasticity). Since the math in our ANOVA rely on the assumption that the variance for the different groupings of cars is more or less equal, we need to check that assumption. We'll use the Brown-Forsythe test. When you run the `leveneTest` in R the default is actually a Brown-Forsythe, to get a true Levene you must specify `center = mean`. Brown-Forsythe is actually more robust since it tests differences from the median. Not surprisingly when we consult out table of group results we have some reason for concern sine the standard deviations vary widely. Finally, let’s address the assumption that our errors or residuals are normally distributed. We’re looking for evidence that our residuals are skewed or tailed or otherwise misshapen in a way that would influence our results. Surprisingly, there is actually quite a bit of controversy on this point since on the one hand we have strong reason to believe that our sample will be imperfect and that our population will not necessarily be “perfectly normal” either. Some argue that some simple plotting is all that is necessary looking for an unspecifiable amount of non normality that will trigger a search for the source. Other prefer a more formal approach using one or more statistical tests. `Plot2WayANOVA` runs the most common test of the normality assumption (there are many) the Shapiro-Wilk test The statistics look good, no strong evidence in the data we have. The default settings for the resultant plot are deliberately minimalistic, allowing you to focus visually on the pattern of means and the connecting lines. If you're already used to looking at this sort of plot it is immediately apparent from the separation between the lines that the number of cylinders is having a significant impact on mileage. Automatic versus manual transmission seems to have less impact (judged by the relative lack of slope except for 4 cylinder models) and there does seem to be at least the start of an interaction between the two. (bear in mind this is a small data set and we are very unbalanced). One other easy tip is warranted. Order matters and sometimes it is helpful to run the command simply reversing the order of the independent variables to help you better "see" the results, e.g. `Plot2WayANOVA(formula = mpg ~ cyl * am, dataframe = mtcars)` **Note that if you want to "save" all these tables of data and information all you need to do is store the results in an object as in `MyResults <- Plot2WayANOVA(formula = mpg ~ am * cyl, dataframe = mtcars)` then `MyResults` can be accessed as a list.** ### Some common tweaks Let's make some changes that are likely to be quite common: 1. Change the order of the factors 1. Change to p < .01 or 99% CI 1. Add title and axis labels 1. Add a label with the actual group mean values 1. **New** display the standard error of the mean (SEM) instead of confidence intervals 1. Change the plotted shape for the group mean to a square not a diamond 1. Change our post hoc test method to something less conservative than Scheffe ```{r Plot2WayANOVA2, echo=TRUE, fig.height=4, fig.width=7, message=FALSE, warning=FALSE} Plot2WayANOVA(formula = mpg ~ cyl * am, dataframe = mtcars, confidence = .99, title = "MPG by cylinders and type transmission", xlab = "Cylinders", ylab = "Miles per gallon", mean.label = TRUE, mean.shape = 22, posthoc.method = "lsd", errorbar.display = "SEM" ) ``` **Please don't fail to notice how liberal Fisher's LSD is compared to Scheffe especially given we've demanded more confidence ** ### Less common more custom tweaks Although the defaults are minimalistic to allow you to focus on the interaction pattern the function also has any number of optional ways of increasing complexity and showing more information. Let's make some custom changes that are more uncommon: 1. Display standard deviation errorbars 1. Show individual data points 1. Superimpose a boxplot 1. **New** use an entirely different theme (minimal) 1. **New** custom text for the factor labels (bigger and blue) ```{r Plot2WayANOVA3, echo=TRUE, fig.height=4, fig.width=7, message=FALSE, warning=FALSE} # Create a new dataset library(dplyr) library(ggplot2) library(stringi) newmpg <- mpg %>% filter(cyl != 5) %>% mutate(am = stringi::stri_extract(trans, regex = "auto|manual")) Plot2WayANOVA(formula = hwy ~ am * cyl, dataframe = newmpg, ylab = "Highway mileage", xlab = "Transmission type", plottype = "line", offset.style = "wide", overlay.type = "box", mean.label = TRUE, mean.shape = 20, mean.size = 3, mean.label.size = 3, show.dots = TRUE, errorbar.display = "SD", ggtheme = ggplot2::theme_minimal(), ggplot.component = theme(axis.text.x = element_text(size=14, color="darkblue")) ) ``` ## Credits Many thanks to Danielle Navarro and the book * [Learning Statistics with R](https://learningstatisticswithr.com/).* ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/vignettes/Using-Plot2WayANOVA.Rmd
--- title: "Using PlotXTabs" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using PlotXTabs} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, echo = FALSE, warning=FALSE, message=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(CGPfunctions) ``` This function is designed to automate and make efficient a relatively common task in some branches of science. The task of cross tabulating and displaying certain types of variables. It makes use of `dplyr` and `ggplot2` to achieve those ends. Imagine that you want to take two of the `mtcars` variables, for example `am` and `cyl`, and conduct a cross tabulation and then plot it. Since it's the sort of thing I'm likely to do often seemed like a good candidate to write a function for. Then I decided that I might very well want the function to allow me to input more than two variables at a time. It would be very tedious to execute the command 25 times if I had 5 dependent variables and 5 independent variables and needed to fully cross them. It provides visually appealing and sensibly labelled charts quickly and efficiently. It does some basic error checking and allows the user some choice as to exact style without having to know any underlying syntax or semantics. ## Possible cases The function is designed to handle four possible scenarios. Take the user's input and parse it into one of four known possibilities and then take appropriate action. The possibilities are: 1. If both are `bare` variables and found in the dataframe immediately print the plot 2. At least one of the variables is `bare` and found in the dataframe (variable x) and the other is one or more column numbers (variable y) 3. At least one of the variables is `bare` and found in the dataframe (variable y) and the other is one or more column numbers (variable x) 4. Both the variables were passed to us as numbers. Could be one or more numbers for either variable. ## Example scenario ... What makes us happy? The documentation examples use the `mtcars` built-in dataset. It's handy, convenient, and it's installed by default. To actually show the function in action, however, I'm going to use a different dataset. Something that should allow you to better see the value of making plots of the crosstabs rather than simple tables. It also has the happy property of being much much larger than `mtcars` so we can see if there are lags in performance due to the number of rows. Rather than provide my own or make anyone work too hard I selected that `happy` dataset that comes bundled with several `R` packages including `productplots` and `GGally`. From the description: > The data is a small sample of variables related to happiness from the general social survey (GSS). The GSS is a yearly cross-sectional survey of Americans, run from 1976. We combine data for 25 years to yield 51,020 observations, and of the over 5,000 variables, we select nine related to happiness. We'll load the library and take a quick look at the structure of the data. ```{r LoadLibrary} library(productplots) str(happy) ``` We'll be focusing on the non numeric variables. I certainly can't claim to do a detailed analysis here but at least the questions will be fun I hope... ```{r vignette1, fig.width=6.0, fig.height=2.5} # who's happier by gender PlotXTabs(happy,happy,sex) # same thing using column numbers and a stacked bar PlotXTabs(happy,2,5,"stack") # happiness by a variety of possible factors as a percent PlotXTabs(happy, 2, c(5:9), plottype = "percent") # turn the numbers around and change them up basically just showing all # the permutations PlotXTabs(happy, c(2,5), 9, plottype = "side") PlotXTabs(happy, c(2,5), c(6:9), plottype = "percent") PlotXTabs(happy, happy, c(6,7,9), plottype = "percent") PlotXTabs(happy, c(6,7,9), happy, plottype = "percent") ``` I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck (ibecav at gmail dot com) ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>. > "He who gives up [code] safety for [code] speed deserves neither." ([via](https://twitter.com/hadleywickham/status/504368538874703872))
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/vignettes/Using-PlotXTabs.Rmd
--- title: "Using PlotXTabs2" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using PlotXTabs2} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, echo = FALSE, warning=FALSE, message=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) library(CGPfunctions) ``` Like `PlotXTabs` this function is designed to automate and make efficient a relatively common task in some branches of science. The task of cross tabulating and displaying certain nominal and ordinal variables. It makes use of the `tidyverse` and to achieve those ends and is optimized to work with `purrr`. Imagine that you want to take two of the `mtcars` variables, for example `am` and `cyl`, and conduct a cross tabulation, get some basic statistics about whether they are "independent" and then plot it. Since it's the sort of thing I'm likely to do often seemed like a good candidate for a function. The function should allow us to efficiently repeat across more than two variables at a time. It would be very tedious to execute the command 25 times if I had 1 dependent variables and 25 independent variables. It provides visually appealing and sensibly labelled charts quickly and efficiently. It does some basic error checking and allows the user some choice as to exact style without having to know any underlying syntax or semantics. ```{r simple, fig.width=7.0, fig.height=3.5} # simplest possible call with the defaults PlotXTabs2( data = mtcars, y = am, x = cyl ) ``` ## Important considerations 1. The variables may be `bare` or quoted text. 2. By default a simple summary of key frequentist and bayesian information is supplied but this subtitle can be suppressed. 3. Thanks to `ggstatsplot` there are a plethora of formatting options. To demonstrate just a few... ```{r simple2, fig.width=7.0, fig.height=3.5} # more complex call PlotXTabs2( data = datasets::mtcars, y = am, x = cyl, bf.details = TRUE, xlab = "Number of cylinders", ylab = NULL, data.label = "both", label.fill.alpha = .3, labels.legend = c("0 = Manual", "1 = Automatic"), legend.title = "Transmission Type", legend.position = "left", title = "The perenial mtcars example", palette = "Pastel1" ) ``` ## Example scenario ... What makes us happy? The documentation examples use the `mtcars` and `HairEyeColor` built-in datasets. They are handy, convenient, and available by default. To demonstrate the function in action, however, I'm going to use a different dataset. Something that should allow you to better see the value of making plots of the crosstabs rather than simple tables. It also has the happy property of being much much larger than `mtcars` so we can see if there are lags in performance due to the number of rows. Rather than provide my own or make anyone work too hard I selected that `happy` dataset that comes bundled with several `R` packages including `productplots` and `GGally`. From the description: > The data is a small sample of variables related to happiness from the general social survey (GSS). The GSS is a yearly cross-sectional survey of Americans, run from 1976. We combine data for 25 years to yield 51,020 observations, and of the over 5,000 variables, we select nine related to happiness. We'll load the library and take a quick look at the structure of the data. ```{r LoadLibrary} library(dplyr) library(purrr) library(productplots) library(tidyselect) str(happy) ``` We'll be focusing on the non numeric variables. I certainly can't claim to do a detailed analysis here but at least the questions will be fun I hope... Here's the shortest possible call. ```{r vignette1, fig.width=7.0, fig.height=3.5} # who's happier by gender PlotXTabs2(happy,happy,sex) ``` That's useful, especially when you consider the variety of formatting options, but far more useful in my work flows when we make use of `purrr` `map` operators. Let's imagine a scenario where we want to see how happiness is related to all the other `factor` (categorical - be they nomainal or ordinal) variables in our dataset. For each of them (`sex`, `marital`, `degree`, `finrela` and `health`) we want to plot consistent graphs and have the same information available. Rather than the tedium of cutting and pasting five times and then changing the variable name let's let `purrr` handles as much of the workflow as possible. Using a simple set of `dplyr` verbs we'll create a simple list of the variables we are interested in. Technically it's a vector but `purrr` will coerce it to a list. Since I dislike plots without titles we can also create a vector of titles by prepending "Happiness by " to the capitalized variable name. After checking our handiwork in creating the vectors we can then feed them to `purrr:map2`. We could conceivably have used any `map` depending on complexity. Just for a little "twist" we'll actually use the `myvariables` list twice. Once as the variable name for the x variable and then again after capitalizing it as the X axis label. ```{r vignette2, fig.width=7.0, fig.height=3.5} myvariables <- happy %>% select_if(is.factor) %>% select(-happy) %>% names mytitles <- stringr::str_c("Happiness by ", stringr::str_to_title(myvariables), " status") myvariables mytitles purrr::map2(.x = myvariables, .y = mytitles, .f = ~ PlotXTabs2(x = all_of(.x), title = .y, data = happy, y = happy, legend.title = "Rating", xlab = stringr::str_to_title(.x), ylab = NULL, perc.k = 1, palette = "Set2" ) ) ``` ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/vignettes/Using-PlotXTabs2.Rmd
--- title: "Using chaid_table" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using chaid_table} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, echo = FALSE, warning=FALSE, message=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` **Chi-square automatic interaction detection (CHAID)** is a decision tree technique, based on adjusted significance testing (Bonferroni testing). The technique was developed in South Africa and was published in 1980 by Gordon V. Kass, who had completed a PhD thesis on this topic. [Wikipedia](https://en.wikipedia.org/wiki/Chi-square_automatic_interaction_detection) I've [written a few blog posts](https://ibecav.netlify.app/tags/chaid/) about using this venerable technique. The default output using `print()` and `plot()` is sparse, elegant and useful as is, and can be adjusted in many ways that [I have documented here](https://ibecav.github.io/chaidtutor1/). The code chunk below is taken straight from the example in the help page for `CHAID::chaid` > The dataset is based on data from a post-election survey on persons who voted for either Bush or Gore in the 2000 U.S. election. The specific variables are related to the publication of Magidson and Vermunt (2005). > Further information (and datasets) about the 2000 U.S. election and other National Election Studies is available on the American National Election Studies Web site (https://electionstudies.org/). ```{r one, fig.width=7.0, fig.height=5.5, warning=FALSE, message=FALSE} library(CGPfunctions) # library(CHAID) library(dplyr) library(knitr) ### fit tree to subsample see ?chaid ## set.seed(290875) ## USvoteS <- USvote[sample(1:nrow(USvote), 1000),] ## ctrl <- chaid_control(minsplit = 200, minprob = 0.1) ## chaidUS <- chaid(vote3 ~ ., data = USvoteS, control = ctrl) print(chaidUS) plot(chaidUS) ``` ## Getting more detailed But what happens if you want to investigate your results more closely? I actually had at least one reader of my blog posts point out that [some other statistical packages](https://www.ibm.com/support/knowledgecenter/en/SSLVMB_23.0.0/spss/tutorials/tree_credit_treetable.html#tree_credit_treetable) produce more detailed information in a tabular format. Some additional things you may want to know that are actually contained in `chaidUS` but aren't especially easy to see from the default plot and print and aren't necessarily easy to ferret out of the `chaidUS` object: 1. It's clear from our call that we fed `chaid` 1,000 random rows of the dataset `USvote`. It must be safe to assume that's how many valid cases there were right? The documentation is mute on how it handles missing cases. 2. There's information about counts and frequencies in the terminal nodes (3, 4, 6, 8, 9) and we could manually calculate the answers to other questions like how many people voted for Bush in node #9 (115 * 40.9% = 47)? How many total voters are in node #2 (311 + 249 = 560)? But getting more information gets increasingly tedious. At node #2 what was the breakdown of votes for Bush -v- Gore (hint 245 -v- 315 respectively). 3. It would also be nice to have easy access to the results of the $\chi^2$ tests that are the inherent workhorse of CHAID. We know that `marstat` was selected as the first split by virtue of having the smallest `p value` after a Bonferroni adjustment, but what were the results? `chaid_table` attempts to provide much more granular information in a tibble and also make it possible for you to derive even more nuanced questions through piping operations. The simplest call is just to feed it the name of the object after it has been processed by `CHAID`. That object will be of class "constparty" "party". ```{r simple2, fig.width=7.0, fig.height=3.5} # simplest use --- chaidUS is included in the package class(chaidUS) chaid_table(chaidUS) mychaidtable <- chaid_table(chaidUS) ``` I debated the wisdom of providing tables as output in the manner I found most useful and aesthetically pleasing but in the end decided to simply provide the tibble and let the user decide what and how to format. ## Example uses Some easy examples using `kable` and `dplyr`. ```{r simple3} mychaidtable %>% select(nodeID:ruletext) %>% kable() # Just node #2 show percentage mychaidtable %>% select(nodeID:ruletext) %>% filter(nodeID == 2) %>% mutate(pctBush = Bush/NodeN * 100) %>% kable(digits = 1) # Just the children of node #5 mychaidtable %>% select(nodeID:ruletext) %>% filter(parent == 5) %>% kable() # stats for all splits including raw (unadjusted) p value mychaidtable %>% select(nodeID, NodeN, split.variable:rawpvalue) %>% filter(!is.na(split.variable)) %>% kable() ``` Hopefully those are enough examples to get your creative juices going. ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. I hope you've found this useful. I am always open to comments, corrections and suggestions. Chuck ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/vignettes/Using-chaid_table.Rmd
--- title: "Using newggslopegraph" author: "Chuck Powell" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Using newggslopegraph} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- This function is designed to automate the process of producing a [Tufte style slopegraph](https://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0003nk) using `ggplot2`. I've been aware of slopegraphs and bumpcharts for quite some time, and I certainly am aware of [Tufte's work](https://www.edwardtufte.com/tufte/). As an amateur military historian I've always loved, for example, [his poster](https://www.edwardtufte.com/tufte/posters) depicting Napoleon's Russian Campaign. So when I saw the article from [Murtaza Haider](https://www.r-bloggers.com/author/murtaza-haider/) titled *"Edward Tufte’s Slopegraphs and political fortunes in Ontario"* I just had to take a shot at writing a function. To make it a little easier to get started with the function I have taken the liberty of providing the cancer data in a format where it is immediately usable. Please see `?newcancer`. ## Installation and setup Long term I'll try and ensure the version on `CRAN` is well maintained but for now you're better served by grabbing the current version from GITHUB. ```{r setup} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) # Install from CRAN # install.packages("CGPfunctions") # Or the development version from GitHub # install.packages("devtools") # devtools::install_github("ibecav/CGPfunctions") library(CGPfunctions) library(tidyr) library(dplyr) ``` ## Simple examples If you're unfamiliar with slopegraphs or just want to see what the display is all about the dataset I've provided can get you started in one line ```{r ggslope1, fig.height=10, fig.width=7} newggslopegraph(newcancer,Year,Survival,Type) ``` Optionally you can provide important label information through `Title`, `Subtitle`, and `Caption` arguments. You can suppress them all together by setting them `= NULL` but since I think they are very important the default is to gently remind you, that you have not provided any information. Let's provide a title and sub-title but skip the caption. ```{r ggslope2, fig.height=10, fig.width=7} newggslopegraph(dataframe = newcancer, Times = Year, Measurement = Survival, Grouping = Type, Title = "Estimates of Percent Survival Rates", SubTitle = "Based on: Edward Tufte, Beautiful Evidence, 174, 176.", Caption = NULL ) ``` ## How it all works It's all well and good to get the little demo to work, but it might be useful for you to understand how to extend it out to data you're interested in. You'll need a dataframe with at least three columns. The function will do some basic error checking and complain if you don't hit the essentials. 1. `Times` is the column in the dataframe that corresponds to the x axis of the plot and is normally a set of moments in time expressed as either characters, factors or ordered factors (in our case `newcancer$Year`. If it is truly time series data (especially with a lot of dates you're much better off using an R function purpose built for that). In `newcancer` it's an ordered factor, mainly because if we fed the information in as character the sort order would be `Year 10, Year 15, Year 20, Year 5` which is very suboptimal. A command like `newcancer$Year <- factor(newcancer$Year,levels = c("Year.5", "Year.10", "Year.15", "Year.20"), labels = c("5 Year","10 Year","15 Year","20 Year"), ordered = TRUE)` would be the way to force things they way you want them. 2. `Measurement` is the column that has the actual numbers you want to display along the y axis. Frequently that's a percentage but it could just as easily be any number. Watch out for scaling issues here you'll want to ensure that its not disparate. In our case `newcancer$Survival` is the percentage of patients surviving at that point in time, so the maximum scale is 0 to 100. 3. `Grouping` is what controls how many individual lines are portrayed. Every attempt is made to color them and label them in ways that lead to clarity but eventually you can have too many. In our example case the column is `newcancer$Type` for the type of cancer or location. ## Another quick example This is loosely based off a blog post from [Murtaza Haider titled “Edward Tufte’s Slopegraphs and political fortunes in Ontario”](https://www.r-bloggers.com/author/murtaza-haider/) that led to my developing this function [chronicled here](https://ibecav.github.io/slopegraph/). In this case we're going to plot the percent of the vote captured by some Canadian political parties. > The data is loosely based on real data but is not actually accurate. `moredata$Date` is the hypothetical polling date as a factor (in this case `character` would work equally well). `moredata$Party` is the various political parties and `moredata$Pct` is the percentage of the vote they are estimated to have. ```{r ggslope3, fig.height=5, fig.width=5} moredata <- structure(list(Date = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("11-May-18", "18-May-18", "25-May-18"), class = "factor"), Party = structure(c(5L, 3L, 2L, 1L, 4L, 5L, 3L, 2L, 1L, 4L, 5L, 3L, 2L, 1L, 4L), .Label = c("Green", "Liberal", "NDP", "Others", "PC"), class = "factor"), Pct = c(42.3, 28.4, 22.1, 5.4, 1.8, 41.9, 29.3, 22.3, 5, 1.4, 41.9, 26.8, 26.8, 5, 1.4)), class = "data.frame", row.names = c(NA, -15L)) #tail(moredata) newggslopegraph(moredata,Date,Pct,Party, Title = "Notional data", SubTitle = NULL, Caption = NULL) ``` There are a plethora of formatting options. See `?newggslopegraph` for all of them. Here's a few. ```{r ggslope4, fig.height=5, fig.width=5} newggslopegraph(moredata, Date, Pct, Party, Title = "Notional data", SubTitle = "none", Caption = "imaginary", LineColor = "gray", LineThickness = .5, YTextSize = 4 ) ``` The most complex is `LineColor` where you can do the following if you want to highlight the difference between the Liberal and NDP parties while making the other three less prominent... ```{r ggslope5, fig.height=5, fig.width=5} newggslopegraph(moredata, Date, Pct, Party, Title = "Notional data", SubTitle = "none", Caption = "imaginary", LineColor = c("Green" = "gray", "Liberal" = "green", "NDP" = "red", "Others" = "gray", "PC" = "gray"), LineThickness = .5, YTextSize = 4 ) ``` ## Slopegraph Best Practices 1. Scaling -- this function plots to scale on an actual scale. 2. If the datapoints or labels are bunching up, expand the vertical size of the plot as necessary. 3. Names of the items on both the left-hand and right-hand axes are aligned, to make vertical scanning of the items’ names easier. 4. Many suggest using a thin, light gray line to connect the data. A too-heavy line is unnecessary and will make the chart harder to read. 4. When a chart features many slope intersections, judicious use of color can avoid what Ben Fry describes as the "pile of sticks" phenomenon (Visualizing Data, 121). 5. A table (with more statistical detail) might be a good complement to use alongside the slopegraph. As Tufte notes: “The data table and the slopegraph are colleagues in explanation not competitors. One display can serve some but not all functions.” ## One last set of data Also from Tufte, this is data about a select group of countries Gross Domestic Product (GDP). I'll use it to show you a tricky way to highlight certain countries without making a named vector with `LineColor = c(rep("gray",3), "red", rep("gray",3), "red", rep("gray",10))` the excess vector entries are silently dropped... The bottom line is that `LineColor` is simply a character vector that you can fill any way you choose. ```{r ggslope6, fig.height=12, fig.width=6} newggslopegraph(newgdp, Year, GDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = c(rep("gray",3), "red", rep("gray",3), "red", rep("gray",10)) ) ``` Finally, let me take a moment about crowding and labeling. I've made every effort to try and deconflict the labels on the left and right axis (in this example the `Country`) and that should work automatically as you resize your plot dimensions. ** pro tip - if you use `RStudio` you can press the `zoom` icon and then use the rescaling of the window to see best choices **. But the numbers (`GDP`) are a different matter and there's no easy way to ensure separation in a case like this data. There's a decent total spread from 57.4 to 20.7 and some really close measurements like France, Belgium, and Germany on the right side. My suggestion is in a case like this one you create a new column in your dataframe with two significant places. So specifically it would be `newgdp$rGDP <- signif(newgdp$GDP, 2)`. In my testing, at least, I've found this helps without creating inaccuracy and not causing you to try and "stretch" vertically to disambiguate the numbers. This time I'll also use `LineColor` to highlight how Canada, Finland and Belgium fare from 1970 to 1979. Then to demonstrate how flexible `LineColor` really is I'll use some `tidyverse` tools to build a named list of countries and colors. The country's line color will be determined by whether the difference between 1979 is positive, near neutral or negative. ```{r ggslope7, fig.height=7, fig.width=6} newgdp$rGDP <- signif(newgdp$GDP, 2) newggslopegraph(newgdp, Year, rGDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = c(rep("gray",6), rep("red",2), "red", rep("gray",10)) ) custom_colors <- tidyr::pivot_wider(newgdp, id_cols = Country, names_from = Year, values_from = GDP) %>% mutate(difference = Year1979 - Year1970) %>% mutate(trend = case_when( difference >= 2 ~ "green", difference <= -1 ~ "red", TRUE ~ "gray" ) ) %>% select(Country, trend) %>% tibble::deframe() custom_colors newggslopegraph(newgdp, Year, rGDP, Country, Title = "Gross GDP", SubTitle = NULL, Caption = NULL, LineThickness = .5, YTextSize = 4, LineColor = custom_colors ) ``` ### Leaving Feedback If you like CGPfunctions, please consider Filing a GitHub issue by [leaving feedback here](https://github.com/ibecav/CGPfunctions/issues), or by contacting me at ibecav at gmail.com by email. ### License <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International License</a>.
/scratch/gouwar.j/cran-all/cranData/CGPfunctions/vignettes/Using-newggslopegraph.Rmd
#' @title CGR #' @description Compound Growth Rate for Capturing the Growth Rate Over the Period #' #' @param variable Time series data taken for the study #' @param data Name of the data taken for the study #' @param verbose Logical. If TRUE, the function prints detailed information about its progress. Default is FALSE. #' #' @return Returns a list containing the Compound growth rate for capturing the growth rated over the period and other model parameters. #' The list includes: #' \itemize{ #' \item \code{CGR}: Growth rate calculated for the data. #' \item \code{AoS}: The value derived by taking anti log of the slope of exponential model. #' } #' @examples{ #' library(CGR) #' years <- 1:50 #' value<-rnorm(length(years),100, 50) #' data <- data.frame(Year = years, Sales = round(value)) #' CGR_results <- CGR(variable = data$Sales, data = data) #' print(CGR_results) #' } #' @export #' #' @references #' #' \itemize{ #'\item • Shankar, S. V., Chandel, A., Gupta, R. K., Sharma, S., Chand, H., Kumar, R., ... & Gowsar, S. N. (2023). Corrigendum: Exploring the dynamics of arrivals and prices volatility in onion (Allium cepa) using advanced time series techniques. Frontiers in Sustainable Food Systems, 7, 1290515. DOI: 10.3389/fsufs.2023.1208898 #' } CGR <- function(variable, data, verbose = FALSE) { y <- variable x <- seq_along(y) Model <- stats::lm(log(y) ~ x) Coefficient <- stats::coef(Model) Slope <- Coefficient[2] AoS <- base::exp(Slope) Growthrate <- (AoS - 1) * 100 if(verbose) { s <- summary(Model) message("Model Summary:\n") print(s) } results <- data.frame("CGR in percentage" = Growthrate, "Antilog of Slope" = AoS) return(results) }
/scratch/gouwar.j/cran-all/cranData/CGR/R/CGR.R
ATE_est = function(fY,fw,fA,fp){ t_ATE = fY*fw tt_ATE = ( ( sum(t_ATE[fA==1]) / sum(fw[fA==1]) ) - ( sum(t_ATE[fA==0]) / sum(fw[fA==0]) ) ) return(tt_ATE) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/ATE_est.R
#' @title Causal Inference with High-Dimensional Error-Prone Covariates and #' Misclassified Treatments #' #' @description The package CHEMIST, referred to Causal inference with High-dimsensional Error- #' prone Covariates and MISclassified Treatments, aims to deal with the average #' treatment effect (ATE), where the data are subject to high-dimensionality and #' measurement error. This package primarily contains two functions: one is #' Data_Gen that is applied to generate artificial data, including potential #' outcomes, error-prone treatments and covariates, and the other is FATE that is #' used to estimate ATE with measurement error correction. #' @details This package aims to estimate ATE in the presence of high-dimensional and #' error-prone data. The strategy is to do variable selection by feature screening #' and general outcome-adaptive lasso. After that, measurement error in #' covariates are corrected. Finally, with informative and error corrected data #' obtained, the propensity score can be estimated and can be used to estimate #' ATE by the inverse probability weight approach. #' #' @return CHEMIST_package #' #' @export CHEMIST_package<-function(){return(CHEMIST_package="CHEMIST_package") }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/CHEMIST-package.R
#' @title Generation of Artificial Data #' #' @description This function shows the demonstration of data generation based on some #' specific and commonly used settings, including exponential family distributed #' potential outcomes, error-prone treatments, and covariates. In this function, #' users can specify different magnitudes of measurement error and relationship #' between outcome, treatment, and covariates. #' #' @param X The input of n x p dimensional matrix of true covariates, where n is #' sample size and p is number of covariates. Users can customize the data structure #' and distribution. #' #' @param alpha A vector of the parameters that reflects the relationship between #' treatment model and covariates. The dimension of \code{alpha} should be equal to the #' dimension of \code{beta}. If \code{alpha} and \code{beta} have the same nonzero #' components, then we call them Xc (covariates associated with both outcome and treatment). #' If components in \code{alpha} are zero but the same components in \code{beta} are #' nonzero, we call them Xp (covariates associated with outcome only), If components #' in \code{alpha} are nonzero but the same components in \code{beta} are zero, we #' call them Xi (covariates associated with treatment only). #' For example, if \code{alpha = c(2,2,0,0,1,1)} and \code{beta = c(3,3,1,1,0,0)}, then #' the first two components are Xc, the middle two components are Xp, and the last two #' components are Xi. #' #' @param beta A vector of the parameters that reflects the relationship between #' outcome and covariates. The dimension of \code{alpha} should be equal to the #' dimension of \code{beta}. If \code{alpha} and \code{beta} have the same nonzero #' components, then we call them Xc (covariates associated with both outcome and treatment). #' If components in \code{alpha} are zero but the same components in \code{beta} are #' nonzero, we call them Xp (covariates associated with outcome only), If components #' in \code{alpha} are nonzero but the same components in \code{beta} are zero, we #' call them Xi (covariates associated with treatment only). #' For example, if \code{alpha = c(2,2,0,0,1,1)} and \code{beta = c(3,3,1,1,0,0)}, then #' the first two components are Xc, the middle two components are Xp, and the last two #' components are Xi. #' #' @param theta The scalar of the parameter used to link outcome and #' treatment. #' #' @param a A weight of \code{cov_e} in the measurement error model #' W = cov_e*a + X + e, where W is observed covariates with measurement error, #' X is actual covariates, and e is noise term with covaraince matrix \code{cov_e}. #' #' @param sigma_e \code{sigma_e} is the common diagonal entries of covariance #' matrix in the measurement error model. #' #' @param e_distr Distribution of the noise term in the classical measurement #' error model. The input "normal" refers to the normal distribution with mean #' zero and covariance matrix with diagonal entries \code{sigma_e}. The scalar input "v" #' represents t-distribution with degree of freedom v. #' #' @param num_pi Settings of misclassification probability with option 1 or 2. #' \code{num_pi = 1} gives that pi_01 equals pi_10, and \code{num_pi = 2} refers to that #' pi_01 is not equal to pi_10. #' #' @param delta The parameter that determines number of treatment with measurement #' error. \code{delta = 1} has equal number of treatment with and without measurement #' error. We set \code{default = 0.5} since it has smaller number of treatment who has #' measurement error. #' #' @param linearY The boolean option that determines the relationship between #' outcome and covariates. \code{linearY = TRUE} gives linear relationship with a #' vector of parameters \code{alpha}, \code{linearY = FALSE} refers to non linear #' relationship between outcome and covariates, where the sin function is specified on #' Xc and the exponential function is specified on Xp. #' #' @param typeY The outcome variable with exponential family distribution #' "binary", "pois" and "cont". \code{typeY = "binary"} refers to binary random #' variables, \code{typeY = "pois"} refers to Poisson random variables, and #' \code{typeY = "cont"} refers to normally distributed random variables. #' #' @return \item{Data}{A n x (p+2) matrix of the original data without measurement error, #' where n is sample size and the first p columns are covariates with the order being #' Xc (the covariates associated with both treatment and outcome), #' Xp (the covariates associated with outcome only), #' Xi (the covariates associated with treatment only), #' Xs (the covariates independent of outcome and treatment), #' the last second column is treatment, and the last column is outcome.} #' #' @return \item{Error_Data}{A n x (p+2) matrix of the data with measurement error in covariates #' and treatment, where n is sample size and the first p columns are covariates #' with the order being #' Xc (the covariates associated with both treatment and outcome), #' Xp (the covariates associated with outcome only), #' Xi (the covariates associated with treatment only), #' Xs (the covariates independent of outcome and treatment), #' the last second column is treatment, and the last column is outcome.} #' #' @return \item{Pi}{A n x 2 matrix containing two misclassification probabilities pi_10 = #' P(Observed Treatment = 1 | Actual Treatment = 0) and pi_01 = #' P(Observed Treatment = 0 | Actual Treatment = 1) in columns.} #' #' @return \item{cov_e}{A covariance matrix of the measurement error model.} #' #' @examples #' ##### Example 1: A multivariate normal continuous X with linear normal Y ##### #' #' ## Generate a multivariate normal X matrix #' mean_x = 0; sig_x = 1; rho = 0 #' Sigma_x = matrix( rho*sig_x^2,nrow=120 ,ncol=120 ) #' diag(Sigma_x) = sig_x^2 #' Mean_x = rep( mean_x, 120 ) #' X = as.matrix( mvrnorm(n = 60,mu = Mean_x,Sigma = Sigma_x,empirical = FALSE) ) #' #' ## Data generation setting #' ## alpha: Xc's scale is 0.2 0.2 and Xi's scale is 0.3 0.3 #' ## so this refers that there is 2 Xc and Xi #' ## beta: Xc's scale is 2 2 and Xp's scale is 2 2 #' ## so this refers that there is 2 Xc and Xp #' ## rest with following setup #' Data_fun <- Data_Gen(X, alpha = c(0.2,0.2,0,0,0.3,0.3), beta = c(2,2,2,2,0,0) #' , theta = 2, a = 2, sigma_e = 0.75, e_distr = 10, num_pi = 1, delta = 0.8, #' linearY = TRUE, typeY = "cont") #' #' ##### Example 2: A uniform X with non linear binary Y ##### #' #' ## Generate a uniform X matrix #' n = 50; p = 120 #' X = matrix(NA,n,p) #' for( i in 1:p ){ X[,i] = sample(runif(n,-1,1),n,replace=TRUE ) } #' X = scale(X) #' #' ## Data generation setting #' ## alpha: Xc's scale is 0.1 and Xi's scale is 0.3 #' ## so this refers that there is 1 Xc and Xi #' ## beta: Xc's scale is 2 and Xp's scale is 3 #' ## so this refers that there is 1 Xc and Xp #' ## rest with following setup #' Data_fun <- Data_Gen(X, alpha = c(0.1,0,0.3), beta = c(2,3,0) #' , theta = 1, a = 2, sigma_e = 0.5, e_distr = "normal", num_pi = 2, delta = 0.5, #' linearY = FALSE, typeY = "binary") #' #' @export #' @importFrom stats "rgamma" "rt" "rbinom" "rpois" "rnorm" #' @importFrom MASS "mvrnorm" #' @importFrom LaplacesDemon "rmvt" Data_Gen <- function(X,alpha,beta,theta,a,sigma_e,e_distr="normal",num_pi,delta,linearY,typeY){ Data = NULL X=X n=nrow(X) p=ncol(X) delta=delta theta=theta a=a sigma_e=sigma_e var.list2=c() scale_list = as.data.frame(rbind(alpha,beta)) colnames(scale_list)[ which(scale_list[1,]*scale_list[2,]!=0 ) ] = "Xc" colnames(scale_list)[ which(scale_list[1,]==0 ) ] = "Xp" colnames(scale_list)[ which(scale_list[2,]==0 ) ] = "Xi" pC = sum(colnames(scale_list)=="Xc" ) # pC: associate with both pP = sum(colnames(scale_list)=="Xp" ) # pP: associate with outcome pI = sum(colnames(scale_list)=="Xi" ) # pI: associate with treatment scale_1 = c( unlist( scale_list[1,colnames(scale_list)=="Xc"] ) ) scale_2 = c( unlist( scale_list[1,colnames(scale_list)=="Xi"] ) ) scale_3 = c( unlist( scale_list[2,colnames(scale_list)=="Xc"] ) ) scale_4 = c( unlist( scale_list[2,colnames(scale_list)=="Xp"] ) ) pS = p - (pC+pI+pP) # pS: associate with neither var.list2 = c( paste( "Xc", 1:pC, sep ="") , paste( "Xp", 1:pP, sep ="") , paste( "Xi", 1:pI, sep =""), paste( "XS", 1:pS, sep ="")) Beta0 = rgamma(n,5,5)-delta Gamma0 = rgamma(n,5,5)-delta #delta=1 has equal num 1 0 ,default 0.5 since has small pi10 pi_10 = 1-exp(Beta0)/ (1+exp(Beta0)) pi_01 = 1-exp(Gamma0)/ (1+exp(Gamma0)) if(num_pi==1){pi_10=pi_01} #generate data colnames(X) = var.list2 #generate measurement error for X\ W = matrix(NA,n,p) cov_e = matrix(0,p,p) diag(cov_e) = sigma_e mean_e = rep(0,p) if(e_distr == "normal"){ e = mvrnorm(n = n, mu = mean_e, Sigma = cov_e) W = sigma_e*a + X + e } else{ e = rmvt(n = n, mu = mean_e, S=cov_e, df=e_distr) W = sigma_e*a + X + e } # set associate with treatment prob = rowSums( cbind( X[,grepl("Xc", colnames(X))]*scale_1 , X[,grepl("Xi", colnames(X))]*scale_2 ) ) prob = exp(prob)/(1+exp(prob)) D = (prob >0.5)*1 #D = rbinom(n, size = 1,prob) D_star = rep(0,n) for( i in 1:n){ pi_matrix = matrix( c(1-pi_10[i],pi_10[i],pi_01[i],1-pi_01[i]) ,nrow=2,ncol=2) prob_star = pi_matrix %*% rbind(prob[i],1-prob[i]) D_star[i] = (prob_star[1,]>prob_star[2,])*1 } if(linearY == TRUE){ CP_vec = rowSums( cbind( X[,grepl("Xc", colnames(X))]*scale_3 , X[,grepl("Xp", colnames(X))]*scale_4) ) } else{ CP_vec = rowSums( cbind(sin(X[,grepl("Xc", colnames(X))])*scale_3 , exp(X[,grepl("Xp", colnames(X))])*scale_4)) } #set associate with outcome if(typeY == "binary") { prob = exp(D*theta + CP_vec ) /(1+exp(D*theta + CP_vec )) #y = rbinom(n, size = 1,prob ) y = (prob >0.5)*1 #TRUE ATE prob1 = exp(theta + CP_vec ) /(1+exp(theta + CP_vec )) prob0 = exp(CP_vec) /(1+exp(CP_vec )) #ATE =mean(rbinom(n,1,prob1)) -mean(rbinom(n,1,prob0)) ATE =mean((prob1 >0.5)*1) -mean((prob0 >0.5)*1) } else if(typeY == "pois"){ lam = abs(D*theta + CP_vec ) y = rpois(n,lam) #TRUE ATE lam1 = abs(theta + CP_vec ) lam0 = abs(CP_vec ) ATE = mean(rpois(n,lam1)) -mean(rpois(n,lam0)) } else { y = D*theta + CP_vec +rnorm(n,0,1) #TRUE ATE ATE = mean(theta+CP_vec +rnorm(n,0,1))-mean(CP_vec +rnorm(n,0,1)) } Data = as.data.frame(cbind(X,D,y) ) colnames(Data) <- c(var.list2,"D","Y") Error_Data = as.data.frame(cbind(W,D_star,y) ) colnames(Error_Data) <- c(var.list2,"D","Y") return( list(Data=Data, Error_Data = Error_Data, Pi = cbind(pi_10,pi_01), cov_e = cov_e) ) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/Data_Gen.R
#' @title Estimation of ATE under high-dimensional error-prone data #' #' @description This function aims to estimate ATE by selecting informative #' covariates and correcting for measurement error in covariates and #' misclassification in treatments. The function FATE reflects the strategy of #' estimation method: Feature screening, Adaptive lasso, Treatment adjustment, #' and Error correction for covariates. #' #' @param Data A n x (p+2) matrix of the data, where n is sample size and the first #' p columns are covariates with the order being #' Xc (the covariates associated with both treatment and outcome), #' Xp (the covariates associated with outcome only), #' Xi (the covariates associated with treatment only), #' Xs (the covariates independent of outcome and treatment), #' the last second column is treatment, and the last column is outcome. #' #' @param cov_e Covariance matrix in the measurement error model. #' #' @param Consider_D Feature screening with treatment effects accommodated. #' \code{Conidser_D = TRUE} refers to feature screening with A and (1-A) incorporated. #' \code{Consider_D = FALSE} will not multiply with A and (1-A). #' #' @param pi_10 Misclassifcation probability is #' P(Observed Treatment = 1 | Actual Treatment = 0). #' #' @param pi_01 Misclassifcation probability is #' P(Observed Treatment = 0 | Actual Treatment = 1). #' #' @return \item{ATE}{A value of the average treatment effect.} #' #' @return \item{wAMD}{A weighted absolute mean difference.} #' #' @return \item{Coef_prop_score}{A table containing coefficients of propensity score.} #' #' @return \item{Kersye_table}{The selected covariates by feature screening.} #' #' @return \item{Corr_trt_table}{A summarized table containing corrected treatment.} #' #' @examples #' ##### Example 1: Input the data without measurement correction ##### #' #' ## Generate a multivariate normal X matrix #' mean_x = 0; sig_x = 1; rho = 0; n = 50; p = 120 #' Sigma_x = matrix( rho*sig_x^2 ,nrow=p ,ncol=p ) #' diag(Sigma_x) = sig_x^2 #' Mean_x = rep( mean_x, p ) #' X = as.matrix( mvrnorm(n ,mu = Mean_x,Sigma = Sigma_x,empirical = FALSE) ) #' #' ## Data generation setting #' ## alpha: Xc's scale is 0.2 0.2 and Xi's scale is 0.3 0.3 #' ## so this refers that there is 2 Xc and Xi #' ## beta: Xc's scale is 2 2 and Xp's scale is 2 2 #' ## so this refers that there is 2 Xc and Xp #' ## rest with following setup #' Data_fun <- Data_Gen(X, alpha = c(0.2,0.2,0,0,0.3,0.3), beta = c(2,2,2,2,0,0) #' , theta = 2, a = 2, sigma_e = 0.75, e_distr = 10, num_pi = 1, delta = 0.8, #' linearY = TRUE, typeY = "cont") #' #' ## Extract Ori_Data, Error_Data, Pi matrix, and cov_e matrix #' Ori_Data=Data_fun$Data #' Pi=Data_fun$Pi #' cov_e=Data_fun$cov_e #' Data=Data_fun$Error_Data #' pi_01 = pi_10 = Pi[,1] #' #' ## Input data into model without error correction #' Model_fix = FATE(Data, matrix(0,p,p), Consider_D = FALSE, 0, 0) #' #' ##### Example 2: Input the data with measurement correction ##### #' #' ## Input data into model with error correction #' Model_fix = FATE(Data, cov_e, Consider_D = FALSE, Pi[,1],Pi[,2]) #' #' @export #' @importFrom stats "sd" "binomial" "coef" FATE <- function(Data, cov_e, Consider_D, pi_10, pi_01){ n = nrow(Data) pi_10 = pi_10 pi_01 = pi_01 if( Consider_D == TRUE){ kersye <- choose_p_D(Data, cov_e) } if( Consider_D == FALSE){ kersye <- choose_p(Data, cov_e) } kersye <- kersye[sort(names(kersye))] var.list = names( kersye ) # find the position of choose p for cov_e p = length(var.list) pos = c() for(i in 1:length(var.list)){ pos = c(pos, which( colnames(Data)==var.list[i]) ) } Data <- Data[ , c(var.list, "D", "Y") ] cov_e <- cov_e[pos,pos] colnames(Data)[length(Data)-1] <- "A" n.p=n+p ## set vector of possible lambda's to try # set lambda values for grid search. lambda_vec = c(-10, -5, -2, -1, -0.75, -0.5, -0.25, 0.25, 0.49) names(lambda_vec) = as.character(lambda_vec) ## lambda_n (n)^(gamma/2 - 1) = n^(gamma_convergence_factor) gamma_convergence_factor = 2 ## get the gamma value for each value in the lambda vector that corresponds to convergence factor gamma_vals = 2*(gamma_convergence_factor - lambda_vec + 1) names(gamma_vals) = names(lambda_vec) ## normalize covariates to have mean 0 and standard deviation 1 temp.mean = colMeans(Data[,var.list]) Temp.mean = matrix(temp.mean,ncol=length(var.list),nrow=nrow(Data),byrow=TRUE) Data[,var.list] = Data[,var.list] - Temp.mean temp.sd = apply(Data[var.list],FUN=sd,MARGIN=2) Temp.sd = matrix(temp.sd,ncol=length(var.list),nrow=nrow(Data),byrow=TRUE) Data[var.list] = Data[,var.list] / Temp.sd rm(list=c("temp.mean","Temp.mean","temp.sd","Temp.sd")) # weight for each variable for refined selection weight = kersye #betaXY <- weight mins = min(weight) maxs = max(weight) betaXY = (weight - mins) / (maxs-mins) betaXY[which(betaXY==0)] <- 10^-7 #betaXY <- weight/ max(weight) ## want to save ATE, wAMD and propensity score coefficients for each lambda value ATE = wAMD_vec =coeff_XA=NULL ATE = wAMD_vec = rep(NA, length(lambda_vec)) names(ATE) = names(wAMD_vec) = names(lambda_vec) coeff_XA = as.data.frame(matrix(NA,nrow=length(var.list),ncol=length(lambda_vec))) names(coeff_XA) = names(lambda_vec) rownames(coeff_XA) = var.list ## set the possible lambda2 value (taken from Zou and Hastie (2005)) S_lam=c(0,10^c(-2,-1.5,-1,-0.75,-0.5,-0.25,0,0.25,0.5,1)) ## want to save ATE, wAMD and propensity score coefficients for each lambda2 value WM_N=M_N=S_wamd=rep(NA,length(S_lam)) M_mat=matrix(NA,length(S_lam),p) colnames(M_mat)= var.list ## fix A's measurements error matrix_A = as.data.frame( matrix( Data$A,n,3)) colnames(matrix_A) = c("no fix A","fix A","get change") Data$A <- as.vector( ( Data$A - pi_10 ) / ( 1 - pi_10 - pi_01) ) Data$A = (Data$A > 0.5)*1 matrix_A[,2] = Data$A matrix_A[,3] = ifelse(matrix_A[,1]==matrix_A[,2] , " ", "fix" ) ## fix X's measurement error W = as.matrix( Data[ , c(var.list) ] ) mu_W = colMeans(W);length(mu_W) sigma_W = (1/(n-1)) * t(W-mu_W)%*%(W-mu_W) ; dim(sigma_W) #sigma_W = cov(W) for(i in 1: n){ Data[i, c(var.list) ] = mu_W + t( sigma_W-cov_e ) %*% solve(sigma_W) %*% (W[i,]-mu_W) } for (m in 1:length(S_lam)) { ## create augmented A and X lambda2=S_lam[m] I=diag(1,p,p) Ip=sqrt(lambda2)*I Anp=c(Data$A,rep(0,p)) Xnp=matrix(0,n+p,p) X=Data[,var.list] for (j in 1:p){ Xnp[,j]=c(X[,j],Ip[,j]) } newData=as.data.frame(Xnp) names(newData)=var.list newData$A=Anp ## want to save ATE, wAMD and propensity score coefficients for each lambda value ATE_try=ATE = wAMD_vec =coeff_XA=NULL; ATE_try=ATE = wAMD_vec = rep(NA, length(lambda_vec)) names(ATE) = names(wAMD_vec) = names(lambda_vec) coeff_XA = as.data.frame(matrix(NA,nrow=length(var.list),ncol=length(lambda_vec))) names(coeff_XA) = names(lambda_vec) rownames(coeff_XA) = var.list ## run GOAL with lqa using augmented data # weight model with all possible covariates included, this is passed into lasso function for( lil in names(lambda_vec) ){ il = lambda_vec[lil] ig = gamma_vals[lil] # create the outcome adaptive lasso penalty with coefficient specific weights determined by outcome model oal_pen = adaptive.lasso(lambda=n.p^(il),al.weights = abs(betaXY)^(-ig) ) # run outcome-adaptive lasso model with appropriate penalty X=as.matrix(newData[var.list]);y=as.vector(newData$A); logit_oal = lqa.default ( X,y, penalty=oal_pen, family=binomial(logit) ) # save propensity score coefficients !!!!adaptive elastic net coeff_XA[var.list,lil] = (1+lambda2)*coef(logit_oal)[var.list] # generate propensity score Data[,paste("f.pA",lil,sep="")]= expit(as.matrix(cbind(rep(1,n),Data[var.list]))%*%as.matrix((1+lambda2)*coef(logit_oal))) # create inverse probability of treatment weights for ATE Data[,paste("w",lil,sep="")] = create_weights(fp=Data[,paste("f.pA",lil,sep="")],fA=Data$A) # estimate weighted absolute mean different over all covaraites using this lambda to generate weights wAMD_vec[lil] = wAMD_function(DataM=Data,varlist=var.list,trt.var="A", wgt=paste("w",lil,sep=""),beta=betaXY)$wAMD # save ATE estimate for this lambda value ATE[lil] = ATE_est(fY=Data$Y,fw=Data[,paste("w",lil,sep="")],fA=Data$A) } # close loop through lambda values # print out wAMD for all the lambda values evaluated wAMD_vec # find the lambda value that creates the smallest wAMD tt = which.min(wAMD_vec) # print out ATE corresponding to smallest wAMD value ATE[tt][[1]] # save the coefficients for the propensity score that corresponds to smallest wAMD value GOAL.lqa.c=coeff_XA[,tt] names(GOAL.lqa.c) = var.list # check which covariates are selected #M_mat[m,]=ifelse(abs(coeff_XA[,tt])> 10^(-8),1,0) M_mat[m,]=coeff_XA[,tt] # save the ATE corresponding to smallest wAMD value M_N[m]=ATE[tt][[1]] # save the smallest wAMD value WM_N[m]=wAMD_vec[tt][[1]] } # find the optimal lambda2 value that creates the smallest wAMD ntt= which.min(WM_N) # save the ATE corresponding the optimal lambda2 value GOAL_ATE =M_N[ntt] # save the propensity score coefficients corresponding the optimal lambda2 value GOAL.lqa.c=M_mat[ntt,] Coefficients_propensity_score_table = as.data.frame( matrix(GOAL.lqa.c,length(GOAL.lqa.c),3) ) colnames(Coefficients_propensity_score_table) = c("Covariate","Coefficients Propensity Score","Significantness") Coefficients_propensity_score_table[,1] = var.list Coefficients_propensity_score_table[,3] = ifelse(abs(Coefficients_propensity_score_table[,3])> 10^(-8),"***"," ") # save wAMD value corresponding the optimal lambda2 value wAMD_vec=WM_N[ntt] return( list( ATE = GOAL_ATE , wAMD = wAMD_vec, Coef_prop_score = Coefficients_propensity_score_table, Kersye_table = kersye , Corr_trt_table = matrix_A ) ) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/FATE.R
#' @importFrom stats "gaussian" adaptive.lasso <- function (lambda = NULL, al.weights = NULL, ...) { lambda.check (lambda) if (length (lambda) != 1) ## Check on dimensionality of lambda stop ("lambda must be a scalar \n") names (lambda) <- "lambda" if (is.null (al.weights)) al.weights <- 1 getpenmat <- function (beta = NULL, c1 = lqa.control()$c1, ...) { if (is.null (beta)) stop ("'beta' must be the current coefficient vector \n") if (c1 < 0) stop ("'c1' must be non-negative \n") penmat <- lambda * diag (al.weights / (sqrt (beta^2 + c1))) * as.integer (beta != 0) penmat } first.derivative <- function (beta, ...) { p <- length (beta) return (rep (lambda * al.weights, p)) } structure (list (penalty = "adaptive.lasso", lambda = lambda, getpenmat = getpenmat, first.derivative = first.derivative), class = "penalty") }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/adaptive.lasso.R
#' @importFrom XICOR "calculateXI" #' @importFrom stats "var" choose_p <- function(test_data,cov_e){ data = test_data xi = c() res = c() d = 0 C = 0 n = nrow(data) p = ncol(data)-2 for( i in 1:p){ w = data[,i] var_e = cov_e[i,i] var_w = var(w) x = mean(w) + as.numeric( (var_w-var_e)*solve(var_w) )*(w-mean(w)) C = calculateXI(x, data$Y) xi = c(xi , C) } var.list = colnames(data)[1:p] names(xi) <- c( var.list ) d = round(n/log(n),0) selected_Var = sort(xi,decreasing = TRUE)[1:d] return(selected_Var) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/choose_p.R
#' @importFrom XICOR "calculateXI" #' @importFrom stats "var" choose_p_D <- function(test_data,cov_e){ data = test_data xi = c() res = c() d = 0 C = 0 n = nrow(data) p = ncol(data)-2 index0 <- which(data$D == 0) index1 <- which(data$D == 1) alpha = length(index0)/n for( i in 1:p){ w_0 = data[index0,i] var_e = cov_e[i,i] var_w_0 = var(w_0) #x_0 = mean(w_0) + as.numeric( (var_w_0-var_e)*solve(var_w_0) ) *(w_0-mean(w_0)) w_1 = data[index1,i] var_e = cov_e[i,i] var_w_1 = var(w_1) #x_1 = mean(w_1) + as.numeric( (var_w_1-var_e)*solve(var_w_1) ) *(w_1-mean(w_1)) x_0 = data[index0,i] x_1 = data[index1,i] C = alpha*calculateXI(x_0 , data$Y[index0] ) + (1-alpha)*calculateXI(x_1 , data$Y[index1]) xi = c(xi , C ) } var.list = colnames(data)[1:p] names(xi) <- c( var.list ) d = round(n/log(n),0) selected_Var = sort(xi,decreasing = TRUE)[1:d] return(selected_Var) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/choose_p_D.R
create_weights = function(fp,fA){ fw = (fp)^(-1) fw[fA==0] = (1 - fp[fA==0])^(-1) return(fw) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/create_weights.R
expit = function(x){ pr = ( exp(x) / (1+exp(x)) ) return(pr) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/expit.R
get.Amat <- function (initial.beta = NULL, penalty = NULL, intercept = TRUE, c1 = lqa.control()$c1, x = NULL, ...) { env <- NULL if (intercept) x <- x[,-1] if (is.null (initial.beta)) stop ("get.Amat: 'initial.beta' is missing.") if (is.null (penalty)) stop ("get.Amat: 'penalty' is missing.") nreg <- length (initial.beta) - as.integer (intercept) coefm0 <- if (intercept) initial.beta[-1] else initial.beta #### Computation of A.lambda: if (is.null (penalty$getpenmat)) { a.coefs <- if (is.null (penalty$a.coefs)) diag (nreg) # just built for the p regressors! (Intercept not accounted for!!!) else penalty$a.coefs (coefm0, env = env, x = x, ...) A.lambda <- matrix (0, nrow = nreg, ncol = nreg) xim0 <- drop (t (a.coefs) %*% coefm0) A.lambda2 <- drop (penalty$first.deriv (coefm0, env = env, x = x, ...) * as.integer (xim0 != 0) / sqrt (c1 + xim0^2)) Jseq <- 1 : ncol (a.coefs) l1 <- sapply (Jseq, function (Jseq) {which (a.coefs[,Jseq] != 0)}) # extracts the positions of elements != 0 in the columns of 'a.coefs' just.one <- which (sapply (Jseq, function (Jseq) {length (l1[[Jseq]]) == 1}) == TRUE) # extracts the column indices of 'a.coefs' with just one element != 0 less.sparse <- setdiff (Jseq, just.one) # extracts the column indices of 'a.coefs' with more than one element != 0 if (length (just.one) > 0) # <FIXME: Does not work if there are more than 'p' columns of 'a.coefs' with just one element != 0!> { jo2 <- rep (0, nreg) jo1 <- A.lambda2[just.one] ### extracts the elements corresponding with just.one sort1 <- sapply (just.one, function (just.one) {l1[[just.one]]}) ### bestimmt die Reihenfolge jo2[sort1] <- jo1 A.lambda <- A.lambda + diag (jo2) } for (i in less.sparse) { ci <- l1[[i]] a.ci <- a.coefs[ci, i] A.lambda[ci,ci] <- A.lambda[ci,ci] + A.lambda2[i] * outer (a.ci, a.ci) } } else A.lambda <- penalty$getpenmat (beta = coefm0, env = env, x = x, ...) # if the 'x' argument is not needed (e.g. for penalreg penalty) then it should be accounted for automatically... (hopefully ;-) if (intercept) { A.lambda <- cbind (0, A.lambda) A.lambda <- rbind (0, A.lambda) } A.lambda }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/get.Amat.R
lambda.check <- function (lambda) { if (is.null (lambda)) ## check for existence of attribute 'lambda' stop ("Tuning parameter lambda missing \n") if (any (lambda < 0)) ## check for non-negativity of lambda stop ("lambda must be non-negative \n") }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/lambda.check.R
lqa.control <- function (x = NULL, var.eps = .Machine$double.eps, max.steps = 5000, conv.eps = 1e-03, conv.stop = TRUE, c1 = 1e-08, digits = 5, ...) { ### x = NULL ... object of class 'lqa'. This optional argument is just included to be in line with the S3 class concept ### var.eps ... tolerance in checking for zero variance of some regressors ### max.steps ... maximum number of steps in the P-IRLS respective Boosting algorithms ### conv.eps ... tolerance for convergence break in parameter updating ### conv.stop ... whether or not to stop the iterations when estimated coefficients are converged ### digits ... number of digits to round the tuning parameter candidates as names in the 'loss.array' (in function 'cv.lqa') ### ... .... further arguments if (!is.numeric (var.eps) || var.eps < 0) stop ("value of var.eps must be >= 0") max.steps <- as.integer (max.steps) digits <- as.integer (digits) if (max.steps < 0) stop ("max.steps must be positive integer") if (!is.numeric (conv.eps) || conv.eps <= 0) stop ("value of conv.eps must be > 0") if (!is.logical (conv.stop)) stop ("conv.stop must be 'TRUE' or 'FALSE'") if (!is.numeric (c1) || c1 < 0) stop ("value of 'c1' must be >= 0") if (!is.numeric (digits) || digits < 0) stop ("value of 'digits' must be >= 0") list (var.eps = var.eps, max.steps = max.steps, conv.eps = conv.eps, conv.stop = conv.stop, digits = digits, c1 = c1) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/lqa.control.R
lqa.default <- function (x, y, family = gaussian (), penalty = NULL, method = "lqa.update2", weights = rep (1, nobs), start = NULL, etastart = NULL, mustart = NULL, offset = rep (0, nobs), control = lqa.control (), intercept = TRUE, standardize = TRUE, ...) { call <- match.call () ### Check for exponential family and link function: ### ----------------------------------------------- if (is.character (family)) family <- get (family, mode = "function", envir = parent.frame ()) if (is.function (family)) family <- family () if (is.null (family$family)) { print (family) stop ("'family' not recognized") } ### Check for quadratic penalty: ### ---------------------------- if (! (method == "nng.update")) { if (is.null (penalty)) stop ("penalty not specified \n") if (is.character (penalty)) penalty <- get (penalty, mode = "function", envir = parent.frame ()) if (is.function (penalty)) penalty <- penalty () if (is.null (penalty$penalty)) { print (penalty) stop ("'penalty' not recognized") } } ### Check for existence of 'method': ### -------------------------------- if (is.null (method)) stop ("method not specified") ### Check for column of ones in x if intercept == TRUE: ### --------------------------------------------------- if (intercept & (var (x[,1]) > control$var.eps)) x <- cbind (1, x) ### Standardization: ### ---------------- x <- as.matrix (x) xnames <- dimnames (x)[[2L]] ynames <- if (is.matrix (y)) rownames(y) else names(y) nobs <- nrow (x) nvars <- ncol (x) # number of coefficients in the predictor (including an intercept, if present) ones <- rep (1, nobs) mean.x <- drop (ones %*% x) / nobs # computes the vector of means if (intercept) # if an intercept is included in the model its corresponding element of mean.x is set to zero mean.x[1] <- 0 # (such that x[,1] is not getting centered (and also not standardized later on ...)) x.std <- scale (x, mean.x, FALSE) # centers the regressor matrix norm.x <- if (standardize) { norm.x <- sqrt (drop (ones %*% (x.std^2))) # computes the euclidean norm of the regressors nosignal <- apply (x, 2, var) < control$var.eps if (any (nosignal)) # modify norm.x for variables with too small a variance (e.g. the intercept) norm.x[nosignal] <- 1 norm.x } else rep (1, nvars) x.std <- scale (x.std, FALSE, norm.x) # standardizes the centered regressor matrix ### Call and get the (estimation) method: ### ------------------------------------- fit <- do.call (method, list (x = x.std, y = y, family = family, penalty = penalty, intercept = intercept, control = control, ...)) ### Back-Transformation of estimated coefficients: ### ---------------------------------------------- coef <- fit$coefficients if (intercept) { coef[1] <- coef[1] - sum (mean.x[-1] * coef[-1] / norm.x[-1]) coef[-1] <- coef[-1] / norm.x[-1] } else coef <- coef / norm.x ### Computation of some important statistics: ### ----------------------------------------- # Remark: The predictors are identical no matter whether we use standardized or unstandardized values, hence all statistics # based on the predictor eta are also equal eta <- drop (x %*% coef) mu <- family$linkinv (eta) mu.eta.val <- family$mu.eta (eta) wt <- sqrt ((weights * mu.eta.val^2) / family$variance (mu)) dev <- sum (family$dev.resids (y, mu, weights)) wtdmu <- sum (weights * y) / sum (weights) nulldev <- sum (family$dev.resids (y, wtdmu, weights)) n.ok <- nobs - sum (weights == 0) nulldf <- n.ok - as.integer (intercept) residuals <- (y - mu) / mu.eta.val xnames <- colnames (x) ynames <- names (y) names (residuals) <- names (mu) <- names (eta) <- names (weights) <- names (wt) <- ynames names (coef) <- xnames Amat <- fit$Amat Amat <- t (norm.x * t (norm.x * Amat)) # must be (quadratically) transformed in order to cope with the transformed parameter space if (is.null (fit$tr.H)) stop ("quadpen.fit: Element 'tr.H' has not been returned from 'method'") model.aic <- dev + 2 * fit$tr.H model.bic <- dev + log (nobs) * fit$tr.H resdf <- n.ok - fit$tr.H dispersion <- ifelse (!((family$family == "binomial") | (family$family == "poisson")), sum ((y - mu)^2 / family$variance (mu)) / (nobs - fit$tr.H), 1) fit <- list (coefficients = coef, residuals = residuals, fitted.values = mu, family = family, penalty = penalty, linear.predictors = eta, deviance = dev, aic = model.aic, bic = model.bic, null.deviance = nulldev, n.iter = fit$stop.at, best.iter = fit$m.stop, weights = wt, prior.weights = weights, df.null = nulldf, df.residual = resdf, converged = fit$converged, mean.x = mean.x, norm.x = norm.x, Amat = Amat, method = method, rank = fit$tr.H, x = x, y = y, fit.obj = fit, call = call, dispersion = dispersion) class (fit) <- c ("lqa", "glm", "lm") fit }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/lqa.default.R
lqa.update2 <- function (x, y, family = NULL, penalty = NULL, intercept = TRUE, weights = rep (1, nobs), control = lqa.control (), initial.beta, mustart, eta.new, gamma1 = 1, ...) { gamma <- gamma1 if (is.null (family)) stop ("lqa.update: family not specified") if (is.null (penalty)) stop ("lqa.update: penalty not specified") if (!is.null (dim (y))) stop ("lqa.update: y must be a vector") x <- as.matrix (x) converged <- FALSE n.iter <- control$max.steps eps <- control$conv.eps c1 <- control$c1 stop.at <- n.iter p <- ncol (x) nobs <- nrow (x) converged <- FALSE beta.mat <- matrix (0, nrow = n.iter, ncol = p) # to store the coefficient updates if (missing (initial.beta)) initial.beta <- rep (0.01, p) else eta.new <- drop (x %*% initial.beta) if (missing (mustart)) { etastart <- drop (x %*% initial.beta) eval (family$initialize) } if (missing (eta.new)) eta.new <- family$linkfun (mustart) # predictor for (i in 1 : n.iter) { beta.mat[i,] <- initial.beta mu.new <- family$linkinv (eta.new) # fitted values d.new <- family$mu.eta (eta.new) # derivative of response function v.new <- family$variance (mu.new) # variance function of the response weights <- d.new / sqrt (v.new) # decomposed elements (^0.5) of weight matrix W, see GLM notation x.star <- weights * x y.tilde.star <- weights * (eta.new + (y - mu.new) / d.new) A.lambda <- get.Amat (initial.beta = initial.beta, penalty = penalty, intercept = intercept, c1 = c1, x = x, ...) p.imat.new <- crossprod (x.star) + A.lambda # penalized information matrix chol.pimat.new <- chol (p.imat.new) # applying cholesky decomposition for matrix inversion inv.pimat.new <- chol2inv (chol.pimat.new) # inverted penalized information matrix beta.new <- gamma * drop (inv.pimat.new %*% t (x.star) %*% y.tilde.star) + (1 - gamma) * beta.mat[i,] # computes the next iterate of the beta vector if ((sum (abs (beta.new - initial.beta)) / sum (abs (initial.beta)) <= eps)) # check convergence condition { converged <- TRUE stop.at <- i if (i < n.iter) break } else { initial.beta <- beta.new # update beta vector eta.new <- drop (x %*% beta.new) } } Hatmat <- x.star %*% inv.pimat.new %*% t (x.star) tr.H <- sum (diag (Hatmat)) dev.m <- sum (family$dev.resids (y, mu.new, weights)) aic.vec <- dev.m + 2 * tr.H bic.vec <- dev.m + log (nobs) * tr.H if (!converged & (stop.at == n.iter)) cat ("lqa.update with ", penalty$penalty, ": convergence warning! (lambda = ", penalty$lambda, ")\n") fit <- list (coefficients = beta.new, beta.mat = beta.mat[1 : stop.at,], tr.H = tr.H, fitted.values = mu.new, family = family, Amat = A.lambda, converged = converged, stop.at = stop.at, m.stop = stop.at, linear.predictors = eta.new, weights = weights^2, p.imat = p.imat.new, inv.pimat = inv.pimat.new, x.star = x.star, v.new = v.new) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/lqa.update2.R
wAMD_function = function(DataM,varlist,trt.var,wgt,beta){ trt = untrt = diff_vec = rep(NA,length(beta)) names(trt) = names(untrt) = names(diff_vec) = varlist for(jj in 1:length(varlist)){ this.var = paste("w",varlist[jj],sep="") DataM[,this.var] = DataM[,varlist[jj]] * DataM[,wgt] trt[jj] = sum( DataM[DataM[,trt.var]==1, this.var ]) / sum(DataM[DataM[,trt.var]==1, wgt]) untrt[jj] = sum(DataM[DataM[,trt.var]==0, this.var]) / sum(DataM[DataM[,trt.var]==0, wgt]) diff_vec[jj] = abs( trt[jj] - untrt[jj] ) } wdiff_vec = diff_vec * abs(beta) wAMD = c( sum(wdiff_vec)) ret = list( diff_vec = diff_vec, wdiff_vec = wdiff_vec, wAMD = wAMD ) return(ret) }
/scratch/gouwar.j/cran-all/cranData/CHEMIST/R/wAMD_function.R
################################################################## # closest History Flow Field Forecasting # ################################################################## # Writen By Patrick Fleming as part of Navel Post Graduate Grant # # NAVSUP Grant No.: N00244-15-0052 # ################################################################## CHFF <-function(data,num,step){ #History,hlength,width){ dlength <-nrow(data) #set up an array to stor the forecasted values ave=1 #averaging slopes over ave points char=14 #char is the number of chararacteistics to consider forecasts <- matrix(data=0, nrow=(num),ncol=(2)) print("CHFF Closest History Flow Field Forecasting") # Define the x and y vectors from the data x <- data[1:(dlength),1] # remove the - num when done testing y <- data[1:(dlength),2] ########################################################################################## ##some initializing current<-0 xhs <- 0 ####################### history from data ############################################## hspace <- historyslopes(x,y,step,ave) size<-(length(hspace)/(2*7+2)) #print(size) ############################################################################################# # find the closest history structure<-standarddistance(char,hspace,size) ############################################################################################# # Transfer history to an updatable version before making forecasts fullhist <- matrix(data=0, nrow=(size+num), ncol=(16)) for(i in 1:size){ fullhist[i,15] <- hspace[i,15] fullhist[i,16] <- hspace[i,16] for(j in 1:(14)){ fullhist[i,j] <- hspace[i,j] }#j }#i ## define the first current full history for(i in 1:(16)) current[i]<-fullhist[size,i] ########################################################### # The forcast loop ########################################################### fullsize<-size for(ww in 1: (num)){ # Compute new x and y values from the change observed in the winning history newx<-current[15]+(fullhist[structure[3]+ww,1]) ## 18 in the winning position, x=1,y=5,dx=9,dy=13 newy<-current[16]+(fullhist[structure[3]+ww,8]) ################################################################################################# # Store the forecasted values of x and y forecasts[ww,1]<- newx forecasts[ww,2]<- newy ################################################################################################# # Update the the history # define a full updatable history #1 - 7 are the x slopes, 8-14 are the y slopes, 15 is the x value and 16 is the y value fullhist[size+1,1]<-newx-fullhist[1+size-step,15] fullhist[size+1,2]<-fullhist[size,1] fullhist[size+1,3]<-fullhist[size,2] fullhist[size+1,4]<-fullhist[size,3] fullhist[size+1,5]<-fullhist[size,4] fullhist[size+1,6]<-fullhist[size,5] fullhist[size+1,7]<-fullhist[size,6] fullhist[size+1,8]<-newy-fullhist[1+size-step,16] fullhist[size+1,9]<-fullhist[size,8] fullhist[size+1,10]<-fullhist[size,9] fullhist[size+1,11]<-fullhist[size,10] fullhist[size+1,12]<-fullhist[size,11] fullhist[size+1,13]<-fullhist[size,12] fullhist[size+1,14]<-fullhist[size,13] fullhist[size+1,15]<-newx fullhist[size+1,16]<-newy #### Update the new current history for(i in 1:16)current[i]<-fullhist[size+1,i] # Increase the size for the next forecast fullsize<-fullsize+1 } ## ww loop ######################################################################## #Close up plots # Last 10 Data points in black forecasts start in green and in red plot(data[(dlength-(10)):dlength,(1)],data[(dlength-(10)):dlength,(2)],col="black",pch=20,cex=.9, xlim=c(min(forecasts[1:num,1],data[(dlength-(10)):dlength,(1)]), max(forecasts[1:num,1],data[(dlength-(10)):dlength,(1)])), ylim=c(min(forecasts[1:num,2],data[(dlength-(10)):dlength,(2)]), max(forecasts[1:num,2],data[(dlength-(10)):dlength,(2)])), xlab="x",ylab="y") points(forecasts[1:num,1],forecasts[1:num,2],col="blue",cex=0.9) points(forecasts[1,1],forecasts[1,2],col="green",cex=0.9) points(forecasts[num,1],forecasts[num,2],col="red",cex=0.9) ################################################################################## #print the forecasted x and y values print("the X and y forecasts") print(forecasts) }#end of CPA function
/scratch/gouwar.j/cran-all/cranData/CHFF/R/CHFF.R
################################################################################################ ################################################################################################ ### Generate the history space and from Data ### Full History structure includes Current x, y values ### Current Delta x and Delta y ### ALong with Six Past Delta x and six Past Delta y ### Return a matrix with 16 collumns and the Number of rows = data length - 7* Step ################################################################################################ ################################################################## # Writen By Patrick Fleming as part of Navel Post Graduate Grant # # NAVSUP Grant No.: N00244-15-0052 # ################################################################## ################################################################################################ historyslopes <- function(x,y,step,ave){ # n = number of data points # n <- length(x) depth<-7 # hl the the history space length hl <- n-((depth*step)+ave-1) #initialize the Delta x and y storage deltax<-0 deltay<-0 ################################################################## #### make the history space for the x's and y's dx's and dy's history <- matrix(data=0, nrow=(hl), ncol=(2*depth+2)) ##################################################################### # there will be n-1 slopes (slope are not averaged over the step size ) for (i in 1:(n-ave)){ # 1,n-1 n-step =+step deltax[i] <- (x[i+ave]-x[i])/ave #dx[i+1] #+1] deltay[i] <- (y[i+ave]-y[i])/ave #dy[i+1] #+1] } ###################################################################### # FILL IN THE HISTORY SPACE MATRIX ###################################################################### for(i in 1:hl){ ################################### # FIRSTFILL IN THE X and Y VALUES history[i,15]<-x[i+depth*step+ave-1] history[i,16]<-y[i+depth*step+ave-1] ############################################################################################ # NOW FILL THE THE DELTA X AND DELTA Y VALUES FOR SINGle SIZED SLOPES (NOT AVERAGED) for(j in 1:depth){history[(i),j] <- deltax[i+depth*step-(1+(j-1)*step)]} ### Delta x for(j in 1:depth){history[(i),j+(depth)] <- deltay[i+depth*step-(1+(j-1)*step)]} ### delta y #for(j in 1:depth){history[(i),j] <- deltax[i+depth*step-(1+(j-1)*step)]} ### Delta x #for(j in 1:depth){history[(i),j+(depth)] <- deltay[i+depth*step-(1+(j-1)*step)]} ### delta y ######################################################################################### }#i #History row i: xi xi-1 xi-2 xi-3 , yi yi-1 yi-2 yi-3, dxi dxi-1 dxi-2 dxi-3 , dyi dyi-1 dyi-2 dyi-3 K<-length(history) #print(K) return(history) } # end of history space generator function
/scratch/gouwar.j/cran-all/cranData/CHFF/R/HistorySpace.R
################################################################################# ################################################################################# ## Standardized Distance Score with structure size of 16 ## Find the past history which is the best match for the most recent history. ################################################################################# # Writen By Patrick Fleming as part of Navel Post Graduate Grant # # NAVSUP Grant No.: N00244-15-0052 # ################################################################################# ################################################################################# standarddistance <-function(char,History,hlength){ #initialize some variables ################################################################################################################# nn <- 1 # how much short of current should we stop thist is to avoid small delta t from producing false positives snum<- char #14 # (number of structures checked is 2^snum-1) big<-2^snum-1 #largest sub structure size n <- hlength-1 #number of past histories dist<-0 # temporary distance storage # ################################################### # Comupute the Difference matrix D <- matrix(data=0, nrow=(n), ncol=(snum)) for(i in 1 : n) for(j in 1 :snum){ D[i,j]<-abs(History[hlength,j]-History[i,j]) } ################################################### #History structure matrix HS <- matrix(data=0, nrow=(snum), ncol=(big)) fHS <- matrix(data=0, nrow=(snum), ncol=(65535)) #r<-0 #i<-7 for(i in 1 : big){ for(j in 1 : snum){ HS[j,i]<-bitwAnd(1,bitwShiftR(i,j-1)) } } ####################################### #Compute the distance matrix DM<-matrix(data=0, nrow=n,ncol=(big)) DM<-D%*%HS ########################################################################## # Compute standard deviation and mean of each column of distance matrix # as well and the standardised distance matrix SDM<-matrix(data=0, nrow=n,ncol=(big)) stds<-0 mns<-0 sscore<-0 for( i in 1 : big){ # compute the standard deviation in distance from current within structure i stds[i] <- sd(DM[,i]) # compute the mean in distance from current within structure i mns[i] <- mean(DM[,i]) # compute max score for structure i (inverse of coefficient of variance) sscore[i] <- mns[i]/stds[i] # compute the Standardized distance martix SDM[,i] <- (DM[,i]/stds[(i)]) }#end i ############################################## # Comupte the complete history score matrix CHS<-matrix(data=0, nrow=n,ncol=(big)) for( j in 1 : big) ##j is structure for(i in 1 : n){ # i is the history CHS[i,j] <- sscore[j]-SDM[i,j] } #end i ########################################################################### #pull the highest score for each history 1 score, 2 structure, 3 history Hscore<-matrix(data=0, nrow=(n-nn),ncol=(3)) for(i in 1 : (n-nn)){ Hscore[i,1]<- CHS[i,1] Hscore[i,2]<-1 Hscore[i,3]<-i for(j in 1 : big){ #j is sctructre if( Hscore[i,1]<= CHS[i,j]){ Hscore[i,1] <- CHS[i,j] #### score Hscore[i,2] <- j #### structure Hscore[i,3] <- i #### History } # end if } # end j } #end i ################################################## #sort the history score so that they are ranked RM<-matrix(data=0, nrow=(n-nn),ncol=(3)) RM<-Hscore[order(Hscore[,1],decreasing=TRUE),] ####################################################################### # write the socre structure and history value to clhist and return it clhist<-0 clhist[1]<-RM[1,1] #score in first column clhist[2]<-RM[1,2] # clhist[3]<-RM[1,3] #history in the last column return(clhist) } # end Distance score function
/scratch/gouwar.j/cran-all/cranData/CHFF/R/standarddistance.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### # __________________________________________________________ # # ForwardR # __________________________________________________________ #' Forward step #' #' @param emisVec a vector of emission probabilities. #' @param initPr a vector specifying initial state probabilities. #' @param trsVec a vector of state transition probabilities. #' @useDynLib CHMM Forward #' @export #' @keywords internal ForwardR <- function(emisVec,initPr,trsVec) { nb.states <- length(initPr) nbI <- length(emisVec) / nb.states .C("Forward", as.double(emisVec), as.double(initPr), as.double(trsVec), as.integer(nbI), as.integer(nb.states), Fpr = double(nbI * nb.states), Lambda = double(nbI), PACKAGE = "CHMM") } ## __________________________________________________________ ## ## BackwardR ## __________________________________________________________ ## #' Backward step #' #' @param Fpr Fpr. #' @param trsVec a vector of state transition probabilities. #' @param nb.states an integer specifying the numbers of states. #' @useDynLib CHMM Backward #' @export #' @keywords internal BackwardR <- function(Fpr, trsVec, nb.states) { nbI <- length(Fpr) / nb.states .C("Backward", as.double(Fpr), as.double(trsVec), as.integer(nbI), as.integer(nb.states), postPr = double(nbI * nb.states), Gpr = double(nbI * nb.states), PACKAGE = "CHMM") }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/CFunctions.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Hidden status of 10 correlated samples. #' #' A matrix containing the hidden status fo the 1,000 positions of 10 #' correlated samples. #'@name toyexample #'@docType data #' @format A list containing a matrix with 1000 rows and 10 columns: #' \describe{ #' \item{X}{a matrix with 1000 rows and 5 columns. Each column is a series} #' \item{hidden}{a matrix of the corresponding hidden status} #' } #' @keywords datasets #' @export #' @examples #' data(toyexample) #' # Variational inference of a coupled hidden Markov Chains #' resCHMM <- chmm(X, nb.states = 3, S = cor(hidden), omega.list = c(0.3, 0.5, 0.7, 0.9)) #' A matrix containing the hidden status fo the 1,000 positions of 10 #' correlated samples. #'@name toyexample #'@docType data #' @format A list containing a matrix with 1000 rows and 10 columns: #' \describe{ #' \item{X}{a matrix with 1000 rows and 5 columns. Each column is a series} #' \item{hidden}{a matrix of the corresponding hidden status} #' } #' @keywords datasets #' @export #' @examples #' data(toyexample) #' # Variational inference of a coupled hidden Markov Chains #' resCHMM <- chmm(X, nb.states = 3, S = cor(hidden), omega.list = c(0.3, 0.5, 0.7, 0.9))
/scratch/gouwar.j/cran-all/cranData/CHMM/R/CHMM.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Perform exact inference of coupled hidden markov models. #' #' @param X a data matrix of observations. Columns correspond to individuals. #' @param nb.states a integer specifying the numbers of states. #' @param S a matrix of similarity between individuals. #' @param omega a value of omega. #' @param meth.init a string specifying the initialization method ("mclust" or "kmeans"). The default method is "mclust". #' @param var.equal a logical variable indicating whether to treat the variances as being equal. #' @param itmax an integer specifying the maximal number of iterations for the EM algorithm. #' @param threshold a value for the threshold used for the stopping criteria. #' @return a list of 10 components #' \describe{ #' \item{\code{postPr}}{a list containing for each series the posterior probabilities.} #' \item{\code{initGb}}{a numeric specifying the initial state probabilities.} #' \item{\code{transGb}}{a matrix of the state transition probabilities.} #' \item{\code{emisGb}}{a list containing for each series the emission probabilities.} #' \item{\code{esAvg}}{ a numeric of the estimated mean for each state.} #' \item{\code{esVar}}{ a numeric of the estimated variance for each state.} #' \item{\code{ID.K}}{ a matrix containing all combination of possible state for nbI series.} #' \item{\code{loglik}}{ a numeric with the value of the loglikelihood.} #' \item{\code{RSS}}{ a numeric corresponding to the Residuals Sum of Squares.} #' \item{\code{iterstop}}{ an integer corresponding to the total number of iterations.} #'} #' @export #' @references Wang, X., Lebarbier, E., Aubert, J. and Robin, S., Variational inference for coupled Hidden Markov Models applied to the joint detection of copy number variations. #' ## __________________________________________________________ ## ## Function :: CHMM.EM() ## __________________________________________________________ ## CHMM_EM <- function(X, nb.states, S, omega, meth.init = "mclust", var.equal = TRUE, itmax = 5e2, threshold = 1e-7){ if (is.null(S)) stop("Argument S must be specified.") nbT <- nrow(X) nbI <- ncol(X) nbK <- nb.states^nbI ID.K <- ExpGrid(nb.states, nbI) wPr <- Wl(ID.K, S, omega) # Initialization EM --------------------------------------------- res.init <- init.EM(X, nb.states, meth.init, var.equal, nbI, nbT) esAvgGb <- res.init$esAvgGb esVarGb <- res.init$esVarGb esVar <- res.init$esVar esAvg <- res.init$esAvg transGb <- res.init$transGb initGb <- res.init$initGb # E-M algorithm ------------------------------------------------ # Attention: besoin de esVar et esAvg Old.param <- c(esVar, esAvg) for (iter in 1:itmax) { emisGb <- EmisGb.Gauss(X, esAvgGb, esVarGb) # E-Step ------------------------------------------------- ## Transform matrix to vectors --------------------------- trsGbVec <- as.vector(transGb) # Forward-Backward recursion --------------------------- resF <- ForwardR(as.vector(emisGb), initGb, trsGbVec) resB <- BackwardR(resF$Fpr, trsGbVec, nbK) postGb.tmp <- apply(matrix(resB$postPr, nbT, nbK), 2, pmax, 1e-6) postGb <- postGb.tmp / rowSums(postGb.tmp) Fpr <- matrix(c(resF$Fpr), nbT, nbK) Gpr <- matrix(c(resB$Gpr), nbT, nbK) loglik <- -sum(log(resF$Lambda)) ## M-Step --------------------------- ### update global mean: esAvgGb --------------------------- for (q in 1:nb.states) { tauq <- NULL for (ind in 1:nbI) { idx <- which(ID.K[,ind] == q) tauq <- cbind(tauq, rowSums(postGb[,idx])) } esAvg[q] <- sum(tauq * X) / sum(tauq) } esAvg <- sort(esAvg) esAvgGb <- matrix(esAvg[ID.K], nbK, nbI) ### update global variance: esVarGb --------------------------- if (var.equal == TRUE) { var.tmp <- 0 for(q in 1:nb.states){ tauiq <- NULL for (ind in 1:nbI) { idx <- which(ID.K[, ind] == q) tauiq <- cbind(tauiq, rowSums(postGb[, idx])) } var.tmp <- var.tmp + sum(tauiq * (X - esAvg[q]) ** 2) } esVar <- var.tmp / nbI / nbT esVarGb <- matrix(esVar, nbK, nbI) } else { for(q in 1:nb.states){ tauiq <- NULL for (ind in 1:nbI) { idx <- which(ID.K[, ind] == q) tauiq <- cbind(tauiq, rowSums(postGb[,idx])) } esVar[q] <- sum(tauiq * ( X - esAvg[q]) ** 2) / sum(tauiq) } esVarGb <- matrix(esVar[ID.K], nbK, nbI) } ### update transition --------------------------- Nkl <- transGb * (t(Fpr[-nbT,]) %*% (postGb[-1,] / Gpr[-1,])) Pkl <- t(Nkl) / wPr Pkl <- t(Pkl) nqr <- matrix(0, nb.states, nb.states) for (iq in 1:nb.states) { for (ir in 1:nb.states) { Ntld <- matrix(0, nbK, nbK) for (ik in 1:nbK) { for (il in 1:nbK) { tmp <- 0 for (ii in 1:nbI) { qik <- ID.K[ik,ii] qil <- ID.K[il,ii] if (qik == iq && qil == ir) tmp = tmp + 1 } Ntld[ik,il] <- Pkl[ik,il] * tmp } } nqr[iq,ir] <- sum(Ntld) } } transPr <- nqr / rowSums(nqr) trans.tmp <- matrix(0,nbK,nbK) for (k in 1:nbK) { qvec <- ID.K[k,] for (l in 1:nbK) { rvec <- ID.K[l,] trans.tmp[k,l] <- prod(diag(transPr[qvec,rvec])) * wPr[l] } } transGb <- trans.tmp / rowSums(trans.tmp) ### update initial distribution --------------------------- val.propre <- round(eigen(t(transGb))$values, 3) pos <- which(val.propre == 1.000) muHMM <- eigen(t(transGb))$vectors[,pos] muHMM <- muHMM / sum(muHMM) init.tmp <- as.numeric(muHMM) init.tmp[init.tmp < 0] <- 0 initGb <- init.tmp / sum(init.tmp) ## Stop criteria --------------------------- New.param <- c(esVar, esAvg) crit <- New.param - Old.param # esVarGb = pmax(esVarGb,1e-3) Old.param <- New.param if (iter > 1 && max(abs(crit)) <= threshold) break() }#end for postPr.list = list() for (i in 1:nbI) { postTmp <- NULL for (q in 1:nb.states) { idq <- which(ID.K[,i] == q) postTmp <- cbind(postTmp, rowSums(postGb[,idq])) } postPr.list[[i]] <- postTmp } RSS <- 0 if (var.equal == TRUE) { for (i in 1:nbI) RSS <- RSS + sum(X[,i]^2) - 2 * esAvg %*% t(postPr.list[[i]]) %*% X[,i] + sum(esAvg^2 %*% t(postPr.list[[i]])) } else { for (r in 1:nb.states) for(i in 1:nbI) RSS <- RSS + sum(postPr.list[[i]][,r] * (X[,i] - esAvg[r])^2) } return(list(postPr = postPr.list, initGb = initGb, transGb = transGb, emisGb = emisGb, esAvg = esAvg, esVar = esVar, ID.K = ID.K, loglik = loglik, RSS = as.numeric(RSS), iterstop = iter)) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/CHMM_EM.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Perform variational inference of coupled Hidden Markov Models. #' #' @param X a data matrix of observations. Columns correspond to individuals. #' @param nb.states a integer specifying the numbers of states. #' @param S a matrix of similarity between individuals. #' @param omega a value of omega. #' @param meth.init a string specifying the initialization method ("mclust" or "kmeans"). The default method is "mclust". #' @param var.equal a logical variable indicating whether to treat the variances as being equal. #' @param itmax an integer specifying the maximal number of iterations for the EM algorithm. #' @param threshold a value for the threshold used for the stopping criteria. #' @return a list of 9 components #' \describe{ #' \item{\code{postPr}}{a list containing for each series the posterior probabilities. } #' \item{\code{initPr}}{ a numeric specifying the initial state probabilities.} #' \item{\code{transPr}}{ a matrix of the state transition probabilities.} #' \item{\code{esAvg}}{ a numeric of the estimated mean for each state.} #' \item{\code{esVar}}{ a numeric of the estimated variance for each state.} #' \item{\code{emisPr}}{a list containing for each series the emission probabilities.} #' \item{\code{emisPrW}}{a list containing for each series the emission probabilities taking into account for the dependency structure.} #' \item{\code{RSS}}{ a numeric corresponding to the Residuals Sum of Squares.} #' \item{\code{iterstop}}{ an integer corresponding to the total number of iterations.} #'} #' @export #' @references Wang, X., Lebarbier, E., Aubert, J. and Robin, S., Variational inference for coupled Hidden Markov Models applied to the joint detection of copy number variations. #' CHMM_VEM <- function(X, nb.states, S = NULL, omega = 0.7, meth.init = "mclust", var.equal = TRUE, itmax = 5e2, threshold = 1e-7){ if (is.null(S)) stop("Argument S must be specified.") nbT <- nrow(X) nbI <- ncol(X) # initialisation ------------------------------------------------------ # if (is.null(init.esAvg)) { res.init <- init.VEM(X, nb.states, meth.init, var.equal, nbI, nbT) esAvg <- res.init$esAvg esVar <- res.init$esVar transPr <- res.init$transPr initPr <- res.init$initPr postPr.last <- res.init$postPr # Variational E-M algorithm ------------------------------------------------------ Old.param = c(esAvg, esVar, as.vector(transPr)) for (iter in 1:itmax) { ## 1.VE-step ----------------------------- postPr.list <- list() emisPr.list <- list() emisPrW.list <- list() trsTmp <- matrix(0, nb.states, nb.states) emisPr <- matrix(0, nbT, nb.states) for (ind in 1:nbI) { w <- matrix(0, nbT, nb.states) for (ij in c(1:nbI)[-ind]) w <- w + S[ind, ij] * (1 - postPr.last[[ij]]) emisPr <- Emis.Gauss(X[,ind], esAvg, esVar) emisPr.list[[ind]] <- emisPr emisPrW <- omega^w * emisPr emisPrW.list[[ind]] <- omega^w * emisPr # Transform matrix to vectors ----------------------------- emisWVec <- as.vector(emisPrW) trsVec <- as.vector(transPr) initTmp <- as.vector(initPr * emisPrW[1,]) initPr <- initTmp /sum(initTmp) # Forward-Backward recursion ----------------------------- resF <- ForwardR(emisWVec, initPr, trsVec) resB <- BackwardR(resF$Fpr, trsVec, nb.states) postPr.tmp <- matrix(resB$postPr, nbT, nb.states) postPr.tmp <- apply(postPr.tmp, 2, pmax, 1e-6) postPr <- postPr.tmp / rowSums(postPr.tmp) postPr.list[[ind]] <- postPr Fpr <- matrix(c(resF$Fpr), nbT, nb.states) Gpr <- matrix(c(resB$Gpr), nbT, nb.states) trsTmp <- trsTmp + transPr * t(Fpr[-nbT,]) %*% (postPr[-1,] / Gpr[-1,]) } postPr.last <- postPr.list ## 2.M-step ---------------------------- # update transPr trsAvg <- trsTmp / nbI transPr <- trsAvg / rowSums(trsAvg) # update initPr ---------------------------- init.tmp <- rep(0, nb.states) for(i in 1:nbI) init.tmp <- init.tmp + postPr.list[[i]][1,] initPr <- init.tmp / sum(init.tmp) # update esAvg ---------------------------- esAvg <- NULL for (r in 1:nb.states) { nom <- 0 den <- 0 for (i in 1:nbI) { nom <- nom + sum(postPr.list[[i]][,r] * (X[,i])) den <- den + sum(postPr.list[[i]][,r]) } esAvg <- c(esAvg, nom / den) } # update esVar ---------------------------- RSS <- 0 esVar <- NULL if (var.equal == TRUE) { nom <- 0 for(i in 1:nbI) nom <- nom + sum(X[,i]^2) - 2 * esAvg %*% t(postPr.list[[i]]) %*% X[,i] + sum(esAvg^2 %*% t(postPr.list[[i]])) esVar <- rep(nom/(nbI*nbT),nb.states) RSS <- nom # } else if(var.model == "V") { } else { for (r in 1:nb.states) { nom <- 0 den <- 0 for (i in 1:nbI) { nom <- nom + sum(postPr.list[[i]][,r] * (X[,i]-esAvg[r])^2) den <- den + sum(postPr.list[[i]][,r]) } esVar <- c(esVar, nom / den) RSS <- RSS + nom } } # order the parameters ---------------------------- ordAvg <- order(esAvg) esAvg <- sort(esAvg) esVar <- esVar[ordAvg] transPr <- transPr[ordAvg,ordAvg] ## 3.Stop iteration ---------------------------- New.param <- c(esAvg, esVar, as.vector(transPr)) crit <- New.param - Old.param esVar <- pmax(esVar, 1e-3) Old.param <- New.param if (iter > 1 && max(abs(crit)) <= threshold) break() } return(list(postPr = postPr.list, initPr = initPr, transPr = transPr, esAvg = esAvg, esVar = esVar, emisPr = emisPr.list, emisPrW = emisPrW.list, RSS = as.numeric(RSS), iterstop = iter)) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/CHMM_VEM.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Wl Internal function calculating Wl. #' #' @param nb.states an integer specifying the numbers of states. #' @param nbI an integer specifying the number of series. #' @return a matrix containing all combination of possible state for nbI series. #' @export #' @keywords internal ExpGrid <- function(nb.states, nbI){ KI.list <- list() for (i in 1:nbI) { KI.list[[i]] <- 1:nb.states } KI.grid <- as.matrix(expand.grid(KI.list)) return(KI.grid[, nbI:1]) } #' Wl Internal function calculating Wl. #' #' @param ID.K as.matrix(expand.grid(list(c(1:nbI),c(1:nb.states))). #' @param S a matrix of similarities between individuals. #' @param omega . #' @return Wl. #' @importFrom stats dist #' @export #' @keywords internal Wl <- function(ID.K, S, omega){ nbK <- nrow(ID.K) Sl <- sapply(1:nbK, function(i) sum(S[lower.tri(S)][which(dist(ID.K[i,])>0)])) Wl <- omega^Sl return(Wl) } #' Summarize the results of the coupled HMM. #' #' @param x a matrix of status. Columns corresponds to series (individuals). #' @return a data.frame with 4 columns #' \describe{ #' \item{\code{sample}}{name of the sample (series). } #' \item{\code{posbegin}}{beginning position.} #' \item{\code{posend}}{ending position.} #' \item{\code{status}}{status.} #'} #' @export #' clusterseg <- function(x){ output <- NULL for (i in 1:ncol(x)){ succStatus <- diff(x) posend <- which(succStatus[,i] != 0) posbegin <- c(1, posend + 1) tmp <- data.frame(sample = colnames(x)[i], posbegin, posend = c(which(succStatus[,i]!=0), nrow(x)), status = x[posbegin,i]) output <- rbind(output,tmp) } return(output) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/FuncAux.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### ## __________________________________________________________ ## ## Function :: Emis.Gauss() ## __________________________________________________________ ## #' Emis.Gauss #' #' @param X data matrix of observations. #' @param esAvg a numeric of the estimated mean for each state. #' @param esVar a numeric of the estimated variance for each state. #' @importFrom stats dnorm #' @keywords internal #' Emis.Gauss <- function(X, esAvg, esVar){ nbS <- length(esAvg) apply(as.matrix(1:nbS), 1, function(r) dnorm(X, mean = esAvg[r], sd = sqrt(esVar[r])) ) } ## __________________________________________________________ ## ## Function :: Emis.LRR() ## __________________________________________________________ ## #' Emis.LRR #' #' @param X data matrix of observations. #' @param esAvg a numeric of the estimated mean for each state. #' @param esVar a numeric of the estimated variance for each state. #' @param weight weight. #' @importFrom stats dnorm #' @keywords internal #' #' Emis.LRR <- function(X, esAvg, esVar, weight = 0.05){ nbS <- length(esAvg) apply(as.matrix(1:nbS), 1, function(r) weight + (1 - weight) * dnorm(X, mean = esAvg[r], sd = sqrt(esVar[r])) ) } ## __________________________________________________________ ## ## Function :: EmisGb.Gauss() ## __________________________________________________________ ## #' EmisGb.Gauss #' #' @param X data matrix of observations. #' @param esAvgGb a matrix of \code{nbK} rows and \code{nbI} columns of estimated mean. #' @param esVarGb a matrix of \code{nbK} rows and \code{nbI} columns of estimated variance. #' @importFrom stats dnorm #' @keywords internal #' EmisGb.Gauss <- function(X, esAvgGb, esVarGb){ nbK <- nrow(esAvgGb) emisGb <- matrix(0, nrow(X), nbK) for(k in 1:nbK) { emisTmp <- NULL for(i in 1:ncol(X)) { emisTmp <- cbind(emisTmp, dnorm(X[,i], mean = esAvgGb[k,i], sd = sqrt(esVarGb[k,i])) ) } emisGb[,k] <- exp(rowSums(log(emisTmp))) } emisGb }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/FuncEmis.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Perform inference of coupled hidden markov models. #' #' #' @param X a matrix of observations. Columns correspond to series (individuals). #' @param nb.states a integer specifying the numbers of states. #' @param S a matrix of similarity between individuals. #' @param omega.list a vector of omega values. #' @param var.equal a logical variable indicating whether to treat the variances as being equal (var.equal = TRUE). #' @param exact a logical variable indicating whether to use VEM (exact = FALSE) or EM (exact = TRUE) algorithm for the inference of the model. #' @param meth.init a string specifying the initialization method ("mclust" or "kmeans") for the (V)-EM algorithm. The default method is "mclust". #' @param viterbi a logical variable indicating whether to use Maximum A Posteriori method (FALSE) or Viterbi algorithm (TRUE, by default) for recovering the most likely path. #' @param itmax an integer specifying the maximal number of iterations for the CHMM_(V)EM algorithm. #' @param threshold a value for the threshold used for the stopping criteria for the CHMM_(V)EM algorithm. #' @return A list of 4 objets. #' \describe{ #' \item{\code{omega}}{ an integer corresponding to the selected value among the omega.list.} #' \item{\code{model}}{a list corresponding to the output of the \code{CHMM-EM} or \code{CHMM-VEM} function for the selected model.} #' \item{\code{status}}{a matrix with status associated to each series in column and each position in row.} #' \item{\code{RSS.omega}}{ a dataframe with omega values and the associated Residuals Sum of Squares.} #'} #' @export #' @examples #' data(toyexample) #' # Variational inference of a coupled hidden Markov Chains #' resCHMM <- coupledHMM(X = toydata, nb.states = 3, S = cor(toystatus), #' omega.list = c(0.3, 0.5, 0.7, 0.9)) #' # Breakpoints positions and status of segments #' info <- clusterseg(resCHMM$status) #' # head(info) #' @seealso \code{\link{CHMM_VEM}}, \code{\link{CHMM_EM}} #' @references Wang, X., Lebarbier, E., Aubert, J. and Robin, S., Variational inference for coupled Hidden Markov Models applied to the joint detection of copy number variations. coupledHMM <- function(X, nb.states = 3, S = NULL, omega.list = c(0.3, 0.7, 0.9), var.equal = TRUE, exact = FALSE, meth.init = "mclust", viterbi = TRUE, itmax = 5e2, threshold = 1e-7){ if (is.null(S)) stop("Argument S must be specified.") nbI <- ncol(X) # inference --------------------------- RSS <- Inf if(exact == FALSE){ resApprox <- apply(as.matrix(omega.list),c(1),FUN=function(y) CHMM_VEM(X, nb.states, S , y, meth.init, var.equal, itmax, threshold)) RSS <- unlist(lapply(resApprox,FUN = function(x) x$'RSS')) mod.sel <- resApprox[[which.min(RSS)]] omega.sel <- omega.list[which.min(RSS)] if (viterbi == TRUE){ status <- apply(as.matrix(1:nbI),c(1),FUN=function(y) viterbi_algo(mod.sel$emisPrW[[y]], mod.sel$transPr, mod.sel$initPr)) }else{ status <- apply(as.matrix(1:nbI),c(1),FUN=function(y) apply(mod.sel$postPr[[y]], 1, which.max)) } colnames(status) <- colnames(X) }else{ resExact <- apply(as.matrix(omega.list),c(1),FUN=function(y) CHMM_EM(X, nb.states, S , y, meth.init, var.equal, itmax, threshold)) RSS <- unlist(lapply(resExact,FUN = function(x) x$'RSS')) mod.sel <- resExact[[which.min(RSS)]] omega.sel <- omega.list[which.min(RSS)] if (viterbi == TRUE){ stsGb <- viterbi_algo(mod.sel$'emisGb', mod.sel$'transGb', mod.sel$'initGb') status <- mod.sel$ID.K[stsGb, ] }else{ status <- apply(as.matrix(1:nbI),c(1),FUN=function(y) apply(mod.sel$postPr[[y]], 1, which.max)) } colnames(status) <- colnames(X) }#end if return(list(omega = omega.sel, model = mod.sel, status = status, RSS.omega = data.frame(RSS = RSS, omega = omega.list))) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/coupledHMM.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Toy example - observations for 5 correlated samples. #' #' A matrix containing the observations for the 1,000 positions of 5 #' correlated samples. #'@name toydata #'@docType data #' @format A simulated matrix with 1000 rows and 5 columns. Each column is a series #' @keywords datasets #' @examples #' data(toyexample) #' # Variational inference of a coupled hidden Markov Chains #' resCHMM <- coupledHMM(X = toydata, nb.states = 3, S = cor(toystatus), #' omega.list = c(0.3, 0.5, 0.7, 0.9)) #' # Breakpoints positions and status of segments #' info <- clusterseg(resCHMM$status) #' # head(info) NULL #' Toy example - status for 5 correlated samples. #' #' A matrix containing the hidden status for the 1,000 positions of 5 #' correlated samples. #'@name toystatus #'@docType data #' @format A matrix of the hidden status corresponding to the \code{toydata} matrix. #' @keywords datasets NULL
/scratch/gouwar.j/cran-all/cranData/CHMM/R/data.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### ## __________________________________________________________ ## ## Function :: init.EM() ## __________________________________________________________ ## #' Initialization step of the \code{CHMM_EM} function. #' #' @param X a matrix of observations. Columns correspond to series (individuals). #' @param nb.states an integer specifying the numbers of states. #' @param meth.init a string specifying the initialization method ("mclust" or "kmeans"). The default method is "mclust". #' @param var.equal a logical variable indicating whether to treat the variances as being equal (TRUE, value by default) or not (FALSE). #' @param nbI an integer specifying the number of series. #' @param nbT an integer specifying the length of one series. #' @return A list of 6 objects. #' \describe{ #' \item{\code{esAvgGb}}{ a matrix of \code{nbK}(nb.states^nbI) rows and \code{nbI} columns of estimated mean.} #' \item{\code{esVarGb}}{ a matrix of \code{nbK}(nb.states^nbI) rows and \code{nbI} columns of estimated variance.} #' \item{\code{esAvg}}{ a numeric of the estimated mean for each state.} #' \item{\code{esVar}}{ a numeric of the estimated variance for each state.} #' \item{\code{transGb}}{ a matrix of the state transition probabilities.} #' \item{\code{initGb}}{ a numeric specifying the initial state probabilities.} #'} #'@details By default, an initialization with the \code{meth.init="mclust"} is performed with homogeneous variances. #' @importFrom mclust Mclust #' @importFrom mclust mclustBIC #' @importFrom stats kmeans #' @importFrom stats runif #' @export #' @seealso \code{\link{CHMM_EM}} #' init.EM <- function(X, nb.states, meth.init, var.equal, nbI, nbT){ nbK <- nb.states^nbI ID.K <- ExpGrid(nb.states, nbI) # mclust initialization --------------------------------------------------------- if(meth.init == "mclust") { if (var.equal == TRUE) { clust <- mclust::Mclust(data = as.vector(t(X)), G = nb.states, modelNames = "E") esVar <- clust$parameters$variance$sigmasq esVarGb <- matrix(esVar, nbK, nbI) } else { clust <- mclust::Mclust(data = as.vector(t(X)), G = nb.states, modelNames = "V") esVar <- clust$parameters$variance$sigmasq esVarGb <- matrix(esVar[ID.K], nbK, nbI) } esAvg <- clust$parameters$mean # kmeans initialization --------------------------------------------------------- } else if(meth.init == "kmeans") { clust <- kmeans(x = as.vector(t(X)), centers = nb.states) esAvg <- sort(as.vector(clust$centers)) if (var.equal == TRUE) { esVar <- clust$tot.withinss / (nbT * nbI - 1) esVarGb <- matrix(esVar, nbK, nbI) } else { esVar <- clust$withinss / (clust$size - 1) esVarGb <- matrix(esVar[ID.K], nbK, nbI) } } esAvgGb <- matrix(esAvg[ID.K], nbK, nbI) # transGb ----------------------------------------------------------- mat.tmp <- matrix(runif(nbK^2), nbK, nbK) + diag(rep(50, nbK)) transGb <- mat.tmp / rowSums(mat.tmp) ## initGb ----------------------------------------------------------- val.propre <- round(eigen(t(transGb))$values, 3) pos <- which(val.propre == 1.000) nuHMM <- eigen(t(transGb))$vectors[,pos] nuHMM <- nuHMM / sum(nuHMM) initGb <- pmax(as.numeric(nuHMM), 0) initGb <- initGb / sum(initGb) return(list(esAvgGb = esAvgGb, esVarGb = esVarGb, esAvg = esAvg, esVar = esVar, transGb = transGb, initGb = initGb)) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/init.EM.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### ## __________________________________________________________ ## ## Function :: init.VEM() ## __________________________________________________________ ## #' Initialization step of the \code{CHMM_VEM} function. #' #' @param X a matrix of observations. Columns correspond to series (individuals). #' @param nb.states an integer specifying the numbers of states. #' @param meth.init a string specifying the initialization method ("mclust" or "kmeans"). The default method is "mclust". #' @param var.equal a logical variable indicating whether to treat the variances as being equal (TRUE, value by default) or not (FALSE). #' @param nbI an integer specifying the number of series. #' @param nbT an integer specifying the length of one series. #' #' @return A list containing the parameters of the model #' \describe{ #' \item{\code{esAvg}}{ a numeric of the estimated mean for each state.} #' \item{\code{esVar}}{ a numeric of the estimated variance for each state.} #' \item{\code{transPr}}{ a matrix of the state transition probabilities} #' \item{\code{postPr}}{ a list containing for each series the posterior probabilities.} #' \item{\code{initPr}}{ a numeric specifying the initial state probabilities}. #'} #' #' @importFrom mclust Mclust #' @importFrom mclust mclustBIC #' @importFrom stats kmeans #' @importFrom stats runif #' @export init.VEM <- function(X, nb.states, meth.init, var.equal, nbI, nbT){ # mclust initialization --------------------------------------------------------- if(meth.init == "mclust") { if (var.equal == TRUE) { clust <- mclust::Mclust(data = as.vector(t(X)), G = nb.states, modelNames = "E") esVar <- rep(clust$parameters$variance$sigmasq, nb.states) } else { clust <- mclust::Mclust(data = as.vector(t(X)), G = nb.states, modelNames = "V") esVar <- clust$parameters$variance$sigmasq } esAvg <- clust$parameters$mean # kmeans initialization --------------------------------------------------------- } else if(meth.init == "kmeans") { clust <- kmeans(x = as.vector(t(X)), centers = nb.states) esAvg <- sort(as.vector(clust$centers)) if (var.equal == TRUE) { esVar <- rep(clust$tot.withinss / (nbT * nbI - 1), nb.states) } else { esVar <- clust$withinss / (clust$size - 1) } } mat.tmp <- matrix(runif(nb.states^2), ncol = nb.states) + diag(rep(50, nb.states)) transPr <- mat.tmp / rowSums(mat.tmp) # initial distribution ----------------------------------------- eigenvalues <- round(eigen(t(transPr))$values, 3) pos <- which(eigenvalues == 1.000) nuHMM <- eigen(t(transPr))$vectors[, pos] initPr <- pmax(as.numeric(nuHMM / sum(nuHMM)), 0) initPr <- initPr / sum(initPr) # postPr ------------------------------------------------------ postPr <- list() for(ind in 1:nbI){ #tau.tmp <- data.frame(matrix(runif(nbT * nb.states, 0, 1), nbT, nb.states)) tau.tmp <- matrix(runif(nbT * nb.states, 0, 1), nbT, nb.states) tau.tmp <- tau.tmp / rowSums(tau.tmp) postPr[[ind]] <- tau.tmp } return(list(esAvg = esAvg, esVar = esVar, transPr = transPr, initPr = initPr, postPr = postPr)) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/init.VEM.R
# CHMM R package # Copyright INRA 2017 # UMR MIA-Paris, AgroParisTech, INRA, Universite Paris-Saclay, 75005, Paris, France ################################################################### #' Implementation of the Viterbi algorithm #' #'@param emisPr a matrix of emission probabilities for the considering series. #'@param transPr a matrix of state transition probabilities. #'@param initPr a vector specifying initial state probabilities. #'@return \item{path}{the most likely path (state sequence).} #'@export #'@keywords internal viterbi_algo <- function(emisPr, transPr, initPr){ nb.states <- ncol(emisPr) nbT <- nrow(emisPr) logF <- matrix(0, nbT, nb.states) logF[1,] <- log(initPr) + log(emisPr[1,]) for (tt in 2:nbT) for (k in 1:nb.states) logF[tt,k] <- log(emisPr[tt, k]) + max(logF[tt - 1,] + log(transPr[,k])) path <- rep(NA, nbT) path[nbT] <- which.max(logF[nbT,]) for (tt in (nbT - 1):1) path[tt] <- which.max(logF[tt, ] + log(transPr[, path[tt + 1]])) return(path) }
/scratch/gouwar.j/cran-all/cranData/CHMM/R/viterbi_algo.R