content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' @title Draw Crossplots #' #' @description This function draws crossplots for As and Bs in each variable in the mean and variance models with the Mean Estimate vs Standard Deviation Estimate. #' #' @param fn.mean.A Enter file name of file with confidence intervals of mean stress, environment level A data. Can be hybrid, inbred, or full data set. This file needs to be obtained from the bootstrap function, run with the desired data set. #' @param fn.mean.B Enter file name of file with confidence intervals of mean stress, environment level B data. Can be hybrid, inbred, or full data set. This file needs to be obtained from the bootstrap function, run with the desired data set. #' @param fn.sd.A Enter file name of file with confidence intervals of SD stress, environment level A data. Can be hybrid, inbred, or full data set. This file needs to be obtained from the bootstrap function, run with the desired data set. #' @param fn.sd.B Enter file name of file with confidence intervals of SD stress, environment level B data. Can be hybrid, inbred, or full data set. This file needs to be obtained from the bootstrap function, run with the desired data set. #' @param fn.pe.mean Enter file name of file with point estimates of mean for each gene (both A and B environment levels present). Can be hybrid, inbred, or full data set. This file needs to be obtained from the mean_stress function, run with the desired data set. #' @param fn.pe.sd Enter file name of file with point estimates of SD for each gene (both A and B environment levels present). Can be hybrid, inbred, or full data set. This file needs to be obtained from the sd.stress function, run with the desired data set. #' @param variables List of variables from mean and variance models. Mean variables need to be listed first, then variance variables. #' @param ishybrid Indicates the type of the data set being examined. You can use 'Hybrid', 'Inbred', "All", etc. #' @param num.vars Number of variables per model. Used to ascertain if a variable falls in the mean or the variance model. #' @return There is no return for this function; it prints crossplots for each of the variables listed in the parameter 'variables.' #' @importFrom utils read.table #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' variables <- colnames(test.data[-1]) #' mean_stress(test.data, variables, 'stress') #' sink(); #' sd.stress(test.data, variables, 'stress') #' sink(); #' plot_vars <- c("loci_var.4","loci_var.7.env_var.2","loci_var.3", #' "loci_var.5","loci_var.8.env_var.2","loci_var.4") #' bootstrap(test.data, n.boot=100,variables, 'stress') #' draw.crossplots('bootstrap mean A stress.txt','bootstrap mean B stress.txt', #' 'bootstrap sd A stress.txt', 'bootstrap sd B stress.txt', 'mean_stress.txt', #' 'sd_stress.txt', plot_vars, 'All',3) #' unlink(c('bootstrap mean A stress.txt','bootstrap mean B stress.txt', #' 'bootstrap sd A stress.txt', 'bootstrap sd B stress.txt', #' 'mean_stress.txt', 'sd_stress.txt')) #' @export draw.crossplots <- function(fn.mean.A, fn.mean.B, fn.sd.A, fn.sd.B, fn.pe.mean, fn.pe.sd, variables, ishybrid, num.vars) { hyb.mean.A <- utils::read.table(fn.mean.A, header = T) hyb.mean.B <- utils::read.table(fn.mean.B, header = T) hyb.sd.A <- utils::read.table(fn.sd.A, header = T) hyb.sd.B <- utils::read.table(fn.sd.B, header = T) # data frame with mean and sd point estimates # note: -1 = A; 1 = B # to access A & B in the data table, you need a table in the format as that produced by mean_stress and sd.stress in job2.diff.stress # A is -1 & is in the third column; B is 1 & is in the second column pe.mean <- read.table(fn.pe.mean, header = T) pe.sd <- read.table(fn.pe.sd, header = T) mean_estimate <- sd_estimate <- xmin <- xmax <- ymin <- ymax <- NULL for (i in seq(1, length(variables), by=1)){ df <- data.frame(mean_estimate = c(pe.mean[i,3],pe.mean[i,2]), sd_estimate = c(pe.sd[i,3],pe.sd[i,2]), xmin = c(hyb.mean.A[1,i],hyb.mean.B[1,i]), xmax = c(hyb.mean.A[2,i], hyb.mean.B[2,i]), ymin = c(hyb.sd.A[1,i],hyb.sd.B[1,i]), ymax = c(hyb.sd.A[2,i],hyb.sd.B[2,i])) # create crossplot # different options based on whether gene is in mean model or variance model if (i <= num.vars) { print(ggplot2::ggplot(data = df,ggplot2::aes(x = mean_estimate,y = sd_estimate, colour = c('A', 'B'))) + ggplot2::geom_point(size=3) + ggplot2::scale_colour_brewer(type = "qual", palette = "Dark2") + ggplot2::theme_bw() + ggplot2::geom_errorbar(ggplot2::aes(ymin = ymin,ymax = ymax),width=.1,size=1.2) + ggplot2::geom_errorbarh(ggplot2::aes(xmin = xmin,xmax = xmax),height=.1,size=1.2) + ggplot2::ggtitle(paste("Stress Mean and SD by Env Level,", variables[i], '(mean)', ishybrid, "Data")) + ggplot2::xlab("Mean Estimate, 95% CI") + ggplot2::ylab("SD Estimate, 95% CI") + ggplot2::labs(color=variables[i])) } else if (i > num.vars) { print(ggplot2::ggplot(data = df,ggplot2::aes(x = mean_estimate,y = sd_estimate, colour = c('A', 'B'))) + ggplot2::geom_point(size=3) + ggplot2::scale_colour_brewer(type = "qual", palette = "Dark2") + ggplot2::theme_bw() + ggplot2::geom_errorbar(ggplot2::aes(ymin = ymin,ymax = ymax),width=.1,size=1.2) + ggplot2::geom_errorbarh(ggplot2::aes(xmin = xmin,xmax = xmax),height=.1,size=1.2) + ggplot2::ggtitle(paste("Stress Mean and SD by Env Level,", variables[i], '(var)', ishybrid, "Data")) + ggplot2::xlab("Mean Estimate, 95% CI") + ggplot2::ylab("SD Estimate, 95% CI") + ggplot2::labs(color=variables[i])) } } } #' @title Draw Square Plots #' #' @description This function draws square plots for As and Bs in each variable in the mean and variance models with the Mean Estimate vs Standard Deviation Estimate #' #' @param fn.mean.A file name of file with confidence intervals of mean stress, environment level A data. Can be either hybrid or inbred data. #' @param fn.mean.B file name of file with confidence intervals of mean stress, environment level B data. Can be either hybrid or inbred data. #' @param fn.sd.A file name of file with confidence intervals of SD stress, environment level A data. Can be either hybrid or inbred data. #' @param fn.sd.B file name of file with confidence intervals of SD stress, environment level B data. Can be either hybrid or inbred data. #' @param fn.pe.mean file name of file with point estimates of mean for each gene (both A and B environment levels present). Can be either hybrid or inbred data. #' @param fn.pe.sd file name of file with point estimates of SD for each gene (both A and B environment levels present). Can be either hybrid or inbred data. #' @param variables list of variables from mean and variance models. Mean vars needs to be listed first, then variance vars. #' @param ishybrid indicates the type of the data set being examined. Choose 'Hybrid' or 'Inbred' or "All". #' @param num.vars number of variables per model. Used to ascertain if a variable falls in the mean or the variance model. #' @return There is no return for this function; it prints square plots for each of the variables listed in the parameter 'variables'. #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' variables <- colnames(test.data[-1]) #' mean_stress(test.data, variables, 'stress') #' sink(); #' sd.stress(test.data, variables, 'stress') #' sink(); #' bootstrap(test.data, n.boot=100,variables, 'stress') #' plot_vars <- c("loci_var.4","loci_var.7.env_var.2","loci_var.3", #' "loci_var.5","loci_var.8.env_var.2","loci_var.4") #' draw.squareplots('bootstrap mean A stress.txt','bootstrap mean B stress.txt', #' 'bootstrap sd A stress.txt', 'bootstrap sd B stress.txt', 'mean_stress.txt', #' 'sd_stress.txt', plot_vars, 'All', 3) #' unlink(c('bootstrap mean A stress.txt','bootstrap mean B stress.txt', #' 'bootstrap sd A stress.txt', 'bootstrap sd B stress.txt', #' 'mean_stress.txt', 'sd_stress.txt')) #' @export draw.squareplots <- function(fn.mean.A, fn.mean.B, fn.sd.A, fn.sd.B, fn.pe.mean, fn.pe.sd, variables, ishybrid, num.vars) { hyb.mean.A <- utils::read.table(fn.mean.A, header = T) hyb.mean.B <- utils::read.table(fn.mean.B, header = T) hyb.sd.A <- utils::read.table(fn.sd.A, header = T) hyb.sd.B <- utils::read.table(fn.sd.B, header = T) # data frame with mean and sd point estimates # note: -1 = A; 1 = B # to access A & B in the data table, you need a table in the format as that produced by mean_stress and sd.stress in job2.diff.stress # A is -1 & is in the third column; B is 1 & is in the second column pe.mean <- read.table(fn.pe.mean, header = T) pe.sd <- read.table(fn.pe.sd, header = T) mean_estimate <- sd_estimate <- xmin <- xmax <- ymin <- ymax <- NULL for (i in seq(1, length(variables), by=1)){ df <- data.frame(mean_estimate = c(pe.mean[i,3],pe.mean[i,2]), sd_estimate = c(pe.sd[i,3],pe.sd[i,2]), xmin = c(hyb.mean.A[1,i],hyb.mean.B[1,i]), xmax = c(hyb.mean.A[2,i], hyb.mean.B[2,i]), ymin = c(hyb.sd.A[1,i],hyb.sd.B[1,i]), ymax = c(hyb.sd.A[2,i],hyb.sd.B[2,i])) # create squareplots # different options based on whether gene is in mean model or variance model if (i <= num.vars) { print(ggplot2::ggplot(data = df,ggplot2::aes(x = mean_estimate,y = sd_estimate, colour = c('A', 'B'))) + ggplot2::geom_point(size=3) + ggplot2::scale_colour_brewer(type = "qual", palette = "Dark2") + ggplot2::theme_bw() + ggplot2::geom_rect(ggplot2::aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax),alpha=0,color=c('chartreuse','lightcoral'),size=1) + ggplot2::ggtitle(paste("Stress Mean and SD by Env Level,", variables[i], '(mean)', ishybrid, "Data")) + ggplot2::xlab("Mean Estimate, 95% CI") + ggplot2::ylab("SD Estimate, 95% CI") + ggplot2::labs(color=variables[i])) } else if (i > num.vars) { print(ggplot2::ggplot(data = df,ggplot2::aes(x = mean_estimate,y = sd_estimate, colour = c('A', 'B'))) + ggplot2::geom_point(size=3) + ggplot2::scale_colour_brewer(type = "qual", palette = "Dark2") + ggplot2::theme_bw() + ggplot2::geom_rect(ggplot2::aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax),alpha=0,color=c('chartreuse','lightcoral'),size=1) + ggplot2::ggtitle(paste("Stress Mean and SD by Env Level,", variables[i], '(var)', ishybrid, "Data")) + ggplot2::xlab("Mean Estimate, 95% CI") + ggplot2::ylab("SD Estimate, 95% CI") + ggplot2::labs(color=variables[i])) } } }
/scratch/gouwar.j/cran-all/cranData/CIS.DGLM/R/Crossplots.functions.R
#' @title Simulated Data with DGLM model #' #' @description This function implements a simulation based on randomly-generated data following a known structure to create a double generalized linear model (DGLM). In particular, it supports the use of interaction terms in the DGLM. #' #' @param n.rep The number of repetitions of each environment level. Defaults to 3. #' @param n.level.env The number of environment variable levels. Defaults to 2. #' @param n.obs.per.rep A parameter to accommodate repetitions in the data set. Defaults to 150. #' @param n.loci The number of gene loci in data set. Defaults to 8. #' @param which.mean.loci A vector that specifies which gene loci are significant in the mean model. Defaults to the vector c(3:4). #' @param hypo.mean.para A vector that contains the slopes of the gene locations (from which.mean.loci) in the mean model. Defaults to the vector c(1,4). #' @param incept.mean The intercept for the mean model portion of the DGLM. Defaults to 36. #' @param which.var.loci A vector that specifies which gene loci are significant in the variance model. Defaults to c(4:5). #' @param hypo.var.para A vector that contains the slopes of the gene locations (from which.var.loci) in the variance model. Defaults to c(2,5). #' @param incept.var The intercept for the variance model portion of the DGLM. Defaults to -2. #' @param which.env.inter.mean Specifies which level of environment significantly interacts in the mean model. This is one of the parameters that supports model-building with interaction terms. Defaults to 2. #' @param which.loci.inter.mean Specifies which gene location interacts with the environment level in the mean model. This is one of the parameters that supports model-building with interaction terms. Defaults to 7. #' @param hypo.inter.para.mean The interaction effect between the specified environment level and the specified gene location in the mean model. This is another parameter that supports model-building with interaction terms. Defaults to 2.5. #' @param which.env.inter.var Specifies which level of environment significantly interacts in the variance model. This is another parameter that supports model-building with interaction terms. Defaults to 2. #' @param which.loci.inter.var Specifies which gene location interacts with the environment level in the variance model. This is another parameter that supports model-building with interaction terms. Defaults to 8. #' @param hypo.inter.para.var Interaction effect between the specified environment level and the specified gene location in the variance model. Defaults to 3.8. #' @param simu.prob.var The probability of each lcoi to be zero or one. Different loci may have different probability and can be adjusted as needed. Defaults to rep(0.5,n.loci). #' @param rc.val A parameter used to control right-censored data. It sets an upper limit such that if an observation is above a certain range, that observation cannot be included in the data set. Default value is 40. #' @param ran.seed The random seed to be used. Defaults to NULL. #' #' @return The function returns a data frame containing the data built from the simulation. It provides data for stress values, an environment variable with two levels (0 and 1), and levels for each simulated gene variable. #' @import dplyr #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' @export simu.inter.dat.interboth<-function(n.rep=3, n.level.env=2, n.obs.per.rep=150, n.loci=8, which.mean.loci=c(3:4), hypo.mean.para=c(1,4), incept.mean=36, which.var.loci=c(4:5), hypo.var.para=c(2,5), incept.var=-2, which.env.inter.mean=2,which.loci.inter.mean=7, hypo.inter.para.mean=2.5, which.env.inter.var =2,which.loci.inter.var =8, hypo.inter.para.var =3.8, simu.prob.var=rep(0.5, n.loci), rc.val=40, ran.seed=NULL) { #generate random data with known structure, replicating environment level, and genes. # With the provided parameters we can estimate stress value. if(is.null(ran.seed)!=1) set.seed(ran.seed); n.mean.loci<-ifelse(length(which.mean.loci)==length(hypo.mean.para),length(which.mean.loci),NA) n.var.loci<-ifelse(length(which.var.loci)==length(hypo.var.para),length(which.var.loci),NA) if (which.env.inter.mean>n.level.env) {print("the which.env.sig should be less than n.level.env"); stop;} if (which.env.inter.var >n.level.env) {print("the which.env.sig should be less than n.level.env"); stop;} env<-rep(rep(c(1:n.level.env),rep(n.rep,n.level.env)),n.obs.per.rep); env.mat<-matrix(0,nrow=n.rep*n.level.env*n.obs.per.rep, ncol=n.level.env); for(i in 1:n.level.env) env.mat[,i]=(env==i); var.names.env<-apply(expand.grid('env_var', c(1:n.level.env)), 1, paste, collapse="."); colnames(env.mat)<-var.names.env; simu.loci<-NULL; for(i in 1:n.loci) simu.loci<-cbind(simu.loci,rep(stats::rbinom(n.obs.per.rep, 1,simu.prob.var[i]),rep(n.rep*n.level.env,n.obs.per.rep))) var.names.loci<-apply(expand.grid('loci_var', c(1:n.loci)), 1, paste, collapse="."); colnames(simu.loci)<-var.names.loci; all.mean.para<-rep(0,n.loci);all.mean.para[which.mean.loci]<-hypo.mean.para; all.var.para<-rep(0,n.loci);all.var.para[which.var.loci]<-hypo.var.para; simu.obs<-cbind(env.mat[,-1],simu.loci); ## the -1 is to get rid of the first level for collinearity. colnames(simu.obs)[1:(n.level.env-1)]<-var.names.env[-1]; ### question: do we need to have similar data structure as the real data set, that is, the same type of genes? 🧬🧬🧬 ### or, would a gene 🧬🧬🧬 structure(a composition of multiple A' 🅰️ s and B' 🅱️s from gene🧬🧬🧬 loci) be an important thing to consider, or just with gene loci is contributing to the phenotype? inter.mat<-NULL; for(i in n.level.env:1) for(j in n.loci:1) inter.mat<-cbind(simu.loci[,j]*env.mat[,i],inter.mat); ## stop at 2 is to get rid of the first level for collinearity. var.names.inter.mat<-apply(as.matrix(expand.grid(var.names.loci, var.names.env)),1,paste,collapse="*"); colnames(inter.mat)<-var.names.inter.mat; all.inter.para.mean<- all.inter.para.var<-rep(0,n.level.env*n.loci); all.inter.para.mean[which.loci.inter.mean+(which.env.inter.mean-1)*n.loci]<-hypo.inter.para.mean; all.inter.para.var[which.loci.inter.var +(which.env.inter.var -1)*n.loci]<-hypo.inter.para.var; #which.env.inter.mean=3,which.loci.inter.mean=7, hypo.inter.para.mean=2.5, inter.pyntp.mean<-inter.mat%*%all.inter.para.mean; # accommodate all the interaction effects inter.pyntp.var <-inter.mat%*%all.inter.para.var; mean.pyntp<-incept.mean+simu.loci%*%all.mean.para; var.pyntp<-sapply(incept.var+simu.loci%*%all.var.para+inter.pyntp.var,FUN=function(x) stats::rnorm(1,sd=sqrt(exp(x)))); stress<-mean.pyntp+var.pyntp+inter.pyntp.mean # main function to generate the mean model, the variance part and interaction part (both mean and variance) simu.obs.df<-data.frame(stress,simu.obs,inter.mat[,-c(1:n.loci)]); #make it a data frame return(simu.obs.df); } # the above function is to generate the simulated data # now we analyze the data we generated above by using the forward stepwise selection approach #' @title Forward Stepwise Selection for Simulated Data #' #' @description This function implements the forward stepwise variable selection procedure on the simulated data set generated in simu.inter.dat.interboth. In this function, we utilize a dummy value of "1" when initializing the model to avoid issues with a NULL value when adding variables to the model. #' #' @param dat.ana.num12.df A data set filled with data based on a simulation, per the procedure to generate it in the simu.inter.dat.interboth function. #' @param ouput.name The name of the output file to which the results are to be saved. Defaults to 'out1.txt'. #' @param num.loop The number of iterations that forward stepwise selection is performed (and hence how many variables will be in the final mean and variance models). Defaults to 10 loops. #' #' @return A list with mean and variance mean effects and p-values associated with the coefficients. #' @import dplyr #' @examples #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' forward.sel.dglm(test.data) #' @export forward.sel.dglm<-function(dat.ana.num12.df, ouput.name='out1.txt', num.loop=10) { # dat.ana.num12.df is a dataframe, the response is "stress" # num.loop=30 is the max step to have sink(ouput.name); current.mean.pool.LO<-current.var.pool.LO<-colnames(dat.ana.num12.df)[-1]; forward.mean.pool<-forward.var.pool<-1; # these are initialized to 1; cannot use NULL, or error is generated conflict.set<-vector(mode = "list", length = num.loop); for(k in 1:num.loop) { print(paste('-------------------------------------Running the',k,'th loop-----------------------------------------------' )); sig.val.mean<-sig.val.var<-0.05; idx.mean<-idx.var<-NULL; print(paste('The current mean model is: ', paste('stress ~', paste(forward.mean.pool, collapse="+"),collapse = ''),sep='')) for(x in 1:length(current.mean.pool.LO)) { mean.x<-current.mean.pool.LO[x]; mean.model<- stats::as.formula(paste('stress', paste(c(forward.mean.pool,mean.x), collapse="+"), sep="~")); var.model<-switch(is.null(forward.var.pool)+1,stats::as.formula(paste('~', paste(forward.var.pool, collapse="+"), sep="")),stats::as.formula('~ 1')) out<-tryCatch( {mod.forward.update<-dglm::dglm( mean.model, dformula=var.model,data=dat.ana.num12.df); res.mod.update<-summary(mod.forward.update); if (res.mod.update$coefficients%>%last<sig.val.mean) { sig.val.mean<-res.mod.update$coefficients%>%last; idx.mean<-x;} }, error=function(cond) {print(paste(mean.x, 'causing error when entering the model')); return(cond)}, warning=function(cond) {print(paste(mean.x, 'causing Warning when entering the model')); return(cond)} ); } if(!is.null(idx.mean)) { print(paste('Adding [',current.mean.pool.LO[idx.mean],'] to mean model, with p-value=',sig.val.mean,sep='')); forward.mean.pool<-c(forward.mean.pool,current.mean.pool.LO[idx.mean]); current.mean.pool.LO<-current.mean.pool.LO[-idx.mean]; } ## else print(paste('The current Var model is: ', paste(' ~', paste(forward.var.pool, collapse="+"),collapse = ''),sep='')) for(z in 1:length(current.var.pool.LO)) { var.z<-current.var.pool.LO[z]; mean.model<- stats::as.formula(paste('stress', paste(c(forward.mean.pool), collapse="+"), sep="~")); var.model<- stats::as.formula(paste('~', paste(c(forward.var.pool,var.z), collapse="+"), sep="")); out<-tryCatch( {mod.forward.update<-dglm::dglm( mean.model, dformula=var.model,data=dat.ana.num12.df); res.mod.update<-summary(mod.forward.update); if (res.mod.update$dispersion.summary$coefficients%>%last<sig.val.var) { sig.val.var<-res.mod.update$dispersion.summary$coefficients%>%last; idx.var<-z;} }, error=function(cond) {print(paste(var.z, 'causing error when entering the model')); return(cond)}, warning=function(cond) {print(paste(var.z, 'causing Warning when entering the model')); return(cond)} ); } if(!is.null(idx.var)) {print(paste('Adding [',current.var.pool.LO[idx.var],'] to var model, with p-value=',sig.val.var,sep='')); forward.var.pool<-c(forward.var.pool,current.var.pool.LO[idx.var]); current.var.pool.LO<-current.var.pool.LO[-idx.var]; } } final.mean.model<- stats::as.formula(paste('stress', paste(c(forward.mean.pool), collapse="+"), sep="~")); final.var.model<- stats::as.formula(paste('~', paste(c(forward.var.pool), collapse="+"), sep="")); final.mod.forward.update<-dglm::dglm(final.mean.model, dformula=final.var.model,data=dat.ana.num12.df); print('-----------------------------Final Model ----------------------------') summary(final.mod.forward.update); print(final.mean.model); print(final.var.model); print('--------------------Conflict variable with models ----------------------------') print(conflict.set) sink(NULL); sum.model<-summary(final.mod.forward.update) main.coef.eff<-colSums(sum.model$coefficients[,1][-1]*outer(row.names(sum.model$coefficients)[-1],colnames(dat.ana.num12.df)[-1],'==')) main.coef.pval<-colSums(sum.model$coefficients[,4][-1]*outer(row.names(sum.model$coefficients)[-1],colnames(dat.ana.num12.df)[-1],'==')) main.coef.eff[main.coef.eff==0]<-NA;main.coef.pval[is.na(main.coef.eff)]<-NA; var.coef.eff<-colSums(sum.model$dispersion.summary$coefficients[,1][-1]*outer(row.names(sum.model$dispersion.summary$coefficients)[-1],colnames(dat.ana.num12.df)[-1],'==')) var.coef.pval<-colSums(sum.model$dispersion.summary$coefficients[,4][-1]*outer(row.names(sum.model$dispersion.summary$coefficients)[-1],colnames(dat.ana.num12.df)[-1],'==')) var.coef.eff[var.coef.eff==0]<-NA;var.coef.pval[is.na(var.coef.eff)]<-NA; return(list(main.coef.eff,main.coef.pval, var.coef.eff,var.coef.pval)) }
/scratch/gouwar.j/cran-all/cranData/CIS.DGLM/R/DGLMsimu.functions.R
#' @title Forward Stepwise Selection for Real Data #' #' @description This function implements the forward stepwise variable selection procedure on a real data set. It utilizes the dglm function from the dglm packages to build the model and helps to account for more complex situations such as convergence issues with dglm and interaction terms in the model. In this function, we utilize a dummy value of "1" when initializing the model to avoid issues with a NULL value when adding variables to the model. #' #' @param dat.ana.num12.df The data set to be used to build the DGLM. #' @param ouput.name The name of the output file to which the results will be saved. #' @param num.loop The number of iterations that forward stepwise selection is performed (and hence how many variables will be in the final mean and variance models). Defaults to 10 iterations. #' @param typ.err Type 1 error. The default value is 0.05. #' #' @return A data frame with mean and variance mean effects and p-values associated with the coefficients for each loop. The function also produces a text file containing the model-building information at each stage of the loop (i.e. variables causing errors or warnings, the state of the model at each iteration, etc.). #' #' @examples #' library(dplyr) #' test.data <- simu.inter.dat.interboth(n.rep = 3, n.obs.per.rep = 15, ran.seed = 1) #' forward.sel.dglm.real(test.data) #' unlink(c('out1.txt')) #' @export forward.sel.dglm.real<-function(dat.ana.num12.df, ouput.name='out1.txt', num.loop=10,typ.err=0.05) { sink(ouput.name); current.mean.pool.LO<-current.var.pool.LO<-colnames(dat.ana.num12.df)[-1]; forward.mean.pool<-forward.var.pool<-1; # these are initialized to 1; cannot use NULL, or error is generated conflict.set<-vector(mode = "list", length = num.loop); for(k in 1:num.loop) { print(paste('-------------------------------------Running the',k,'th loop-----------------------------------------------' )); sig.val.mean<-sig.val.var<-typ.err; idx.mean<-idx.var<-NULL; print(paste('The current mean model is: ', paste('stress ~', paste(forward.mean.pool, collapse="+"),collapse = ''),sep='')) for(x in 1:length(current.mean.pool.LO)) { #print(forward.mean.pool) mean.x<-current.mean.pool.LO[x]; mean.model<- stats::as.formula(paste('stress ', paste(c(forward.mean.pool,mean.x), collapse="+"), sep="~")); var.model<-switch(is.null(forward.var.pool)+1,stats::as.formula(paste('~', paste(forward.var.pool, collapse="+"), sep="")),stats::as.formula('~ 1')) out<-tryCatch( {mod.forward.update<-dglm::dglm( mean.model, dformula=var.model,data=dat.ana.num12.df); res.mod.update<-summary(mod.forward.update); if (res.mod.update$coefficients%>%last<sig.val.mean) { sig.val.mean<-res.mod.update$coefficients%>%last; idx.mean<-x;} }, error=function(cond) {print(paste(mean.x, 'causing error when entering the model')); return(cond)}, warning=function(cond) {print(paste(mean.x, 'causing error when entering the model')); return(cond)} ); } if(!is.null(idx.mean)) { print(paste('Adding [',current.mean.pool.LO[idx.mean],'] to mean model, with p-value=',sig.val.mean,sep='')); forward.mean.pool<-c(forward.mean.pool,current.mean.pool.LO[idx.mean]); current.mean.pool.LO<-current.mean.pool.LO[-idx.mean]; } ## else print(paste('The current Var model is: ', paste(' ~', paste(forward.var.pool, collapse="+"),collapse = ''),sep='')) for(z in 1:length(current.var.pool.LO)) { var.z<-current.var.pool.LO[z]; mean.model<- stats::as.formula(paste('stress ', paste(forward.mean.pool, collapse="+"), sep="~")); var.model<- stats::as.formula(paste('~', paste(c(forward.var.pool,var.z), collapse="+"), sep="")); out<-tryCatch( {mod.forward.update<-dglm::dglm( mean.model, dformula=var.model,data=dat.ana.num12.df); res.mod.update<-summary(mod.forward.update); if (res.mod.update$dispersion.summary$coefficients%>%last<sig.val.var) { sig.val.var<-res.mod.update$dispersion.summary$coefficients%>%last; idx.var<-z;} }, error=function(cond) {print(paste(var.z, 'causing error when entering the model')); return(cond)}, warning=function(cond) {print(paste(var.z, 'causing error when entering the model')); return(cond)} ); } if(!is.null(idx.var)) {print(paste('Adding [',current.var.pool.LO[idx.var],'] to var model, with p-value=',sig.val.var,sep='')); forward.var.pool<-c(forward.var.pool,current.var.pool.LO[idx.var]); current.var.pool.LO<-current.var.pool.LO[-idx.var]; } } final.mean.model<- stats::as.formula(paste('stress ', paste(forward.mean.pool, collapse="+"), sep="~")); final.var.model<- stats::as.formula(paste('~', paste(forward.var.pool, collapse="+"), sep="")); final.mod.forward.update<-dglm::dglm(final.mean.model, dformula=final.var.model,data=dat.ana.num12.df); print('-----------------------------Final Model ----------------------------') summary(final.mod.forward.update); print(final.mean.model); print(final.var.model); print('--------------------Conflict variable with models ----------------------------') print(conflict.set) sink(NULL); sum.model<-summary(final.mod.forward.update) main.coef.eff<-colSums(sum.model$coefficients[,1][-1]*outer(forward.mean.pool[-1],colnames(dat.ana.num12.df)[-1],'==')) main.coef.pval<-colSums(sum.model$coefficients[,4][-1]*outer(forward.mean.pool[-1],colnames(dat.ana.num12.df)[-1],'==')) main.coef.eff[main.coef.eff==0]<-NA;main.coef.pval[is.na(main.coef.eff)]<-NA; var.coef.eff<-colSums(sum.model$dispersion.summary$coefficients[,1][-1]*outer(forward.var.pool[-1],colnames(dat.ana.num12.df)[-1],'==')) var.coef.pval<-colSums(sum.model$dispersion.summary$coefficients[,4][-1]*outer(forward.var.pool[-1],colnames(dat.ana.num12.df)[-1],'==')) var.coef.eff[var.coef.eff==0]<-NA;var.coef.pval[is.na(var.coef.eff)]<-NA; res<-rbind(main.coef.eff,main.coef.pval, var.coef.eff,var.coef.pval)%>%data.frame; colnames(res)<-colnames(dat.ana.num12.df)[-1]; rownames(res)<-c('main.eff','main.pval','var.eff','var.pval') return(res) } ### the function above performs the forward selection and produces a text file with the significant variables for mean and variance models and their corresponding pvalues
/scratch/gouwar.j/cran-all/cranData/CIS.DGLM/R/forselhyb.functions.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2022 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' \pkg{CITAN} is a library of functions useful in --- but not limited to --- #' quantitative research in the field of scientometrics. #' #' The package is deprecated, see \pkg{agop} instead. #' #' #' For the complete list of functions, call \code{library(help="CITAN")}. #' \cr\cr #' #' @name CITAN-package #' @aliases CITAN #' @docType package #' @title CITation ANalysis toolpack #' @author Marek Gagolewski #' @references #' Dubois D., Prade H., Testemale C. (1988). Weighted fuzzy pattern matching, #' Fuzzy Sets and Systems 28, s. 313-331.\cr #' Egghe L. (2006). Theory and practise of the g-index, Scientometrics 69(1), #' 131-152.\cr #' Gagolewski M., Grzegorzewski P. (2009). A geometric approach to the construction of #' scientific impact indices, Scientometrics 81(3), 617-634.\cr #' Gagolewski M., Debski M., Nowakiewicz M. (2009). Efficient algorithms for computing #' ''geometric'' scientific impact indices, Research Report of Systems #' Research Institute, Polish Academy of Sciences RB/1/2009.\cr #' Gagolewski M., Grzegorzewski P. (2010a). S-statistics and their basic properties, #' In: Borgelt C. et al (Eds.), Combining Soft Computing and Statistical #' Methods in Data Analysis, Springer-Verlag, 281-288.\cr #' Gagolewski M., Grzegorzewski P. (2010b). Arity-monotonic extended aggregation #' operators, In: Hullermeier E., Kruse R., Hoffmann F. (Eds.), #' Information Processing and Management of Uncertainty in Knowledge-Based #' Systems, CCIS 80, Springer-Verlag, 693-702.\cr #' Gagolewski M. (2011). Bibliometric Impact Assessment with R and the CITAN Package, #' Journal of Informetrics 5(4), 678-692.\cr #' Gagolewski M., Grzegorzewski P. (2011a). Axiomatic Characterizations of (quasi-) #' L-statistics and S-statistics and the Producer Assessment Problem, #; In: Galichet S., Montero J., Mauris G. (Eds.), Proc. 7th conf. European Society #' for Fuzzy Logic and Technology (EUSFLAT/LFA 2011), Atlantis Press, 53-58. #' Grabisch M., Pap E., Marichal J.-L., Mesiar R. (2009). Aggregation functions, #' Cambridge.\cr #' Gagolewski M., Grzegorzewski P. (2011b). Possibilistic analysis of arity-monotonic #' aggregation operators and its relation to bibliometric impact assessment #' of individuals, International Journal of Approximate Reasoning 52(9), 1312-1324.\cr #' Hirsch J.E. (2005). An index to quantify individual's scientific research output, #' Proceedings of the National Academy of Sciences 102(46), #' 16569-16572.\cr #' Kosmulski M. (2007). MAXPROD - A new index for assessment of the scientific output #' of an individual, and a comparison with the h-index, Cybermetrics 11(1).\cr #' Woeginger G.J. (2008). An axiomatic characterization of the Hirsch-index, #' Mathematical Social Sciences 56(2), 224-232.\cr #' Zhang J., Stevens M.A. (2009). A New and Efficient Estimation Method for the #' Generalized Pareto Distribution, Technometrics 51(3), 316-325.\cr #' #' @importFrom stringi stri_trim_both #' @importFrom stringi stri_replace_all_fixed #' @importFrom RSQLite dbGetInfo #' @importFrom RSQLite dbGetQuery #' @importFrom RSQLite dbCommit #' @importFrom DBI dbDriver #' @importFrom RSQLite dbConnect #' @importFrom DBI dbDisconnect #' @importFrom RSQLite dbListTables #' @importFrom grDevices as.graphicsAnnot #' @importFrom grDevices dev.interactive #' @importFrom grDevices devAskNewPage #' @importFrom graphics barplot #' @importFrom graphics boxplot #' @importFrom graphics mtext #' @importFrom graphics par #' @importFrom graphics pie #' @importFrom stats na.omit #' @importFrom utils read.csv invisible(NULL)
/scratch/gouwar.j/cran-all/cranData/CITAN/R/CITAN-package.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Given a list of authors' citation sequences, the function calculates #' values of many impact functions at a time. #' #' @title Calculate impact of given authors #' @param citseq list of numeric vectors, e.g. the output of \code{\link{lbsGetCitations}}. #' @param f a list of \eqn{n} functions which compute the impact of an author. #' The functions must calculate their values using numeric #' vectors passed as their first arguments. #' @param captions a list of \eqn{n} descriptive captions for the functions in \code{f}. #' @param orderByColumn column to sort the results on. \code{1} for author #' names, \code{2} for the first function in \code{f}, \code{3} #' for the second, and so on. #' @param bestRanks if not \code{NULL}, only a given number of authors #' with the greatest impact (for each function in \code{f}) will be included in the output. #' @param verbose logical; \code{TRUE} to inform about the progress of the process. #' @return A data frame in which each row corresponds to the assessment #' results of some citation sequence. #' The first column stands for the authors' names (taken from \code{names(citseq)}, #' the second for the valuation of \code{f[[1]]}, the third for \code{f[[2]]}, and so on. #' See Examples below. #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' citseq <- lbsGetCitations(conn, #' surveyDescription="Scientometrics", documentTypes="Article", #' idAuthors=c(39264,39265,39266)); #' print(citseq); #' ## $`Liu X.` # Author name #' ## 40116 34128 39122 29672 32343 32775 # IdDocument #' ## 11 4 1 0 0 0 # Citation count #' ## attr(,"IdAuthor") #' ## [1] 39264 # IdAuthor #' ## #' ## $`Xu Y.` #' ## 38680 38605 40035 40030 40124 39829 39745 29672 #' ## 30 14 8 6 6 5 3 0 #' ## attr(,"IdAuthor") #' ## [1] 39265 #' ## #' ## $`Wang Y.` #' ## 29992 29672 29777 32906 33858 33864 34704 #' ## 1 0 0 0 0 0 0 #' ## attr(,"IdAuthor") #' ## [1] 39266 #' library("agop") #' print(lbsAssess(citseq, #' f=list(length, sum, index.h, index.g, function(x) index.rp(x,1), #' function(x) sqrt(prod(index.lp(x,1))), #' function(x) sqrt(prod(index.lp(x,Inf)))), #' captions=c("length", "sum", "index.h", "index.g", "index.w", #' "index.lp1", "index.lpInf"))); #' ## Name length sum index.h index.g index.w index.lp1 index.lpInf #' ## 3 Xu Y. 8 72 5 8 7 8.573214 5.477226 #' ## 2 Wang Y. 7 1 1 1 1 1.000000 1.000000 #' ## 1 Liu X. 6 16 2 4 3 4.157609 3.316625 #' ## ... #' dbDisconnect(conn);} #' @export #' #' @importFrom agop index_h #' #' @seealso \code{\link{lbsConnect}}, \code{\link{lbsGetCitations}} lbsAssess <- function(citseq, f=list(length, index_h), captions=c("length", "index_h"), orderByColumn=2, bestRanks=20, verbose=T) { if (!class(citseq)=="list") stop("incorrect 'citseq'"); if (!is.null(bestRanks) && (!is.numeric(bestRanks) || bestRanks <= 0)) stop("incorrect 'bestRanks'"); if (class(f) != "list") stop("incorrect 'f'"); if (class(captions) != "character") stop("incorrect 'captions'"); if (length(f) != length(captions)) stop("'f' and 'captions' must be of the same length"); result <- data.frame(Name=names(citseq)); for (i in 1:length(f)) { if (verbose) cat(sprintf("Calculating %s... ", captions[i])); result <- cbind(result, sapply(citseq,f[[i]])); if (verbose) cat("DONE.\n"); } names(result)[2:(length(f)+1)] <- captions; result <- result[order(result[,orderByColumn]),] rownames(result) <- NULL; if (!is.null(bestRanks) && is.finite(bestRanks)) { wh <- numeric(0); for (i in 1:length(f)) { wh <- c(wh, which(rank(-result[,i+1],ties.method="min")<=bestRanks)); } return(result[unique(sort(wh,decreasing=TRUE)),]); } else return(result); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.assess.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Clears a Local Bibliometric Storage by dropping all tables #' named \code{Biblio_*} and all views named \code{ViewBiblio_*}. #' #' For safety reasons, an SQL transaction opened at the beginning of the #' removal process is not committed (closed) automatically. #' You should do manually (or rollback it), see Examples below. #' #' @title Clear a Local Bibliometric Storage #' @param conn database connection object, see \code{\link{lbsConnect}}. #' @param verbose logical; \code{TRUE} to be more verbose. #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' lbsClear(conn); #' dbCommit(conn); #' lbsCreate(conn); #' Scopus_ImportSources(conn); #' ## ... #' lbsDisconnect(conn);} #' #' @return \code{TRUE} on success. #' @export #' @importFrom RSQLite dbBegin #' #' @seealso \code{\link{lbsConnect}}, \code{\link{lbsCreate}}, #' \code{\link{Scopus_ImportSources}}, \code{\link{lbsDeleteAllAuthorsDocuments}} #' \code{\link{dbCommit}}, \code{\link{dbRollback}} lbsClear <- function(conn, verbose=TRUE) { .lbsCheckConnection(conn); # will stop on invalid/dead connection dbBegin(conn); objects <- dbListTables(conn); tables <- objects[substr(objects,1,7) == "Biblio_"]; views <- objects[substr(objects,1,11) == "ViewBiblio_"]; if (length(tables) == 0 && length(views) == 0) { warning("Your Local Bibliometric Storage is already empty."); return(TRUE); } if (length(tables) != 0) for (i in 1:length(tables)) { if (verbose) cat(sprintf("Dropping table '%s'... ", tables[i])); dbExecQuery(conn, sprintf("DROP TABLE %s;", tables[i]), TRUE); if (verbose) cat("DONE.\n"); } if (length(views) != 0) for (i in 1:length(views)) { if (verbose) cat(sprintf("Dropping view '%s'... ", views[i])); dbExecQuery(conn, sprintf("DROP VIEW %s;", views[i]), TRUE); if (verbose) cat("DONE.\n"); } warning("Transaction has not been committed yet. Please use dbCommit(...) or dbRollback(...)."); return(TRUE); } #' Deletes author, citation, document, and survey information from a Local Bibliometric #' Storage. #' #' For safety reasons, an SQL transaction opened at the beginning of the #' removal process is not committed (closed) automatically. #' You should do manually (or rollback it), see Examples below. #' #' @title Delete all authors, documents and surveys from a Local Bibliometric Storage #' @param conn database connection object, see \code{\link{lbsConnect}}. #' @param verbose logical; \code{TRUE} to be more verbose. #' @return \code{TRUE} on success. #' @export #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db") #' lbsDeleteAllAuthorsDocuments(conn) #' dbCommit(conn) #' ## ... #' lbsDisconnect(conn)} #' @seealso #' \code{\link{lbsClear}}, #' \code{\link{dbCommit}}, #' \code{\link{dbRollback}} lbsDeleteAllAuthorsDocuments <- function(conn, verbose=TRUE) { .lbsCheckConnection(conn); # will stop on invalid/dead connection if (verbose) cat(sprintf("Deleting all author and document information... ")); dbBegin(conn); dbExecQuery(conn, "DELETE FROM Biblio_DocumentsSurveys", TRUE); dbExecQuery(conn, "DELETE FROM Biblio_AuthorsDocuments", TRUE); dbExecQuery(conn, "DELETE FROM Biblio_Surveys", TRUE); dbExecQuery(conn, "DELETE FROM Biblio_Authors", TRUE); dbExecQuery(conn, "DELETE FROM Biblio_Citations", TRUE); dbExecQuery(conn, "DELETE FROM Biblio_Documents", TRUE); if (verbose) cat(sprintf("DONE.\n")); warning("Transaction has not been committed yet. Please use dbCommit(...) or dbRollback(...)."); return(TRUE); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.clear.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' @title Connect to a Local Bibliometric Storage #' #' @description #' Connects to a Local Bibliometric Storage handled by the SQLite engine #' (see \pkg{RSQLite} package documentation). #' #' @details #' Do not forget to close the connection (represented by the connection object returned) #' with the \code{\link{lbsDisconnect}} function after use. #' #' Please note that the database may be also accessed by using #' lower-level functions from the \pkg{DBI} package called on the #' returned connection object. The table-view structure of a Local #' Bibliometric Storage is presented in the man page of the #' \code{\link{lbsCreate}} function. #' #' @export #' @param dbfilename filename of an SQLite database. #' @return An object of type \code{SQLiteConnection}, used to communicate with the SQLite engine. #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db") #' ## ... #' lbsDisconnect(conn)} #' @seealso \code{\link{lbsCreate}}, #' \code{\link{lbsDisconnect}} lbsConnect <- function(dbfilename) { if (length(dbfilename)!=1 || !is.character(dbfilename)) stop("incorrect 'dbfilename' given"); drv <- dbDriver("SQLite"); conn <- dbConnect(drv, dbname = dbfilename); objects <- dbListTables(conn); tables <- objects[substr(objects,1,7) == "Biblio_"]; views <- objects[substr(objects,1,11) == "ViewBiblio_"]; if (length(tables) == 0 && length(views) == 0) { warning("Your Local Bibliometric Storage is empty. Use lbsCreate(...) to establish one."); } else if (any((tables == "Biblio_Countries") | (tables == "Biblio_Languages"))) { warning("Your Local Bibliometric Storage seems to be created with an older version of CITAN. Please re-create the database."); } return(conn); } #' Disconnects from a Local Bibliometric Storage. #' #' #' @title Disconnect from a Local Bibliometric Storage #' @param conn database connection object, see \code{\link{lbsConnect}}. #' @export #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' lbsDisconnect(conn);} #' @seealso \code{\link{lbsConnect}} lbsDisconnect <- function(conn) { .lbsCheckConnection(conn); # will stop on an invalid/dead connection dbDisconnect(conn); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.connect.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' @description #' Creates an empty Local Bibliometric Storage. #' #' @details #' The function may be executed only if the database contains no tables #' named \code{Biblio_*} and no views named \code{ViewBiblio_*}. #' #' The following SQL code is executed. #' \preformatted{ #' CREATE TABLE Biblio_Categories (\cr #' -- Source classification codes (e.g. ASJC)\cr #' IdCategory INTEGER PRIMARY KEY ASC,\cr #' IdCategoryParent INTEGER NOT NULL,\cr #' Description VARCHAR(63) NOT NULL,\cr #' FOREIGN KEY(IdCategoryParent) REFERENCES Biblio_Categories(IdCategory)\cr #' ); #' } #' #' #' \preformatted{ #' CREATE TABLE Biblio_Sources ( #' IdSource INTEGER PRIMARY KEY AUTOINCREMENT, #' AlternativeId VARCHAR(31) UNIQUE NOT NULL, #' Title VARCHAR(255) NOT NULL, #' IsActive BOOLEAN, #' IsOpenAccess BOOLEAN, #' Type CHAR(2) CHECK (Type IN ('bs', 'cp', 'jo')), #' -- Book Series / Conference Proceedings / Journal #' -- or NULL in all other cases #' Impact1 REAL, -- value of an impact factor #' Impact2 REAL, -- value of an impact factor #' Impact3 REAL, -- value of an impact factor #' Impact4 REAL, -- value of an impact factor #' Impact5 REAL, -- value of an impact factor #' Impact6 REAL, -- value of an impact factor #' ); #' } #' #' \preformatted{ #' CREATE TABLE Biblio_SourcesCategories ( #' -- links Sources and Categories #' IdSource INTEGER NOT NULL, #' IdCategory INTEGER NOT NULL, #' PRIMARY KEY(IdSource, IdCategory), #' FOREIGN KEY(IdSource) REFERENCES Biblio_Sources(IdSource), #' FOREIGN KEY(IdCategory) REFERENCES Biblio_Categories(IdCategory) #' ); #' } #' #' #' \preformatted{ #' CREATE TABLE Biblio_Documents ( #' IdDocument INTEGER PRIMARY KEY AUTOINCREMENT, #' IdSource INTEGER, #' AlternativeId VARCHAR(31) UNIQUE NOT NULL, #' Title VARCHAR(255) NOT NULL, #' BibEntry TEXT, #' -- (e.g. Source Title,Year,Volume,Issue,Article Number,PageStart,PageEnd) #' Year INTEGER, #' Pages INTEGER, #' Citations INTEGER NOT NULL, #' Type CHAR(2) CHECK (Type IN ('ar', 'ip', 'bk', #' 'cp', 'ed', 'er', 'le', 'no', 'rp', 're', 'sh')), #' -- Article-ar / Article in Press-ip / Book-bk / #' -- Conference Paper-cp / Editorial-ed / Erratum-er / #' -- Letter-le/ Note-no / Report-rp / Review-re / Short Survey-sh #' -- or NULL in all other cases #' FOREIGN KEY(IdSource) REFERENCES Biblio_Sources(IdSource), #' FOREIGN KEY(IdLanguage) REFERENCES Biblio_Languages(IdLanguage) #' ); #' } #' #' #' \preformatted{ #' CREATE TABLE Biblio_Citations ( #' IdDocumentParent INTEGER NOT NULL, # cited document #' IdDocumentChild INTEGER NOT NULL, # reference #' PRIMARY KEY(IdDocumentParent, IdDocumentChild), #' FOREIGN KEY(IdDocumentParent) REFERENCES Biblio_Documents(IdDocument), #' FOREIGN KEY(IdDocumentChild) REFERENCES Biblio_Documents(IdDocument) #' ); #' } #' #' #' \preformatted{ #' CREATE TABLE Biblio_Surveys ( #' -- each call to lbsImportDocuments() puts a new record here, #' -- they may be grouped into so-called 'Surveys' using 'Description' field #' IdSurvey INTEGER PRIMARY KEY AUTOINCREMENT, #' Description VARCHAR(63) NOT NULL, -- survey group name #' FileName VARCHAR(63), -- original file name #' Timestamp DATETIME -- date of file import #' ); #' } #' #' #' #' \preformatted{ #' CREATE TABLE Biblio_DocumentsSurveys ( #' -- note that the one Document may often be found in many Surveys #' IdDocument INTEGER NOT NULL, #' IdSurvey INTEGER NOT NULL, #' PRIMARY KEY(IdDocument, IdSurvey), #' FOREIGN KEY(IdSurvey) REFERENCES Biblio_Surveys(IdSurvey), #' FOREIGN KEY(IdDocument) REFERENCES Biblio_Documents(IdDocument) #' ); #' } #' #' \preformatted{ #' CREATE TABLE Biblio_Authors ( #' IdAuthor INTEGER PRIMARY KEY AUTOINCREMENT, #' Name VARCHAR(63) NOT NULL, #' AuthorGroup VARCHAR(31), # used to merge authors with non-unique representations #' ); #' } #' #' \preformatted{ #' CREATE TABLE Biblio_AuthorsDocuments ( #' -- links Authors and Documents #' IdAuthor INTEGER NOT NULL, #' IdDocument INTEGER NOT NULL, #' PRIMARY KEY(IdAuthor, IdDocument), #' FOREIGN KEY(IdAuthor) REFERENCES Biblio_Authors(IdAuthor), #' FOREIGN KEY(IdDocument) REFERENCES Biblio_Documents(IdDocument) #' ); #' } #' #' In addition, the following views are created. #' \preformatted{ #' CREATE VIEW ViewBiblio_DocumentsSurveys AS #' SELECT #' Biblio_DocumentsSurveys.IdDocument AS IdDocument, #' Biblio_DocumentsSurveys.IdSurvey AS IdSurvey, #' Biblio_Surveys.Description AS Description, #' Biblio_Surveys.Filename AS Filename, #' Biblio_Surveys.Timestamp AS Timestamp #' FROM Biblio_DocumentsSurveys #' JOIN Biblio_Surveys #' ON Biblio_DocumentsSurveys.IdSurvey=Biblio_Surveys.IdSurvey; #' } #' #' \preformatted{ #' CREATE VIEW ViewBiblio_DocumentsCategories AS #' SELECT #' IdDocument AS IdDocument, #' DocSrcCat.IdCategory AS IdCategory, #' DocSrcCat.Description AS Description, #' DocSrcCat.IdCategoryParent AS IdCategoryParent, #' Biblio_Categories.Description AS DescriptionParent #' FROM #' ( #' SELECT #' Biblio_Documents.IdDocument AS IdDocument, #' Biblio_SourcesCategories.IdCategory AS IdCategory, #' Biblio_Categories.Description AS Description, #' Biblio_Categories.IdCategoryParent AS IdCategoryParent #' FROM Biblio_Documents #' JOIN Biblio_SourcesCategories #' ON Biblio_Documents.IdSource=Biblio_SourcesCategories.IdSource #' JOIN Biblio_Categories #' ON Biblio_SourcesCategories.IdCategory=Biblio_Categories.IdCategory #' ) AS DocSrcCat #' JOIN Biblio_Categories #' ON DocSrcCat.IdCategoryParent=Biblio_Categories.IdCategory; #' } #' #' @title Create a Local Bibliometric Storage #' @param conn a connection object, see \code{\link{lbsConnect}}. #' @param verbose logical; \code{TRUE} to be more verbose. #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' lbsCreate(conn); #' Scopus_ImportSources(conn); #' ## ... #' lbsDisconnect(conn);} #' #' @return \code{TRUE} on success. #' #' @export #' #' @seealso #' \code{\link{lbsConnect}}, #' \code{\link{lbsClear}}, #' \code{\link{Scopus_ImportSources}}, #' \code{\link{lbsTidy}} lbsCreate <- function(conn, verbose=TRUE) { .lbsCheckConnection(conn); # will stop on invalid/dead connection ## --------- auxiliary function ------------------------------------------- #' /internal/ .lbsCreateTable <- function(conn, tablename, query, verbose) { if (verbose) cat(sprintf("Creating table '%s'... ", tablename)); dbExecQuery(conn, query, FALSE); if (verbose) cat("Done.\n"); } ## --------- auxiliary function ------------------------------------------- #' /internal/ .lbsCreateView <- function(conn, viewname, query, verbose) { if (verbose) cat(sprintf("Creating view '%s'... ", viewname)); dbExecQuery(conn, query, FALSE); if (verbose) cat("Done.\n"); } ## --------- auxiliary function ------------------------------------------- #' /internal/ .lbsCreateIndex <- function(conn, indexname, query, verbose) { if (verbose) cat(sprintf("Creating index for '%s'... ", indexname)); dbExecQuery(conn, query, FALSE); if (verbose) cat("Done.\n"); } ## ---- check whether LBS is empty ------------------------------------ tablesviews <- dbListTables(conn); if (any(substr(tablesviews, 1, 7) == "Biblio_")) stop("Your Local Bibliometric Storage is not empty."); if (any(substr(tablesviews, 1, 11) == "ViewBiblio_")) stop("Your Local Bibliometric Storage is not empty."); ## ------------------------------------------------------------------- query <- "CREATE TABLE Biblio_Categories ( IdCategory INTEGER PRIMARY KEY ASC, IdCategoryParent INTEGER NOT NULL, Description VARCHAR(63) NOT NULL, FOREIGN KEY(IdCategoryParent) REFERENCES Biblio_Categories(IdCategory) );" .lbsCreateTable(conn, "Biblio_Categories", query, verbose); query <- "CREATE TABLE Biblio_Sources ( IdSource INTEGER PRIMARY KEY NOT NULL, AlternativeId VARCHAR(31) UNIQUE NOT NULL, Title VARCHAR(255) NOT NULL, IsActive BOOLEAN, IsOpenAccess BOOLEAN, Type CHAR(2) CHECK (Type IN ('bs', 'cp', 'jo')), Impact1 REAL, Impact2 REAL, Impact3 REAL, Impact4 REAL, Impact5 REAL, Impact6 REAL );" .lbsCreateTable(conn, "Biblio_Sources", query, verbose); query <- "CREATE INDEX IF NOT EXISTS Biblio_Sources_Title ON Biblio_Sources (Title ASC);"; .lbsCreateIndex(conn, "Biblio_Sources", query, verbose); query <- "CREATE TABLE Biblio_SourcesCategories ( IdSource INTEGER NOT NULL, IdCategory INTEGER NOT NULL, PRIMARY KEY(IdSource, IdCategory), FOREIGN KEY(IdSource) REFERENCES Biblio_Sources(IdSource), FOREIGN KEY(IdCategory) REFERENCES Biblio_Categories(IdCategory) );" .lbsCreateTable(conn, "Biblio_SourcesCategories", query, verbose); query <- "CREATE TABLE Biblio_Documents ( IdDocument INTEGER PRIMARY KEY AUTOINCREMENT, IdSource INTEGER, AlternativeId VARCHAR(31) UNIQUE NOT NULL, Title VARCHAR(255), BibEntry TEXT, Year INTEGER, Pages INTEGER, Citations INTEGER NOT NULL, Type CHAR(2) CHECK (Type IN ('ar', 'ip', 'bk', 'cp', 'ed', 'er', 'le', 'no', 'rp', 're', 'sh')), FOREIGN KEY(IdSource) REFERENCES Biblio_Sources(IdSource) );" .lbsCreateTable(conn, "Biblio_Documents", query, verbose); query <- "CREATE TABLE Biblio_Citations ( IdDocumentParent INTEGER NOT NULL, IdDocumentChild INTEGER NOT NULL, PRIMARY KEY(IdDocumentParent, IdDocumentChild), FOREIGN KEY(IdDocumentParent) REFERENCES Biblio_Documents(IdDocument), FOREIGN KEY(IdDocumentChild) REFERENCES Biblio_Documents(IdDocument) );" .lbsCreateTable(conn, "Biblio_Citations", query, verbose); query <- "CREATE TABLE Biblio_Surveys ( IdSurvey INTEGER PRIMARY KEY AUTOINCREMENT, Description VARCHAR(63) NOT NULL, FileName VARCHAR(63), Timestamp DATETIME );" .lbsCreateTable(conn, "Biblio_Surveys", query, verbose); query <- "CREATE TABLE Biblio_DocumentsSurveys ( IdDocument INTEGER NOT NULL, IdSurvey INTEGER NOT NULL, PRIMARY KEY(IdDocument, IdSurvey), FOREIGN KEY(IdSurvey) REFERENCES Biblio_Surveys(IdSurvey), FOREIGN KEY(IdDocument) REFERENCES Biblio_Documents(IdDocument) );" .lbsCreateTable(conn, "Biblio_DocumentsSurveys", query, verbose); query <- "CREATE TABLE Biblio_Authors ( IdAuthor INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(63) NOT NULL, AuthorGroup VARCHAR(31) );" .lbsCreateTable(conn, "Biblio_Authors", query, verbose); query <- "CREATE TABLE Biblio_AuthorsDocuments ( IdAuthor INTEGER NOT NULL, IdDocument INTEGER NOT NULL, PRIMARY KEY(IdAuthor, IdDocument), FOREIGN KEY(IdAuthor) REFERENCES Biblio_Authors(IdAuthor), FOREIGN KEY(IdDocument) REFERENCES Biblio_Documents(IdDocument) );" .lbsCreateTable(conn, "Biblio_AuthorsDocuments", query, verbose); query <- "CREATE VIEW ViewBiblio_DocumentsSurveys AS SELECT Biblio_DocumentsSurveys.IdDocument AS IdDocument, Biblio_DocumentsSurveys.IdSurvey AS IdSurvey, Biblio_Surveys.Description AS Description, Biblio_Surveys.Filename AS Filename, Biblio_Surveys.Timestamp AS Timestamp FROM Biblio_DocumentsSurveys JOIN Biblio_Surveys ON Biblio_DocumentsSurveys.IdSurvey=Biblio_Surveys.IdSurvey;"; .lbsCreateView(conn, "ViewBiblio_DocumentsSurveys", query, verbose); query <- "CREATE VIEW ViewBiblio_DocumentsCategories AS SELECT IdDocument AS IdDocument, DocSrcCat.IdCategory AS IdCategory, DocSrcCat.Description AS Description, DocSrcCat.IdCategoryParent AS IdCategoryParent, Biblio_Categories.Description AS DescriptionParent FROM ( SELECT Biblio_Documents.IdDocument AS IdDocument, Biblio_SourcesCategories.IdCategory AS IdCategory, Biblio_Categories.Description AS Description, Biblio_Categories.IdCategoryParent AS IdCategoryParent FROM Biblio_Documents JOIN Biblio_SourcesCategories ON Biblio_Documents.IdSource=Biblio_SourcesCategories.IdSource JOIN Biblio_Categories ON Biblio_SourcesCategories.IdCategory=Biblio_Categories.IdCategory ) AS DocSrcCat JOIN Biblio_Categories ON DocSrcCat.IdCategoryParent=Biblio_Categories.IdCategory;"; .lbsCreateView(conn, "ViewBiblio_DocumentsCategories", query, verbose); # ------------------------------------------------------------------- if (verbose) cat("Your Local Bibliometric Storage has been created. Perhaps now you may wish to use Scopus_ImportSources(...) to import source information.\n"); return(TRUE); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.create.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Creates ordered citation sequences of authors in a Local Bibliometric Storage. #' #' A citation sequence is a numeric vector #' consisting of citation counts of all the documents mapped to #' selected authors. #' However, the function may take into account only the documents #' from a given Survey (using \code{surveyDescription} #' parameter) or of chosen types (\code{documentTypes}). #' #' @title Fetch authors' citation sequences #' @param conn a connection object as produced by \code{\link{lbsConnect}}. #' @param documentTypes character vector or \code{NULL}; specifies document types to restrict to; #' a combination of \code{Article}, \code{Article in Press}, \code{Book}, \code{Conference Paper}, #' \code{Editorial}, \code{Erratum}, \code{Letter}, \code{Note}, \code{Report}, \code{Review}, #' \code{Short Survey}. \code{NULL} means no restriction. #' @param surveyDescription single character string or \code{NULL}; survey to restrict to or \code{NULL} for no restriction. #' @param idAuthors numeric vector of authors' identifiers for which the sequences are to be created or \code{NULL} for all authors in the database. #' @param verbose logical; \code{TRUE} to inform about the progress of the process. #' @return A list of non-increasingly ordered numeric vectors is returned. Each element of the list corresponds #' to a citation sequence of some author. List \code{names} attribute are #' set to authors' names. Moreover, each vector has a set \code{IdAuthor} #' attribute, which uniquely identifies the corresponding record in the table \code{Biblio_Authors}. #' Citation counts come together with \code{IdDocument}s (vector elements are named). #' #' The list of citation sequences may then be used to calculate #' authors' impact using \code{\link{lbsAssess}} (see Examples below). #' #' @export #' #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' citseq <- lbsGetCitations(conn, #' surveyDescription="Scientometrics", documentTypes="Article", #' idAuthors=c(39264,39265,39266)); #' print(citseq); #' ## $`Liu X.` # Author name #' ## 40116 34128 39122 29672 32343 32775 # IdDocument #' ## 11 4 1 0 0 0 # Citation count #' ## attr(,"IdAuthor") #' ## [1] 39264 # IdAuthor #' ## #' ## $`Xu Y.` #' ## 38680 38605 40035 40030 40124 39829 39745 29672 #' ## 30 14 8 6 6 5 3 0 #' ## attr(,"IdAuthor") #' ## [1] 39265 #' ## #' ## $`Wang Y.` #' ## 29992 29672 29777 32906 33858 33864 34704 #' ## 1 0 0 0 0 0 0 #' ## attr(,"IdAuthor") #' ## [1] 39266 #' print(lbsAssess(citseq, #' f=list(length, sum, index.h, index.g, function(x) index.rp(x,1), #' function(x) sqrt(prod(index.lp(x,1))), #' function(x) sqrt(prod(index.lp(x,Inf)))), #' captions=c("length", "sum", "index.h", "index.g", "index.w", #' "index.lp1", "index.lpInf"))); #' ## Name length sum index.h index.g index.w index.lp1 index.lpInf #' ## 3 Xu Y. 8 72 5 8 7 8.573214 5.477226 #' ## 2 Wang Y. 7 1 1 1 1 1.000000 1.000000 #' ## 1 Liu X. 6 16 2 4 3 4.157609 3.316625 #' ## ... #' dbDisconnect(conn);} #' @seealso #' \code{\link{lbsConnect}}, #' \code{\link{lbsAssess}} lbsGetCitations <- function(conn, documentTypes=NULL, surveyDescription=NULL, idAuthors=NULL, verbose=TRUE ) { .lbsCheckConnection(conn); # will stop on invalid/dead connection # ----------------------------------------------------- # Data set restrictions & subset stats surveyDescription <- .lbs_PrepareRestriction_SurveyDescription(conn, surveyDescription); documentTypesShort <- .lbs_PrepareRestriction_DocumentTypes(conn, documentTypes); # Get subQueryWhere if (length(documentTypesShort)>0) { subQueryWhere <- sprintf("(%s)", paste("Type", documentTypesShort, sep="=", collapse=" OR ")); } else subQueryWhere <- "1"; if (!is.null(surveyDescription)) subQueryWhere <- paste(c(subQueryWhere, sprintf(" Description='%s'", surveyDescription)), collapse=" AND "); if (verbose) { cat("Data set restrictions:\n"); cat(sprintf("\tSurvey: %s.\n", ifelse(is.null(surveyDescription), "<ALL>", surveyDescription))); cat(sprintf("\tDocument types: %s.\n", ifelse(is.null(documentTypesShort), "<ALL>", paste(documentTypesShort, collapse=", ")))); cat("\n"); } # --------------------------------------------------------------------- if (!is.null(idAuthors) && (!is.numeric(idAuthors) || any(!is.finite(idAuthors)))) stop("incorrect 'idAuthors' given"); if (length(idAuthors) == 0) { query <- sprintf(" SELECT IdAuthor FROM ( SELECT DISTINCT Biblio_AuthorsDocuments.IdAuthor FROM Biblio_AuthorsDocuments JOIN ( SELECT Biblio_Documents.IdDocument FROM Biblio_Documents JOIN ViewBiblio_DocumentsSurveys ON ViewBiblio_DocumentsSurveys.IdDocument=Biblio_Documents.IdDocument WHERE %s ) AS Docs ON Docs.IdDocument=Biblio_AuthorsDocuments.IdDocument );", subQueryWhere); idAuthors <- dbGetQuery(conn, query)[,1]; if (length(idAuthors) == 0) return(list()); } i <- 1L; k <- 0L; n <- as.integer(length(idAuthors)); citseq <- list(); length(citseq) <- n; if (verbose) { cat("Creating citation sequences... "); } while (i <= n) { query <- sprintf(" SELECT DISTINCT Biblio_Authors2.Name AS Name, Biblio_Documents.IdDocument AS IdDocument, Biblio_Documents.Citations AS Citations FROM ( SELECT Name, IdAuthor FROM Biblio_Authors WHERE IdAuthor=%s ) AS Biblio_Authors2 JOIN Biblio_AuthorsDocuments ON (Biblio_Authors2.IdAuthor=Biblio_AuthorsDocuments.IdAuthor) JOIN ViewBiblio_DocumentsSurveys ON (Biblio_AuthorsDocuments.IdDocument=ViewBiblio_DocumentsSurveys.IdDocument) JOIN Biblio_Documents ON (Biblio_AuthorsDocuments.IdDocument=Biblio_Documents.IdDocument) WHERE %s ORDER BY Biblio_Documents.Citations DESC", sqlNumericOrNULL(idAuthors[i]), subQueryWhere ); AuthorInfo <- dbGetQuery(conn, query); if (nrow(AuthorInfo) > 0) { names(citseq)[i] <- AuthorInfo$Name[1]; citseq[[i]] <- as.numeric(AuthorInfo$Citations); names(citseq[[i]]) <- as.numeric(AuthorInfo$IdDocument); attr(citseq[[i]], "IdAuthor") <- idAuthors[i]; k <- k+1L; } i <- i+1L; } if (verbose) cat(sprintf("OK, %g of %g records read.\n", k, n)); return(citseq); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.getcitations.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2022 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Imports bibliographic data from a special 11-column \code{data.frame} object #' (see e.g. \code{\link{Scopus_ReadCSV}}) into a Local Bibliometric Storage. #' #' \code{data} must consist of the following 11 columns (in order). Otherwise #' the process will not be executed. #' \tabular{llll}{ #' 1 \tab \code{Authors} \tab character\tab Author(s) name(s), comma-separated, surnames first.\cr #' 2 \tab \code{Title} \tab character\tab Document title.\cr #' 3 \tab \code{Year} \tab numeric \tab Year of publication.\cr #' 4 \tab \code{SourceTitle} \tab character\tab Title of the source containing the document.\cr #' 5 \tab \code{Volume} \tab character\tab Volume.\cr #' 6 \tab \code{Issue} \tab character\tab Issue.\cr #' 7 \tab \code{PageStart} \tab numeric \tab Start page; numeric.\cr #' 8 \tab \code{PageEnd} \tab numeric \tab End page; numeric.\cr #' 9 \tab \code{Citations} \tab numeric \tab Number of citations; numeric.\cr #' 10 \tab \code{AlternativeId} \tab character\tab Alternative document identifier. \cr #' 11 \tab \code{DocumentType} \tab factor \tab Type of the document.\cr #' } #' #' \code{DocumentType} is one of \dQuote{Article}, \dQuote{Article in Press}, #' \dQuote{Book}, \dQuote{Conference Paper}, \dQuote{Editorial}, \dQuote{Erratum}, #' \dQuote{Letter}, \dQuote{Note}, \dQuote{Report}, #' \dQuote{Review}, \dQuote{Short Survey}, or \code{NA} (other categories are interpreted as \code{NA}). #' #' Note that if \code{data} contains a large number of records (>1000), #' the whole process may take a few minutes. #' #' Sources (e.g. journals) are identified by SourceTitle (table \code{Biblio_Sources}). #' Note that generally there is no need to concern about missing SourceTitles of #' conference proceedings. #' #' Each time a function is called, a new record in the table \code{Biblio_Surveys} #' is created. Such surveys may be grouped using the \code{Description} #' field, see \code{\link{lbsCreate}}. #' #' @title Import bibliographic data into a Local Bibliometric Storage. #' @param conn a connection object, see \code{\link{lbsConnect}}. #' @param data 11 column \code{data.frame} with bibliometric entries; see above. #' @param surveyDescription description of the survey. Allows for documents grouping. #' @param surnameFirstnameCommaSeparated logical; indicates wher surnames are separated from first names (or initials) by comma or by space (\code{FALSE}, default). #' @param originalFilename original filename; \code{attr(data, "filename")} used by default. #' @param excludeRows a numeric vector with row numbers of \code{data} to be excluded or \code{NULL}. #' @param updateDocumentIfExists logical; if \code{TRUE} then documents with existing \code{AlternativeId} will be updated. #' @param warnSourceTitle logical; if \code{TRUE} then warnings are generated if a given SourceTitle is not found in \code{Biblio_Sources}. #' @param warnExactDuplicates logical; \code{TRUE} to warn if exact duplicates are found (turned off by default). #' @param verbose logical; \code{TRUE} to display progress information. #' @return \code{TRUE} on success. #' @seealso \code{\link{Scopus_ReadCSV}}, \code{\link{lbsConnect}}, \code{\link{lbsCreate}} #' #' @export #' #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' data <- Scopus_ReadCSV("db_Polish_MATH/Poland_MATH_1987-1993.csv"); #' lbsImportDocuments(conn, data, "Poland_MATH"); #' ## ... #' lbsDisconnect(conn);} lbsImportDocuments <- function(conn, data, surveyDescription="Default survey", surnameFirstnameCommaSeparated = FALSE, originalFilename=attr(data, "filename"), excludeRows=NULL, updateDocumentIfExists=TRUE, warnSourceTitle=TRUE, warnExactDuplicates=FALSE, verbose=TRUE) { .lbsCheckConnection(conn); # will stop on invalid/dead connection ## --------- auxiliary function ------------------------------------------- # /internal/ # Creates a new survey # @return idSurvey .lbsImportDocuments_GetSurvey <- function(conn, surveyDescription, originalFilename, verbose) { query <- sprintf("INSERT INTO Biblio_Surveys('Description', 'FileName', 'Timestamp') VALUES(%s, %s, %s)", sqlStringOrNULL(surveyDescription), sqlStringOrNULL(originalFilename), sqlStringOrNULL(format(Sys.time(), "%Y-%m-%d %H:%M:%S")) ); dbExecQuery(conn, query, TRUE); return(as.numeric(dbGetQuery(conn, "SELECT last_insert_rowid()")[1,1])); } ## --------- auxiliary function ------------------------------------------- # /internal/ .lbsImportDocuments_Add_Get_idSource <- function(conn, sourceTitle, i, warnSourceTitle) { if (is.na(sourceTitle)) return(NA); sourceTitle <- sqlStringOrNULL(sourceTitle); idSource <- dbGetQuery(conn, sprintf("SELECT IdSource, IsActive FROM Biblio_Sources WHERE UPPER(Title)=UPPER(%s)", sourceTitle )); if (nrow(idSource)==1) { return(idSource[1,1]); } else if (nrow(idSource)==0) { if (warnSourceTitle) { warning(sprintf("no source with sourceTitle='%s' found for record %g. Setting IdSource=NA.", sourceTitle, i)); } return(NA); } else { active = which(as.logical(idSource[,2])); if (length(active) == 1) { if (warnSourceTitle) warning(sprintf("more than one source with sourceTitle='%s' found for record %g. Using the only active.", sourceTitle, i)); return(idSource[active,1]); } else if (length(active) > 1) { if (warnSourceTitle) warning(sprintf("more than one source with sourceTitle='%s' found for record %g. Using first active.", sourceTitle, i)); return(idSource[active[1],1]); } else { if (warnSourceTitle) warning(sprintf("more than one source with sourceTitle='%s' found for record %g. Using first (no active).", sourceTitle, i)); return(idSource[1,1]); } } } ## --------- auxiliary function ------------------------------------------- # /internal/ .lbsImportDocuments_Add <- function(conn, record, idAuthors, idSurvey, i, surnameFirstnameCommaSeparated, updateDocumentIfExists, warnExactDuplicates, warnSourceTitle, verbose) { idSource <- sqlNumericOrNULL(.lbsImportDocuments_Add_Get_idSource(conn, record$SourceTitle, i, warnSourceTitle)); res <- dbGetQuery(conn, sprintf("SELECT IdDocument, IdSource, Title, BibEntry, Citations, Type FROM Biblio_Documents WHERE UPPER(AlternativeId)=UPPER('%s');", record$AlternativeId)); if (nrow(res) != 0) { documentExists <- TRUE; idDocument <- res$IdDocument[1]; if (warnExactDuplicates) { warning(sprintf("source at row=%g already exists (IdSource=%g, Title='%s', Citations=%g, Type='%s'). %s.", i, res$IdSource[1], res$Title[1], res$Citations[1], res$Type[1], ifelse(updateDocumentIfExists, "Updating", "Ignoring"))); } if (updateDocumentIfExists) { # will add authors once again later (they may be different) dbExecQuery(conn, sprintf("DELETE FROM Biblio_AuthorsDocuments WHERE IdDocument=%g;", idDocument), TRUE); # Update document query <- sprintf("UPDATE Biblio_Documents SET IdSource=%s, AlternativeId='%s', Title='%s', BibEntry='%s', Year=%s, Pages=%s, Citations=%s, Type=%s WHERE IdDocument=%s;", idSource, record$AlternativeId, record$Title, record$BibEntry, record$Year, record$Pages, record$Citations, record$DocumentType, sqlNumericOrNULL(idDocument) ); dbExecQuery(conn, query, TRUE); } } else { documentExists <- FALSE; # Insert document query <- sprintf("INSERT OR FAIL INTO Biblio_Documents ('IdSource', 'AlternativeId', 'Title', 'BibEntry', 'Year', 'Pages', 'Citations', 'Type') VALUES(%s, '%s', '%s', '%s', %s, %s, %s, %s);", idSource, record$AlternativeId, record$Title, record$BibEntry, record$Year, record$Pages, record$Citations, record$DocumentType ); dbExecQuery(conn, query, TRUE); idDocument <- dbGetQuery(conn, "SELECT last_insert_rowid()")[1,1]; } query <- sprintf("INSERT INTO Biblio_DocumentsSurveys (IdDocument, IdSurvey) VALUES(%s, %s);", sqlNumericOrNULL(idDocument), sqlNumericOrNULL(idSurvey)); dbExecQuery(conn, query, TRUE); if (documentExists && !updateDocumentIfExists) return(FALSE); for (j in 1:length(idAuthors)) { query <- sprintf("INSERT OR IGNORE INTO Biblio_AuthorsDocuments(IdAuthor, IdDocument) %s", paste( sprintf("SELECT %s AS 'IdAuthor', %s AS 'IdDocument'", sqlNumericOrNULL(idAuthors), sqlNumericOrNULL(idDocument)), collapse=" UNION ")); dbExecQuery(conn, query, TRUE); } return(!documentExists) } ## ------ check data ------------------------------------------------------ if (class(data) != "data.frame") stop("'data' is not a data.frame."); if (ncol(data) != 11 || is.null(data$Authors) || is.null(data$Title) || is.null(data$Year) || is.null(data$SourceTitle) || is.null(data$Volume) || is.null(data$Issue) || is.null(data$PageStart) || is.null(data$PageEnd) || is.null(data$Citations) || is.null(data$AlternativeId) || is.null(data$DocumentType)) stop("incorrect format of 'data'."); data$Authors <- as.character(data$Authors); if (class(data$PageStart)!="numeric") stop("column 'PageStart' in 'data' should be 'numeric'."); if (class(data$PageEnd)!="numeric") stop("column 'PageEnd' in 'data' should be 'numeric'."); if (class(data$Citations)!="numeric") stop("column 'Citations' in 'data' should be 'numeric'."); if (!is.null(excludeRows) && !is.numeric(excludeRows)) stop("'excludeRows' must be numeric or NULL."); if (is.null(originalFilename) || is.na(originalFilename) || length(originalFilename) != 1) originalFilename <- "Unknown filename"; if (is.null(surveyDescription) || is.na(surveyDescription) || length(surveyDescription) != 1) surveyDescription <- "Default survey"; ## ------------------------------------------------------------------- if (verbose) cat("Importing documents and their authors... "); n <- as.integer(nrow(data)); if (!is.null(excludeRows)) data <- data[-excludeRows,]; ## CREATE A NEW SURVEY idSurvey <- .lbsImportDocuments_GetSurvey(conn, surveyDescription, originalFilename, verbose); stopifnot(length(idSurvey) == 1 && is.finite(idSurvey)); ## PREPARE BibEntry data$BibEntry <- sqlEscape(paste( sqlTrim(data$SourceTitle), sqlTrim(data$Year), sqlTrim(data$Volume), sqlTrim(data$Issue), sqlTrim(data$ArticleNumber), data$PageStart, data$PageEnd, sep=",")); ## PREPARE other fields data$SourceTitle <- sqlEscapeTrim(data$SourceTitle); data$AlternativeId <- sqlEscapeTrim(data$AlternativeId); data$Title <- sqlEscapeTrim(data$Title); data$Year <- sqlNumericOrNULL(data$Year); data$Pages <- sqlNumericOrNULL(data$PageEnd-data$PageStart+1); data$Citations <- ifelse(is.finite(data$Citations), data$Citations, 0); data$DocumentType <- sqlSwitchOrNULL(data$DocumentType, .lbs_DocumentTypesFull, .lbs_DocumentTypesShort ); ## PREPARE authors authors <- strsplit(toupper(data$Authors), "[[:space:]]*,[[:space:]]*"); #hashAuthors <- hash(); hashAuthors <- new.env() stopifnot(length(authors) == n); for (i in 1:n) { m <- length(authors[[i]]); stopifnot(m>0); stopifnot(all(nchar(authors[[i]]))>0); if (surnameFirstnameCommaSeparated) { if (m>1) # "[No author name available]" { if (m%%2 == 1) { stop(sprintf("Error while extracting author names @ row=%g.", i)); } idx <- (1:(m/2)-1)*2+1; authors[[i]] <- paste(authors[[i]][idx], authors[[i]][-idx], sep=" "); hashAuthors[[ authors[[i]] ]] <- NA; } } else hashAuthors[[ authors[[i]] ]] <- NA; } ## IMPORT authors hashAuthorNames <- names(as.list(hashAuthors)); p <- length(hashAuthorNames); if (verbose) { cat(sprintf("Importing %g authors... ", p)); } k <- 0L; dbExecQuery(conn, "PRAGMA journal_mode = MEMORY"); dbBegin(conn); for (i in seq_along(hashAuthorNames)) { # Get idAuthor (and add him/her if necessary) idAuthor <- dbGetQuery(conn, sprintf("SELECT IdAuthor FROM Biblio_Authors WHERE Name=%s", sqlStringOrNULL(hashAuthorNames[i]) )); if (nrow(idAuthor) == 0) { dbExecQuery(conn, sprintf("INSERT INTO Biblio_Authors(Name) VALUES(%s);", sqlStringOrNULL(hashAuthorNames[i])), TRUE); idAuthor <- dbGetQuery(conn, "SELECT last_insert_rowid()")[1,1]; k <- k+1; } else { idAuthor <- idAuthor[1,1]; } hashAuthors[[ hashAuthorNames[i] ]] <- idAuthor; } dbCommit(conn); if (verbose) cat(sprintf("%g new authors added.\n", k)); ## ------------------------------------------------------------------- k <- 0L; dbExecQuery(conn, "PRAGMA journal_mode = MEMORY"); dbBegin(conn); for (i in 1:n) { if (.lbsImportDocuments_Add(conn, data[i,], unlist(as.list(hashAuthors))[authors[[i]]], idSurvey, i, surnameFirstnameCommaSeparated, updateDocumentIfExists, warnExactDuplicates, warnSourceTitle, verbose)) { k <- k+1L; } } dbCommit(conn); if (verbose) cat(sprintf("Done, %g of %g new records added to %s/%s.\n", k, n, surveyDescription, originalFilename)); ## ------------------------------------------------------------------- return(TRUE); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.import.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Retrieves basic information on given authors. #' #' @title Retrieve author information #' @param conn a connection object as produced by \code{\link{lbsConnect}}. #' @param idAuthors a numeric or integer vector with author identifiers (see column \code{IdAuthor} in the table \code{Biblio_Authors}). #' @return #' A list of \code{authorinfo} objects, that is lists with the following components: #' \itemize{ #' \item \code{IdAuthor} --- numeric; author's identifier in the table \code{Biblio_Authors}, #' \item \code{Name} --- character; author's name. #' \item \code{AuthorGroup} --- character; author group (used to merge author records). #' } #' @examples #' \dontrun{ #' conn <- dbBiblioConnect("Bibliometrics.db"); #' ## ... #' id <- lbsSearchAuthors(conn, c("Smith\%", "Knuth D.E.", "V_n \%")); #' lbsGetInfoAuthors(conn, id); #' ## ...} #' @export #' @seealso \code{\link{lbsSearchAuthors}}, \code{\link{lbsSearchDocuments}}, #' \code{\link{lbsGetInfoDocuments}},\cr #' \code{\link{as.character.authorinfo}}, \code{\link{print.authorinfo}}, lbsGetInfoAuthors <- function(conn, idAuthors) { .lbsCheckConnection(conn); # will stop on invalid/dead connection if (is.null(idAuthors) || (class(idAuthors) != "numeric" && class(idAuthors) != "integer")) stop("'idAuthors' must be a nonempty numeric vector."); query <- sprintf("SELECT IdAuthor, Name, AuthorGroup FROM Biblio_Authors WHERE IdAuthor IN (%s)", paste(idAuthors, collapse=",")); res <- dbGetQuery(conn, query); n <- nrow(res); out <- list(); length(out) <- n; if (n < 1) return(NULL); for (i in 1:n) { out[[i]] <- list(IdAuthor=res[i,1], Name=res[i,2], AuthorGroup=res[i,3]); class(out[[i]]) <- "authorinfo"; } return(out); } #' Retrieves information on given documents. #' #' @title Retrieve document information #' @param conn a connection object as produced by \code{\link{lbsConnect}}. #' @param idDocuments a numeric or integer vector with document identifiers (see column \code{IdDocument} in the table \code{Biblio_Documents}). #' @return #' A list of \code{docinfo} objects, that is lists with the following components: #' \itemize{ #' \item \code{IdDocument} --- numeric; document identifier in the table \code{Biblio_Documents}, #' \item \code{Authors} --- list of \code{authorinfo} objects (see e.g. \code{\link{as.character.authorinfo}}). #' \item \code{Title} --- title of the document, #' \item \code{BibEntry} --- bibliographic entry, #' \item \code{AlternativeId} --- unique character identifier, #' \item \code{Pages} --- number of pages, #' \item \code{Citations} --- number of citations, #' \item \code{Year} --- publication year, #' \item \code{Type} --- document type, e.g. \code{Article} or \code{Conference Paper}. #' } #' @examples #' \dontrun{ #' conn <- dbBiblioConnect("Bibliometrics.db"); #' ## ... #' id <- lbsSearchDocuments(conn, #' idAuthors=lbsSearchAuthors(conn, "Knuth\%")); #' lbsGetInfoDocuments(conn, id); #' ## ...} #' @export #' @seealso \code{\link{print.docinfo}}, \code{\link{lbsSearchDocuments}}, #' \code{\link{lbsGetInfoAuthors}},\cr #' \code{\link{as.character.authorinfo}}, \code{\link{as.character.docinfo}} lbsGetInfoDocuments <- function(conn, idDocuments) { .lbsCheckConnection(conn); # will stop on invalid/dead connection if (is.null(idDocuments) || (class(idDocuments) != "numeric" && class(idDocuments) != "integer")) stop("'idDocuments' must be a nonempty numeric vector."); idDocuments_str <- paste(idDocuments, collapse=","); query <- sprintf("SELECT IdDocument, Title, BibEntry, AlternativeId, Pages, Citations, Year, Type FROM Biblio_Documents WHERE IdDocument IN (%s) ORDER BY IdDocument", idDocuments_str); res <- dbGetQuery(conn, query); n <- nrow(res); out <- list(); length(out) <- n; if (n < 1) return(NULL); query2 <- sprintf("SELECT DISTINCT IdDocument, Biblio_Authors.IdAuthor, Biblio_Authors.Name, Biblio_Authors.AuthorGroup FROM Biblio_AuthorsDocuments JOIN Biblio_Authors ON Biblio_Authors.IdAuthor=Biblio_AuthorsDocuments.IdAuthor WHERE IdDocument IN (%s) ORDER BY IdDocument", idDocuments_str); res2 <- dbGetQuery(conn, query2); stopifnot(nrow(res2) >= 1); i <- 1; k <- 1; m <- nrow(res2); while (i <= m) { stopifnot(res2$IdDocument[i] == res$IdDocument[k]); j <- i+1; while (j<=m && res2$IdDocument[i] == res2$IdDocument[j]) j <- j+1; authors <- list(); length(authors) <- j-i; for (u in i:(j-1)) { authors[[u-i+1]] <- list(IdAuthor=res2[u,2], Name=res2[u,3], AuthorGroup=res2[u,4]); class(authors[[u-i+1]]) <- "authorinfo"; } doc <- list(IdDocument=res[k,1], Authors=authors, Title=res[k,2], BibEntry=res[k,3], AlternativeId=res[k,4], Pages=res[k,5], Citations=res[k,6], Year=res[k,7], Type=.lbs_DocumentType_ShortToFull(res[k,8])); class(doc) <- "docinfo"; out[[k]] <- doc; i <- j; k <- k+1; } stopifnot(k-1 == n); return(out); } #' Converts an object of class \code{docinfo} to a character string. #' Such an object is returned by e.g. \code{\link{lbsGetInfoDocuments}}. #' #' A \code{docinfo} object is a list with the following components: #' \itemize{ #' \item \code{IdDocument} --- numeric; document identifier in the table \code{Biblio_Documents}, #' \item \code{Authors} --- list of \code{authorinfo} objects (see e.g. \code{\link{as.character.authorinfo}}). #' \item \code{Title} --- title of the document, #' \item \code{BibEntry} --- bibliographic entry, #' \item \code{AlternativeId} --- unique character identifier, #' \item \code{Pages} --- number of pages, #' \item \code{Citations} --- number of citations, #' \item \code{Year} --- publication year, #' \item \code{Type} --- type of document, see \code{\link{lbsCreate}}. #' } #' #' @title Coerce a docinfo object to character string #' @param x a single object of class \code{docinfo}. #' @param ... unused. #' @return A character string #' @export #' @method as.character docinfo #' @seealso \code{\link{lbsSearchDocuments}}, #' \code{\link{as.character.authorinfo}}, \code{\link{print.docinfo}},\cr #' \code{\link{lbsGetInfoDocuments}} as.character.docinfo <- function(x, ...) { ret <- sprintf("IdDocument: %g", x$IdDocument); ret <- paste(ret, sprintf("AlternativeId: %s", x$AlternativeId), sep="\n"); ret <- paste(ret, sprintf("Title: %s", x$Title), sep="\n"); ret <- paste(ret, sprintf("BibEntry: %s", x$BibEntry), sep="\n"); ret <- paste(ret, sprintf("Year: %s", x$Year), sep="\n"); ret <- paste(ret, sprintf("Type: %s", x$Type), sep="\n"); ret <- paste(ret, sprintf("Citations: %s", x$Citations), sep="\n"); ret <- paste(ret, sprintf("Authors: %s\n", paste( sapply(x$Authors, function(y) paste(y$Name, y$IdAuthor, y$AuthorGroup, sep="/")), collapse=", ") ), sep="\n"); return(ret); } #' Prints out an object of class \code{docinfo}. Such an object is returned by e.g. \code{\link{lbsGetInfoDocuments}}. #' #' For more information see man page for \code{\link{as.character.docinfo}}. #' #' @title Print a docinfo object #' @param x an object of class \code{docinfo}. #' @param ... unused. #' @export #' @method print docinfo #' @seealso \code{\link{as.character.docinfo}}, \code{\link{lbsSearchDocuments}}, \code{\link{lbsGetInfoDocuments}} print.docinfo <- function(x, ...) { cat(as.character(x)); } #' Converts an object of class \code{authorinfo} to a character string. #' Such an object is returned by e.g. \code{\link{lbsGetInfoAuthors}}. #' #' An \code{authorinfo} object is a list with the following components: #' \itemize{ #' \item \code{IdAuthor} --- numeric; author's identifier in the table \code{Biblio_Authors}, #' \item \code{Name} --- character; author's name. #' } #' #' @title Coerce an authorinfo object to character string #' @param x a single object of class \code{authorinfo}. #' @param ... unused. #' @return A character string #' @export #' @method as.character authorinfo #' @seealso \code{\link{print.authorinfo}}, \code{\link{lbsSearchAuthors}}, \code{\link{lbsGetInfoAuthors}} as.character.authorinfo <- function(x, ...) { ret <- sprintf("IdAuthor: %g", x$IdAuthor); ret <- paste(ret, sprintf("Name: %s", x$Name), sep="\n"); ret <- paste(ret, sprintf("AuthorGroup: %s\n", x$AuthorGroup), sep="\n"); return(ret); } #' Prints out an object of class \code{authorinfo}. Such an object is returned by e.g. \code{\link{lbsGetInfoAuthors}}. #' #' For more information see man page for \code{\link{as.character.authorinfo}}. #' #' @title Print an authorinfo object #' @param x an object of class \code{authorinfo}. #' @param ... unused. #' @method print authorinfo #' @export #' @seealso \code{\link{as.character.authorinfo}}, \code{\link{lbsSearchAuthors}}, \code{\link{lbsGetInfoAuthors}} print.authorinfo <- function(x, ...) { cat(as.character(x)); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.info.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. # /internal/ # stops if connection is invalid or dead .lbsCheckConnection <- function(conn) { if (!class(conn) == "SQLiteConnection") stop("incorrect 'conn' given"); dbGetInfo(conn); # check if conn is active } # /internal/ .lbs_SourceTypesFull <- c("Book Series", "Conference Proceedings", "Journal"); # /internal/ .lbs_SourceTypesShort <- c("'bs'", "'cp'", "'jo'"); # /internal/ .lbs_DocumentTypesFull <- c("Article", "Article in Press", "Book", "Conference Paper", "Editorial", "Erratum", "Letter", "Note", "Report", "Review", "Short Survey"); # /internal/ .lbs_DocumentTypesShort <- c("'ar'", "'ip'", "'bk'", "'cp'", "'ed'", "'er'", "'le'", "'no'", "'rp'", "'re'", "'sh'"); # /internal/ .lbs_DocumentType_ShortToFull <- function(type) { was.factor <- is.factor(type); type <- as.factor(type); lev <- sprintf("'%s'", levels(type)); for (i in 1:length(.lbs_DocumentTypesFull)) { lev[lev==(.lbs_DocumentTypesShort[i])] <- .lbs_DocumentTypesFull[i]; } levels(type) <- lev; if (!was.factor) type <- as.character(type); return(type); } # /internal/ .lbs_PrepareRestriction_DocumentTypes <- function(conn, documentTypes) { if (is.null(documentTypes)) return(NULL); if (!is.character(documentTypes)) stop("incorrect 'documentTypes' given"); documentTypesShort <- character(length(documentTypes)); for (i in 1:length(documentTypes)) documentTypesShort[i] <- sqlSwitchOrNULL(documentTypes[i], .lbs_DocumentTypesFull, .lbs_DocumentTypesShort ); incorrect <- which(documentTypesShort == "NULL"); if (length(incorrect)>0) { warning(sprintf("incorrect document types: %s. Ignoring.", paste(documentTypes[incorrect], collapse=", "))); documentTypesShort <- documentTypesShort[-incorrect]; } if (length(documentTypesShort) == 0) stop("all given document types were incorrect."); return(documentTypesShort); } # /internal/ .lbs_PrepareRestriction_SurveyDescription <- function(conn, surveyDescription) { if (is.null(surveyDescription)) return(NULL); if (!is.character(surveyDescription) || length(surveyDescription)!=1) stop("incorrect 'surveyDescription' given"); surveyDescription <- sqlEscapeTrim(surveyDescription); res <- dbGetQuery(conn, sprintf("SELECT * FROM Biblio_Surveys WHERE Description='%s';", surveyDescription)); if (nrow(res) == 0) stop("Survey not found."); return(surveyDescription); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.internal.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Finds authors by name. #' #' \code{names.like} is a set of search patterns in an SQL \code{LIKE} format, #' i.e. an underscore \code{_} matches a single character and a percent sign #' \code{\%} matches any set of characters. The search is case-insensitive. #' #' @title Find authors that satisfy given criteria #' @param conn connection object, see \code{\link{lbsConnect}}. #' @param names.like character vector of SQL-LIKE patterns to match authors' names. #' @param group character vector of author group identifiers. #' @return #' Integer vector of authors' identifiers which match at least one of given #' SQL-LIKE patterns. #' @examples #' \dontrun{ #' conn <- dbBiblioConnect("Bibliometrics.db"); #' ## ... #' id <- lbsSearchAuthors(conn, c("Smith\%", "Knuth D.E.", "V_n \%")); #' lbsGetInfoAuthors(conn, id); #' ## ...} #' @export #' @seealso \code{\link{lbsGetInfoAuthors}}, #' \code{\link{lbsSearchDocuments}}, #' \code{\link{lbsGetInfoDocuments}} lbsSearchAuthors <- function(conn, names.like=NULL, group=NULL) { .lbsCheckConnection(conn); # will stop on invalid/dead connection if (!is.null(names.like) && class(names.like) != "character") stop("'names.like' must be a character vector."); if (!is.null(group) && class(group) != "character") stop("'group' must be a character vector."); query <- "SELECT IdAuthor FROM Biblio_Authors WHERE 1"; if (!is.null(names.like)) { query <- paste(query, " AND (0"); for (i in 1:length(names.like)) query <- paste(query, sprintf("(Name LIKE '%s')", sqlEscapeTrim(names.like[i])), sep=" OR "); query <- paste(query, ")"); } if (!is.null(group)) { query <- paste(query, " AND (0"); for (i in 1:length(group)) query <- paste(query, sprintf("(AuthorGroup='%s')", sqlEscapeTrim(group[i])), sep=" OR "); query <- paste(query, ")"); } return(dbGetQuery(conn, query)[,1]); } #' Searches for documents meeting given criteria (e.g. document titles, #' documents' authors identifiers, number of citations, number of pages, publication years #' or document types). #' #' \code{titles.like} is a set of search patterns in an SQL \code{LIKE} format, #' i.e. an underscore \code{_} matches a single character and a percent sign #' \code{\%} matches any set of characters. The search is case-insensitive. #' #' The expressions passed as #' parameters \code{citations.expr}, \code{pages.expr}, \code{year.expr} #' must be acceptable by SQL WHERE clause in the form #' \code{WHERE field <expression>}, see Examples below. #' #' @title Find documents that satisfy given criteria #' @param conn connection object, see \code{\link{lbsConnect}}. #' @param titles.like character vector of SQL-LIKE patterns to match documents' titles or \code{NULL}. #' @param idAuthors numeric or integer vector with author identifiers (see column \code{IdAuthor} in the table \code{Biblio_Authors}) or \code{NULL}. #' @param citations.expr expression determining the desired number of citations or \code{NULL}, see Examples below. #' @param pages.expr expression determining the desired number of pages or \code{NULL}, see Examples below. #' @param year.expr expression determining the desired publication year or \code{NULL}, see Examples below. #' @param documentTypes character vector or \code{NULL}; specifies document types to restrict to; #' a combination of \code{Article}, \code{Article in Press}, \code{Book}, \code{Conference Paper}, #' \code{Editorial}, \code{Erratum}, \code{Letter}, \code{Note}, \code{Report}, \code{Review}, #' \code{Short Survey}. \code{NULL} means no such restriction. #' @param surveyDescription single character string or \code{NULL}; survey description to restrict to or \code{NULL}. #' @param alternativeId character vector of documents' AlternativeIds. #' @export #' @return #' Integer vector of documents' identifiers matching given criteria. #' @examples #' \dontrun{ #' conn <- dbBiblioConnect("Bibliometrics.db"); #' ## ... #' idd <- lbsSearchDocuments(conn, pages.expr=">= 400", #' year.expr="BETWEEN 1970 AND 1972"); #' lbsGetInfoDocuments(conn, idd); #' ## ...} #' @seealso \code{\link{lbsGetInfoAuthors}}, #' \code{\link{lbsSearchAuthors}}, #' \code{\link{lbsGetInfoDocuments}} lbsSearchDocuments <- function(conn, titles.like=NULL, idAuthors=NULL, citations.expr=NULL, pages.expr=NULL, year.expr=NULL, documentTypes=NULL, alternativeId=NULL, surveyDescription=NULL ) { .lbsCheckConnection(conn); # will stop on invalid/dead connection surveyDescription <- .lbs_PrepareRestriction_SurveyDescription(conn, surveyDescription); documentTypesShort <- .lbs_PrepareRestriction_DocumentTypes(conn, documentTypes); if (!is.null(titles.like) && class(titles.like) != "character") stop("'titles.like' must be a character vector."); if (!is.null(idAuthors) && class(idAuthors) != "numeric" && class(idAuthors) != "integer") stop("'idAuthors' must be a numeric vector."); if (!is.null(citations.expr) && (class(citations.expr) != "character" || length(citations.expr)!=1)) stop("'citations.expr' must be a character string."); if (!is.null(pages.expr) && (class(pages.expr) != "character" || length(pages.expr)!=1)) stop("'pages.expr' must be a character string."); if (!is.null(year.expr) && (class(year.expr) != "character" || length(year.expr)!=1)) stop("'year.expr' must be a character string."); if (!is.null(alternativeId) && class(alternativeId) != "character") stop("'alternativeId' must be a character vector."); if (is.null(titles.like) && is.null(documentTypes) && is.null(idAuthors) && is.null(citations.expr) && is.null(pages.expr) && is.null(year.expr) && is.null(alternativeId)) stop("at least one of: 'titles.like', 'documentTypes', 'idAuthors', 'citations.expr', 'pages.expr', 'year.expr', 'alternativeId' must not be NULL"); # Get subQueryWhere if (length(documentTypesShort)>0) { subquery0 <- sprintf("(%s)", paste("Type", documentTypesShort, sep="=", collapse=" OR ")); } else subquery0 <- "1"; if (!is.null(surveyDescription)) subquery0 <- paste(c(subquery0, sprintf(" Description='%s'", surveyDescription)), collapse=" AND "); if (is.null(titles.like)) { subquery1 <- "1"; } else { subquery1 <- "0"; for (i in 1:length(titles.like)) subquery1 <- paste(subquery1, sprintf("(Title LIKE '%s')", sqlEscapeTrim(titles.like[i])), sep=" OR "); } if (is.null(idAuthors)) { subquery2 <- "1"; } else { subquery2 <- "0"; for (i in 1:length(idAuthors)) subquery2 <- paste(subquery2, sprintf("(IdAuthor=%g)", idAuthors[i]), sep=" OR "); } if (is.null(citations.expr)) { subquery3 <- "1"; } else { # might be dangerous, but the user surely knows what is she doing :-) subquery3 <- sprintf("Citations %s", sqlTrim(citations.expr)); } if (is.null(year.expr)) { subquery4 <- "1"; } else { # might be dangerous, but the user surely knows what is she doing :-) subquery4 <- sprintf("Year %s", sqlTrim(year.expr)); } if (is.null(pages.expr)) { subquery5 <- "1"; } else { # might be dangerous, but the user surely knows what is she doing :-) subquery5 <- sprintf("Pages %s", sqlTrim(pages.expr)); } if (is.null(alternativeId)) { subquery6 <- "1"; } else { subquery6 <- "0"; for (i in 1:length(alternativeId)) subquery6 <- paste(subquery6, sprintf("(AlternativeId='%s')", sqlEscapeTrim(alternativeId[i])), sep=" OR "); } query <- sprintf("SELECT DISTINCT Biblio_Documents.IdDocument FROM Biblio_Documents JOIN Biblio_AuthorsDocuments ON Biblio_Documents.IdDocument=Biblio_AuthorsDocuments.IdDocument JOIN ViewBiblio_DocumentsSurveys ON Biblio_Documents.IdDocument=ViewBiblio_DocumentsSurveys.IdDocument WHERE (%s) AND (%s) AND (%s) AND (%s) AND (%s) AND (%s) AND (%s)", subquery0, subquery1, subquery2, subquery3, subquery4, subquery5, subquery6); return(dbGetQuery(conn, query)[,1]); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.search.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Performs preliminary analysis of data in a Local Bibliometric Storage #' by creating some basic descriptive statistics (numeric and graphical). #' Dataset may be restricted to any given document types #' or a single survey. #' #' Plot types (accessed with \code{which}): #' \itemize{ #' \item \code{1} --- "Document types", #' \item \code{2} --- "Publication years", #' \item \code{3} --- "Citations per document", #' \item \code{4} --- "Citations of cited documents per type", #' \item \code{5} --- "Number of pages per document type", #' \item \code{6} --- "Categories of documents" (based od source categories), #' \item \code{7} --- "Documents per author". #' } #' #' Note that this user interaction scheme is similar in behavior #' to the \code{\link{plot.lm}} function. #' #' @title Perform preliminary analysis of data in a Local Bibliometric Storage #' @param conn connection object, see \code{\link{lbsConnect}}. #' @param documentTypes character vector or \code{NULL}; specifies document types to restrict to; #' a combination of \code{Article}, \code{Article in Press}, \code{Book}, \code{Conference Paper}, #' \code{Editorial}, \code{Erratum}, \code{Letter}, \code{Note}, \code{Report}, \code{Review}, #' \code{Short Survey}. \code{NULL} means no restriction. #' @param surveyDescription single character string or \code{NULL}; survey to restrict to, or \code{NULL} for no restriction. #' @param which numeric vector with elements in 1,...,7, or \code{NULL}; plot types to be displayed. #' @param main title for each plot. #' @param ask logical; if \code{TRUE}, the user is asked to press return before each plot. #' @param ... additional graphical parameters, see \code{\link{plot.default}}. #' @param cex.caption controls size of default captions. #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' lbsDescriptiveStats(conn, surveyDescription="Scientometrics", #' documentTypes=c("Article", "Note", "Report", "Review", "Short Survey")); #' ## ... #' lbsDisconnect(conn);} #' #' @export #' #' @seealso #' \code{\link{plot.default}}, #' \code{\link{lbsConnect}} lbsDescriptiveStats <- function(conn, documentTypes=NULL, surveyDescription=NULL, which=(1L:7L), main="", ask = (prod(par("mfcol")) < length(which) && dev.interactive()), ..., cex.caption=1 ) { .lbsCheckConnection(conn); # will stop on invalid/dead connection ## ---------------------- AUXILIARY FUNCTION ------------------------------- #' /internal/ .lbsDescriptiveStats_PrintStatsSubset <- function(conn, subQueryWhere) { query <- sprintf(" SELECT COUNT(idDocument) FROM ( SELECT DISTINCT Biblio_Documents.IdDocument FROM Biblio_Documents JOIN ViewBiblio_DocumentsSurveys ON ViewBiblio_DocumentsSurveys.IdDocument=Biblio_Documents.IdDocument WHERE %s );", subQueryWhere); res <- dbGetQuery(conn, query); cat(sprintf("Number of documents in the selected subset: %g.\n", res[1,1])); query <- sprintf(" SELECT COUNT(IdAuthor) FROM ( SELECT DISTINCT Biblio_AuthorsDocuments.IdAuthor FROM Biblio_AuthorsDocuments JOIN ( SELECT Biblio_Documents.IdDocument FROM Biblio_Documents JOIN ViewBiblio_DocumentsSurveys ON ViewBiblio_DocumentsSurveys.IdDocument=Biblio_Documents.IdDocument WHERE %s ) AS Docs ON Docs.IdDocument=Biblio_AuthorsDocuments.IdDocument );", subQueryWhere); res <- dbGetQuery(conn, query); cat(sprintf("Number of authors in the selected subset: %g.\n", res[1,1])); cat("\n"); } ## ---------------------- AUXILIARY FUNCTION ------------------------------- #' /internal/ .lbsDescriptiveStats_PrintSurveyStats <- function(conn, subQueryWhere, split2filenames) { if (!split2filenames) { query <- sprintf(" SELECT Description AS surveyDescription, COUNT(IdDocument) AS DocumentCount FROM ( SELECT DISTINCT Description, ViewBiblio_DocumentsSurveys.IdDocument FROM ViewBiblio_DocumentsSurveys JOIN Biblio_Documents ON ViewBiblio_DocumentsSurveys.IdDocument=Biblio_Documents.IdDocument WHERE %s ) GROUP BY Description;", subQueryWhere ); res <- dbGetQuery(conn, query); cat("Surveys:\n"); print(res); } else { query <- sprintf(" SELECT Filename, Timestamp, COUNT(IdDocument) AS DocumentCount FROM ( SELECT DISTINCT Filename, Timestamp, ViewBiblio_DocumentsSurveys.IdDocument FROM ViewBiblio_DocumentsSurveys JOIN Biblio_Documents ON ViewBiblio_DocumentsSurveys.IdDocument=Biblio_Documents.IdDocument WHERE %s ) GROUP BY Filename;", subQueryWhere ); res <- dbGetQuery(conn, query); cat("Source files in selected survey:\n"); print(res); } cat(" * Note that a document may belong to many surveys/files.\n"); cat("\n"); } ## ----------------------------------------------------- ## Basic stats res <- dbGetQuery(conn, "SELECT COUNT(idSource) FROM Biblio_Sources;"); cat(sprintf("Number of sources in your LBS: %g\n", res[1,1])); res <- dbGetQuery(conn, "SELECT COUNT(idDocument) FROM Biblio_Documents;"); cat(sprintf("Number of documents in your LBS: %g\n", res[1,1])); res <- dbGetQuery(conn, "SELECT COUNT(idAuthor) FROM Biblio_Authors;"); cat(sprintf("Number of author records in your LBS: %g\n", res[1,1])); res <- dbGetQuery(conn, "SELECT COUNT(*) FROM (SELECT AuthorGroup FROM Biblio_Authors GROUP BY AuthorGroup);"); cat(sprintf("Number of author groups in your LBS: %g\n", res[1,1])); res <- dbGetQuery(conn, "SELECT COUNT(*) FROM (SELECT IdAuthor FROM Biblio_Authors WHERE AuthorGroup IS NULL);"); cat(sprintf("Number of ungrouped authors in your LBS: %g\n", res[1,1])); cat("\n"); ## ----------------------------------------------------- ## Data set restrictions & subset stats surveyDescription <- .lbs_PrepareRestriction_SurveyDescription(conn, surveyDescription); documentTypesShort <- .lbs_PrepareRestriction_DocumentTypes(conn, documentTypes); # Get subQueryWhere if (length(documentTypesShort)>0) { subQueryWhere <- sprintf("(%s)", paste("Type", documentTypesShort, sep="=", collapse=" OR ")); } else subQueryWhere <- "1"; if (!is.null(surveyDescription)) subQueryWhere <- paste(c(subQueryWhere, sprintf(" Description='%s'", surveyDescription)), collapse=" AND "); cat("You have chosen the following data restrictions:\n"); cat(sprintf("\tSurvey: %s.\n", ifelse(is.null(surveyDescription), "<ALL>", surveyDescription))); cat(sprintf("\tDocument types: %s.\n", ifelse(is.null(documentTypesShort), "<ALL>", paste(documentTypesShort, collapse=", ")))); cat("\n"); if (length(documentTypesShort)>0 || !is.null(surveyDescription)) .lbsDescriptiveStats_PrintStatsSubset(conn, subQueryWhere); ## ----------------------------------------------------- ## Survey(s) stats .lbsDescriptiveStats_PrintSurveyStats(conn, subQueryWhere, !is.null(surveyDescription)); which <- as.integer(which); which <- which[which >=1 & which <= 7]; if (length(which) < 1) return(); ## ----------------------------------------------------- ## UI # This user interaction scheme is based on the code of plot.lm() function show <- rep(FALSE, 7) show[which] <- TRUE if (ask) { oask <- devAskNewPage(TRUE); on.exit(devAskNewPage(oask)); } captions <- c("Document types", "Publication years", "Citations per document", "Citations of cited documents per type", "Number of pages per document type", "Categories of documents", "Documents per author"); ## ----------------------------------------------------- ## 1:5 if (any(show[1L:5L])) { res <- dbGetQuery(conn, sprintf(" SELECT DISTINCT Biblio_Documents.IdDocument, Citations, Type, Year, Pages FROM Biblio_Documents JOIN ViewBiblio_DocumentsSurveys ON Biblio_Documents.IdDocument=ViewBiblio_DocumentsSurveys.IdDocument WHERE %s", subQueryWhere)); } else res <- NULL; if (show[1L]) { tab <- sort(table(res$Type), decreasing=TRUE); barplot(tab, main=main, ...); mtext(as.graphicsAnnot(captions[1]), 3, 0.25, cex=cex.caption); cat(sprintf("%s:\n", captions[1])); print(tab); cat("\n\n"); } if (show[2L]) { tab <- table(res$Year); barplot(tab, main=main, ...); mtext(as.graphicsAnnot(captions[2]), 3, 0.25, cex=cex.caption); cat(sprintf("%s:\n", captions[2])); print(tab); cat("\n\n"); } if (show[3L]) { tab <- table(res$Citations); barplot(tab, main=main, ...); mtext(as.graphicsAnnot(captions[3]), 3, 0.25, cex=cex.caption); cat(sprintf("%s:\n", captions[3])); print(tab); cat("\n\n"); } if (show[4L]) { boxplot(res$Citations[res$Citations>0]~res$Type[res$Citations>0], log="y", main=main, ...); mtext(as.graphicsAnnot(captions[4]), 3, 0.25, cex=cex.caption); } if (show[5L]) { boxplot(res$Pages[res$Pages>0 & res$Pages<500]~res$Type[res$Pages>0 & res$Pages<500], log="y", main=main, ...); mtext(as.graphicsAnnot(captions[5]), 3, 0.25, cex=cex.caption); } # ----------------------------------------------------- # 6 if (any(show[6L:6L])) { query <- sprintf( "SELECT DISTINCT DocInfo.IdDocument, IdCategoryParent, DescriptionParent FROM ViewBiblio_DocumentsCategories JOIN ( SELECT DISTINCT Biblio_Documents.IdDocument FROM Biblio_Documents JOIN ViewBiblio_DocumentsSurveys ON Biblio_Documents.IdDocument=ViewBiblio_DocumentsSurveys.IdDocument WHERE %s ) AS DocInfo ON DocInfo.IdDocument=ViewBiblio_DocumentsCategories.IdDocument;", subQueryWhere ); res <- dbGetQuery(conn, query) } else res <- NULL; if (show[6L]) { mergepercent <- 0.017; tab <- table(as.factor(res$DescriptionParent)); tab2 <- tab[tab>mergepercent*sum(tab)]; tab2 <- c(tab2, "Other"=sum(tab[tab<=mergepercent*sum(tab)])); otab <- order(tab2); for (i in 1:(length(otab)/2)) { if (i %% 2 == 0) { r <- otab[length(otab)-i/2]; otab[length(otab)-i/2] <- otab[i]; otab[i] <- r; } } tab <- tab2[otab]; pie(tab, main=main, ...); mtext(as.graphicsAnnot(captions[6]), 3, 0.25, cex=cex.caption); cat(sprintf("%s:\n", captions[6])); print(tab); cat("\n\n"); } # ----------------------------------------------------- # 7 if (any(show[7L:7L])) { query <- sprintf( "SELECT IdAuthor, COUNT(IdDocument) AS Number FROM ( SELECT DISTINCT Biblio_AuthorsDocuments.IdAuthor, Biblio_AuthorsDocuments.IdDocument FROM Biblio_AuthorsDocuments JOIN Biblio_Documents ON Biblio_Documents.IdDocument=Biblio_AuthorsDocuments.IdDocument JOIN ViewBiblio_DocumentsSurveys ON ViewBiblio_DocumentsSurveys.IdDocument=Biblio_Documents.IdDocument WHERE %s ) GROUP BY (IdAuthor)", subQueryWhere ); res <- dbGetQuery(conn, query) } else res <- NULL; if (show[7L]) { tab <- table(res$Number); barplot(tab, main=main, ...); mtext(as.graphicsAnnot(captions[7]), 3, 0.25, cex=cex.caption); cat(sprintf("%s:\n", captions[7])); print(tab); cat("\n\n"); } }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.stats.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Cleans up a Local Bibliometric Storage #' by removing all authors with no documents, fixing documents #' with missing survey information, and executing the \code{VACUUM} #' SQL command. #' #' @title Clean up a Local Bibliometric Storage #' @param conn database connection object, see \code{\link{lbsConnect}}. #' @param newSuveyDescription character; default survey description for documents with missing survey info. #' @param newSuveyFilename character; default survey filename for documents with missing survey info. #' @export #' @return \code{TRUE} on success. #' @seealso \code{\link{lbsConnect}}, \code{\link{lbsCreate}}, #' \code{\link{Scopus_ImportSources}}, #' \code{\link{lbsDeleteAllAuthorsDocuments}}, #' \code{\link{dbCommit}}, \code{\link{dbRollback}} lbsTidy <- function(conn, newSuveyDescription="lbsTidy_Merged", newSuveyFilename="lbsTidy_Merged") { .lbsCheckConnection(conn); # will stop on invalid/dead connection ## REMOVE ALL AUTHORS WITHOUT DOCUMENTS dbExecQuery(conn, "DELETE FROM Biblio_Authors WHERE IdAuthor IN ( SELECT Biblio_Authors.IdAuthor FROM Biblio_Authors LEFT JOIN Biblio_AuthorsDocuments ON Biblio_Authors.IdAuthor=Biblio_AuthorsDocuments.IdAuthor WHERE IdDocument IS NULL )"); chg <- dbGetQuery(conn, "SELECT changes()")[1,1]; cat(sprintf("Deleted %g authors with no documents.\n", chg)); ## FIX ALL DOCUMENTS WITH NO SURVEY INFO idDocNoSurvey <- dbGetQuery(conn, "SELECT Biblio_Documents.IdDocument FROM Biblio_Documents LEFT JOIN Biblio_DocumentsSurveys ON Biblio_Documents.IdDocument=Biblio_DocumentsSurveys.IdDocument WHERE Biblio_DocumentsSurveys.IdSurvey IS NULL"); n <- nrow(idDocNoSurvey); if (n > 0) { query <- sprintf("INSERT INTO Biblio_Surveys('Description', 'FileName', 'Timestamp') VALUES(%s, %s, %s)", sqlStringOrNULL(newSuveyDescription), sqlStringOrNULL(newSuveyFilename), sqlStringOrNULL(format(Sys.time(), "%Y-%m-%d %H:%M:%S")) ); dbExecQuery(conn, query, TRUE); idSurvey <- (as.numeric(dbGetQuery(conn, "SELECT last_insert_rowid()")[1,1])); # dbBegin(conn); for (i in 1:n) { dbExecQuery(conn, sprintf("INSERT INTO Biblio_DocumentsSurveys('IdDocument', 'IdSurvey') VALUES (%s, %s);", sqlNumericOrNULL(idDocNoSurvey[i,1]), sqlNumericOrNULL(idSurvey) )); } dbCommit(conn); } cat(sprintf("Fixed %g documents with no survey information.\n", n)); ## VACUUM dbExecQuery(conn, "VACUUM", FALSE); return(TRUE); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/biblio.tidy.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Executes an SQL query and immediately frees all allocated resources. #' #' This function may be used to execute queries like \code{CREATE TABLE}, #' \code{UPDATE}, \code{INSERT}, etc. #' #' It has its own exception handler, which prints out detailed information #' on caught errors. #' #' @title Execute a query and free its resources #' @param conn a \code{DBI} connection object. #' @param statement a character string with the SQL statement to be executed. #' @param rollbackOnError logical; if \code{TRUE}, then the function executes rollback on current transaction if an exception occurs. #' @seealso \code{\link{dbSendQuery}}, \code{\link{dbClearResult}}, \code{\link{dbGetQuery}} #' @export #' @importFrom RSQLite dbSendQuery #' @importFrom RSQLite dbGetException #' @importFrom RSQLite dbRollback #' @importFrom RSQLite dbClearResult dbExecQuery <- function(conn, statement, rollbackOnError=FALSE) { if (!is.character(statement) || length(statement)!=1) stop("incorrect 'statement'"); tryCatch(res <- dbSendQuery(conn, statement), error=function(err) { cat("\n\n*** SQL Exception caught ***\n\n"); cat(sprintf("Statement: %s\n", statement)); ex <- dbGetException(conn); if (rollbackOnError) dbRollback(conn); print(ex); stop("stopping on SQL exception."); } ); dbClearResult(res); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/execquery.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' List of Elsevier's \emph{SciVerse Scopus} covered titles (journals, conference proceedings, book series, etc.) #' #' Last update: October 2011. The data file is based on the official and publicly available #' (no permission needed as stated by Elsevier) Scopus list of covered titles. #' #' This data frame consists of 30794 records. #' It has the following columns. #' \tabular{ll}{ #' \code{SourceId} \tab Unique source identifier in \emph{SciVerse Scopus} (integer). \cr #' \code{Title} \tab Title of the source. \cr #' \code{Status} \tab Status of the source, either \code{Active} or \code{Inactive}. \cr #' \code{SJR_2009} \tab SCImago Journal Rank 2009. \cr #' \code{SNIP_2009} \tab Source Normalized Impact per Paper 2009. \cr #' \code{SJR_2010} \tab SCImago Journal Rank 2010. \cr #' \code{SNIP_2010} \tab Source Normalized Impact per Paper 2010. \cr #' \code{SJR_2011} \tab SCImago Journal Rank 2011. \cr #' \code{SNIP_2011} \tab Source Normalized Impact per Paper 2011. \cr #' \code{OpenAccess} \tab Type of Open Access, see below. \cr #' \code{Type} \tab Type of the source, see below. \cr #' \code{ASJC} \tab A list of semicolon-separated ASJC classification codes, see \code{\link{Scopus_ASJC}}. \cr #' } #' #' \code{OpenAccess} is one of \code{DOAJ}, \code{Not OA} (not Open Access source), #' \code{OA but not registered}, \code{OA registered}. #' #' \code{Type} is one of \code{Book Series}, \code{Conference Proceedings}, \code{Journal}, \code{Trade Journal} #' #' The \code{data.frame} is sorted by \code{Status} (\code{Active} sources first) and then by \code{SJR_2011} (higher values first). #' #' @export #' #' @title Scopus covered source list #' @name Scopus_SourceList #' @docType data #' @seealso \code{\link{Scopus_ASJC}}, \code{\link{Scopus_ReadCSV}}, \code{\link{Scopus_ImportSources}} Scopus_SourceList <- NULL # will be loaded later #' List of Elsevier's \emph{SciVerse Scopus} ASJC (All Science. Journals Classification) #' source classification codes. #' #' Last update: October 2011. The data file is based on the official and publicly available #' (no permission needed as stated by Elsevier) Scopus list of covered titles. #' #' It consists of 334 ASJC 4-digit integer codes (column \code{ASJC}) #' together with their group identifiers (column \code{ASJC_Parent}) #' and descriptions (column \code{Description}). #' #' ASJC codes are used to classify Scopus sources (see \code{\link{Scopus_SourceList}}). #' #' @export #' #' @title Scopus ASJC (All Science. Journals Classification) classification codes #' @name Scopus_ASJC #' @docType data #' @seealso \code{\link{Scopus_SourceList}}, \code{\link{Scopus_ReadCSV}}, \code{\link{Scopus_ImportSources}} Scopus_ASJC <- NULL # will be loaded later
/scratch/gouwar.j/cran-all/cranData/CITAN/R/scopus.data.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Imports \emph{SciVerse Scopus} covered titles and their ASJC codes to an empty Local Bibliometric Storage (\acronym{LBS}). #' #' This function should be called prior to importing any document information #' to the LBS with the function \code{\link{lbsImportDocuments}}. #' #' Note that adding all the sources takes some time. #' #' Only elementary ASJC and \emph{SciVerse Scopus} source data #' read from \code{\link{Scopus_ASJC}} and \code{\link{Scopus_SourceList}} #' will be added to the LBS (\code{Biblio_Categories}, \code{Biblio_Sources}, \code{Biblio_SourcesCategories}). #' #' #' @title Import SciVerse Scopus coverage information and ASJC codes to a Local Bibliometric Storage #' @param conn a connection object, see \code{\link{lbsConnect}}. #' @param verbose logical; \code{TRUE} to display progress information. #' @return \code{TRUE} on success. #' @export #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' lbsCreate(conn); #' Scopus_ImportSources(conn); #' ## ... #' lbsDisconnect(conn);} #' @seealso \code{\link{Scopus_ASJC}}, \code{\link{Scopus_SourceList}}, \code{\link{Scopus_ReadCSV}}, \code{\link{lbsConnect}}, \code{\link{lbsCreate}} Scopus_ImportSources <- function(conn, verbose=T) { .lbsCheckConnection(conn); # will stop on invalid/dead connection ## ---- check if 3 tables used here are empty ----------------------------- res <- dbGetQuery(conn, "SELECT COUNT(*) AS Count FROM Biblio_Categories"); if (res[1,1] != 0) stop("table 'Biblio_Categories' is not empty."); res <- dbGetQuery(conn, "SELECT COUNT(*) AS Count FROM Biblio_Sources"); if (res[1,1] != 0) stop("table 'Biblio_Sources' is not empty."); res <- dbGetQuery(conn, "SELECT COUNT(*) AS Count FROM Biblio_SourcesCategories"); if (res[1,1] != 0) stop("table 'Biblio_SourcesCategories' is not empty."); ## ------------------------------------------------------------------------ ## ----- auxiliary functions ---------------------------------------------- # /internal/ # Imports data from Scopus_ASJC to Biblio_Categories .Scopus_ImportSources_Categories <- function(conn, verbose) { if (verbose) cat("Importing Scopus ASJC codes... "); n <- nrow(Scopus_ASJC); ## ----- prepare queries ---------------------------------------------- queries <- sprintf("INSERT INTO Biblio_Categories ('IdCategory', 'IdCategoryParent', 'Description') VALUES (%g, %g, '%s');", as.integer(Scopus_ASJC$ASJC), as.integer(Scopus_ASJC$ASJC_Parent), sqlEscapeTrim(Scopus_ASJC$Description) ); ## -------------------------------------------------------------------- dbBegin(conn); for (i in 1:n) dbExecQuery(conn, queries[i], TRUE); dbCommit(conn); if (verbose) cat(sprintf("Done, %g records added.\n", n)); } ## ----- auxiliary function ---------------------------------------------- # /internal/ .Scopus_ImportSources_Sources <- function(conn, verbose) { n <- nrow(Scopus_SourceList); if (verbose) cat("Importing Scopus source list... "); ## ----- prepare queries ------------------------ queries <- sprintf("INSERT OR FAIL INTO Biblio_Sources( 'IdSource', 'AlternativeId', 'Title', 'IsActive', 'IsOpenAccess', 'Type', 'Impact1', 'Impact2', 'Impact3', 'Impact4', 'Impact5', 'Impact6' ) VALUES (%.0f, '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s);", 1:n, sqlEscapeTrim(as.character(Scopus_SourceList$SourceId)), sqlEscapeTrim(Scopus_SourceList$Title), as.integer(Scopus_SourceList$Status == "Active"), as.integer(Scopus_SourceList$OpenAccess != "Not OA"), sqlSwitchOrNULL(Scopus_SourceList$Type, .lbs_SourceTypesFull, .lbs_SourceTypesShort ), sqlNumericOrNULL(Scopus_SourceList$SJR_2009), sqlNumericOrNULL(Scopus_SourceList$SNIP_2009), sqlNumericOrNULL(Scopus_SourceList$SJR_2010), sqlNumericOrNULL(Scopus_SourceList$SNIP_2010), sqlNumericOrNULL(Scopus_SourceList$SJR_2011), sqlNumericOrNULL(Scopus_SourceList$SNIP_2011) ); ## ------ prepare ASJCs -------------------------- asjcs <- strsplit(Scopus_SourceList$ASJC, "[[:space:]]*;[[:space:]]*"); asjcs <- lapply(asjcs, function(x) { x<- na.omit(as.integer(x)); x<- x[x>=1000 & x<=9999]; x; }); stopifnot(length(asjcs) == nrow(Scopus_SourceList)); ## ----- exec queries ------------------------ omitted <- numeric(0); k <- 0; dbExecQuery(conn, "PRAGMA journal_mode = MEMORY"); dbBegin(conn); for (i in 1:n) { tryCatch( { res <- dbSendQuery(conn, queries[i]); dbClearResult(res); # id <- as.numeric(dbGetQuery(conn, "SELECT last_insert_rowid()")[1,1]); ## == i m <- length(asjcs[[i]]); if (m > 0) { query2 <- sprintf("INSERT INTO Biblio_SourcesCategories('IdSource', 'IdCategory') %s", paste( sprintf("SELECT %.0f AS 'IdSource', %.0f AS 'IdCategory'", i, asjcs[[i]]), collapse=" UNION ")); dbExecQuery(conn, query2, TRUE); k <- k+m; } else warning(sprintf("No ASJC @ row=%g.", i)); }, error=function(err) { # print(i); # print(err); omitted <<- c(omitted, i); }); } dbCommit(conn); ## ----- now check which rows were added and report missing values ------ if (verbose) cat(sprintf("Done, %g of %g records added; %g ASJC codes processed.\n", n-length(omitted), n, k)); if (length(omitted) > 0 && verbose) { cat(sprintf("Note: %g records omitted @ rows=%s.\n", length(omitted), paste(omitted,collapse=",")) ); } } ## ---- Import categories and sources ----------------------------------- .Scopus_ImportSources_Categories(conn, verbose) .Scopus_ImportSources_Sources(conn, verbose) ## --------- VACUUM ----------------------------------------------------- dbExecQuery(conn, "VACUUM", FALSE); ## ---------------------------------------------------------------------- return(TRUE); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/scopus.importsources.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. #' Reads bibliography entries from a UTF-8 encoded CSV file. #' #' #' #' The \code{\link{read.csv}} function is used to read the bibliography. #' You may therefore freely modify its behavior #' by passing further arguments (\code{...}), see the manual page #' of \code{\link{read.table}} for details. #' #' The CSV file should consist at least of the following columns. #' \enumerate{ #' \item \code{Authors}: Author name(s) (surname first; multiple names are comma-separated, #' e.g. \dQuote{Smith John, Nowak G. W.}), #' \item \code{Title}: Document title, #' \item \code{Year}: Year of publication, #' \item \code{Source.title}: Source title, e.g. journal name, #' \item \code{Volume}: Volume number, #' \item \code{Issue}: Issue number, #' \item \code{Page.start}: Start page number, #' \item \code{Page.end}: End page number, #' \item \code{Cited.by}: Number of citations received, #' \item \code{Link}: String containing unique document identifier, by default of the form ...id=\emph{\strong{UNIQUE_ID}}&... (see \code{alternativeIdPattern} parameter), #' \item \code{Document.Type}: Document type, one of: \dQuote{Article}, \dQuote{Article in Press}, #' \dQuote{Book}, \dQuote{Conference Paper}, \dQuote{Editorial}, #' \dQuote{Erratum}, \dQuote{Letter}, \dQuote{Note}, \dQuote{Report}, #' \dQuote{Review}, \dQuote{Short Survey}, or \code{NA} #' (other categories are treated as \code{NA}s), #' \item \code{Source}: Data source identifier, must be the same as the #' \code{dbIdentifier} parameter value. It is used for parse errors detection. #' } #' #' The CSV file to be read may, for example, be created by \emph{SciVerse Scopus} #' (Export format=\emph{comma separated file, .csv (e.g. Excel)}, #' Output=\emph{Complete format} or \emph{Citations only}). #' Note that the exported CSV file sometimes needs to be corrected by hand #' (wrong page numbers, single double quotes in character strings instead of two-double quotes etc.). #' We suggest to make the corrections in a \dQuote{Notepad}-like application #' (in plain text). The function tries to indicate line numbers causing #' potential problems. #' #' @title Import bibliography entries from a CSV file. #' @param filename the name of the file which the data are to be read from, see \code{\link{read.csv}}. #' @param stopOnErrors logical; \code{TRUE} to stop on all potential parse errors or just warn otherwise. #' @param dbIdentifier character or \code{NA}; database identifier, helps detect parse errors, see above. #' @param alternativeIdPattern character; regular expression used to extract AlternativeId, \code{NA} to get the id as is, #' @param ... further arguments to be passed to \code{read.csv}. #' @return A \code{data.frame} containing the following 11 columns: #' \tabular{ll}{ #' \code{Authors} \tab Author name(s), comma-separated, surnames first.\cr #' \code{Title} \tab Document title.\cr #' \code{Year} \tab Year of publication.\cr #' \code{AlternativeId} \tab Unique document identifier.\cr #' \code{SourceTitle} \tab Title of the source containing the document.\cr #' \code{Volume} \tab Volume.\cr #' \code{Issue} \tab Issue.\cr #' \code{PageStart} \tab Start page; numeric.\cr #' \code{PageEnd} \tab End page; numeric.\cr #' \code{Citations} \tab Number of citations; numeric.\cr #' \code{DocumentType} \tab Type of the document; see above.\cr #' } #' The object returned may be imported into a local bibliometric storage via \code{\link{lbsImportDocuments}}. #' @export #' @examples #' \dontrun{ #' conn <- lbsConnect("Bibliometrics.db"); #' ## ... #' data <- Scopus_ReadCSV("db_Polish_MATH/Poland_MATH_1987-1993.csv"); #' lbsImportDocuments(conn, data, "Poland_MATH"); #' ## ... #' lbsDisconnect(conn);} #' @seealso \code{\link{Scopus_ASJC}}, \code{\link{Scopus_SourceList}}, #' \code{\link{lbsConnect}}, #' \code{\link{Scopus_ImportSources}},\cr #' \code{\link{read.table}}, \code{\link{lbsImportDocuments}} Scopus_ReadCSV <- function(filename, stopOnErrors=TRUE, dbIdentifier='Scopus', alternativeIdPattern="^.*\\id=|\\&.*$", ...) { datafile <- read.csv(filename, header = T, encoding="UTF-8", fileEncoding="UTF-8", stringsAsFactors=FALSE, ...); if (!is.na(dbIdentifier) && is.null(datafile$Source)) stop("Column not found: `Source'."); if (is.null(datafile$Authors)) stop("Column not found: `Authors'."); if (is.null(datafile$Title)) stop("Column not found: `Title'."); if (is.null(datafile$Year)) stop("Column not found: `Year'."); if (is.null(datafile$Source.title)) stop("Column not found: `Source.title'."); if (is.null(datafile$Volume)) stop("Column not found: `Volume'."); if (is.null(datafile$Issue)) stop("Column not found: `Issue'."); if (is.null(datafile$Page.start)) stop("Column not found: `Page.start'."); if (is.null(datafile$Page.end)) stop("Column not found: `Page.end'."); if (is.null(datafile$Cited.by)) stop("Column not found: `Cited.by'."); if (is.null(datafile$Link)) stop("Column not found: `Link'."); if (is.null(datafile$Document.Type)) stop("Column not found: `Document.Type'."); if (!is.na(dbIdentifier) && any(datafile$Source != dbIdentifier)) { msg <- (sprintf("source database does not match 'dbIdentifier'. This may possibly indicate a parse error. Check records: %s.", paste(which(datafile$Source != dbIdentifier), collapse=", "))); if (stopOnErrors) stop(msg) else warning(msg); } if (!is.na(alternativeIdPattern)) { datafile$AlternativeId <- gsub(alternativeIdPattern, "", datafile$Link); # REG EXP } else { datafile$AlternativeId <- datafile$Link; # AS IS } datafile$AlternativeId[datafile$AlternativeId == ""] <- NA; naAlternativeId <- which(is.na(datafile$AlternativeId)); if (length(naAlternativeId) > 0) { msg <- (sprintf("some documents do not have unique identifiers. Check line %s (or its neighborhood). \ Perhaps somethings is wrong with the end page (check for ', ' nearby).", naAlternativeId[1]+1)); if (stopOnErrors) stop(msg) else warning(msg); } checkAlternativeId <- unique(datafile$AlternativeId, incomparables=NA); if (length(checkAlternativeId) != nrow(datafile)) { msg <- (sprintf("non-unique document identifiers at rows: %s.", paste((1:nrow(datafile))[-checkAlternativeId], collapse=", "))); if (stopOnErrors) stop(msg) else warning(msg); } datafile$Cited.by[!is.na(gsub("^([[:digit:]]+)$", NA, datafile$Cited.by))] <- NA; datafile$Cited.by <- as.numeric(datafile$Cited.by); checkCitations <- which(datafile$Cited.by < 0 | datafile$Cited.by>100000); if (length(checkCitations) > 0) { msg <- (sprintf("something is wrong with citation counts at rows: %s.", paste((1:nrow(datafile))[-checkCitations], collapse=", "))); if (stopOnErrors) stop(msg) else warning(msg); } datafile$Page.start[!is.na(gsub("^([[:digit:]]+)$", NA, datafile$Page.start))] <- NA; datafile$Page.end [!is.na(gsub("^([[:digit:]]+)$", NA, datafile$Page.end ))] <- NA; datafile$Page.start <- as.numeric(datafile$Page.start); datafile$Page.end <- as.numeric(datafile$Page.end); checkPages <- which((datafile$Page.start<0) | (datafile$Page.end<datafile$Page.start) | (datafile$Page.end-datafile$Page.start>10000)); if (length(checkPages) > 0) { msg <- (sprintf("some documents seem to have incorrect page numbers. Check line %s (or its neighborhood).", checkPages[1]+1)); if (stopOnErrors) stop(msg) else warning(msg); } datafile <- data.frame(Authors=as.character(datafile$Authors), Title=as.character(datafile$Title), Year=datafile$Year, AlternativeId=datafile$AlternativeId, SourceTitle=as.character(datafile$Source.title), Volume=datafile$Volume, Issue=datafile$Issue, PageStart=datafile$Page.start, PageEnd=datafile$Page.end, Citations=datafile$Cited.by, DocumentType=datafile$Document.Type); attr(datafile, "filename") <- filename; return(datafile); }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/scopus.readcsv.R
## This file is part of the CITAN package for R ## ## Copyright 2011-2015 Marek Gagolewski ## ## ## CITAN is free software: you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## CITAN is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the ## GNU Lesser General Public License for more details. ## ## You should have received a copy of the GNU Lesser General Public License ## along with CITAN. If not, see <http://www.gnu.org/licenses/>. # Converts a numeric vector to its character representation or returns \code{"NULL"}. # # @title Get nullable numeric values for use in an SQL query # @param value numeric vector to be processed. # @return The function returns a character vector containing a # textual representations of each numeric value or \code{"NULL"}. # @export # @seealso \code{\link{sqlSwitchOrNULL}}, \code{\link{sqlStringOrNULL}} sqlNumericOrNULL <- function(value) { value <- as.character(as.numeric(value)); ifelse(is.na(value) | is.null(value), "NULL", value); } # Returns trimmed and single-quote-escaped (see \code{\link{sqlEscapeTrim}}) # character strings or \code{"NULL"}s on empty input. # # @title Get nullable character string values for use in an SQL query # @param value character vector to be processed. # @return The function returns a character vector containing a # processed input values and/or \code{"NULL"}s. # @export # @seealso \code{\link{sqlNumericOrNULL}}, \code{\link{sqlSwitchOrNULL}}, \code{\link{sqlEscapeTrim}} sqlStringOrNULL <- function(value) { value <- sqlEscapeTrim(value); ifelse(is.na(value) | is.null(value) | nchar(value)==0, "NULL", paste("'", value, "'", sep="")); } # Given a character vector, the function # tries to match each of its values up in the array \code{search}. # On success, corresponding value of \code{replace} will is returned. # Otherwise, it outputs \code{"NULL"}. # # @title Switch-like nullable construct for use in an SQL query # @param value character vector to be processed. # @param search character vector of length \code{n}. # @param replace character vector of length \code{n}. # @return The function returns a character vector containing # values from \code{replace} that correspond to elements of \code{search} and/or \code{"NULL"}s. # @export # @seealso \code{\link{sqlNumericOrNULL}}, \code{\link{sqlStringOrNULL}}, \code{\link{sqlTrim}} sqlSwitchOrNULL <- function(value, search, replace) { stopifnot(length(search) == length(replace) && length(search) > 0) value <- sqlEscapeTrim(value) #h <- hash(keys=search, values=replace); h <- new.env() for (i in seq_along(replace)) h[ search[[i]] ] <- replace[[i]] out <- sapply(value, function(x) { if (is.na(x) || nchar(x) == 0) return("NULL") ret <- h[[x]] ifelse(is.null(ret), "NULL", ret) }); #clear(h) #rm(h) return(out) } # Escapes character strings for use in an SQL query. # # The SQL standard specifies that single-quotes in strings should be # escaped by putting two single quotes in a row. # This function repeats the quotes using \code{\link{stri_replace_all_fixed}}. # # @title Escape character strings for use in an SQL query # @param str a character vector where matches are sought, or an object which can be coerced by \code{as.character} to a character vector. # @return See 'Value' for \code{\link{stri_replace_all_fixed}}. # @export # @seealso \code{\link{sqlTrim}}, \code{\link{sqlEscapeTrim}} sqlEscape <- function(str, useBytes=FALSE) { stri_replace_all_fixed(str, "'", "''") } # Trims white-spaces on both sides of a string. # # This function uses \code{\link{stri_replace_all_fixed}}. # # @title Trim white-spaces on both sides of character strings # @param str a character vector where matches are sought, or an object which can be coerced by \code{as.character} to a character vector. # @return See 'Value' for \code{\link{stri_trim_both}}. # @export # @seealso \code{\link{stri_replace_all_fixed}}, \code{\link{sqlEscape}}, \code{\link{sqlEscapeTrim}} sqlTrim <- function(str) { stri_trim_both(str) } # Escapes given character strings for use in an SQL query and trims white-spaces on both sides. # # The SQL standard specifies that single-quotes in strings should be # escaped by putting two single quotes in a row. # This function repeats the quotes using \code{\link{gsub}}. # # @title Escape character strings for use in an SQL query and trim white-spaces on both sides # @param str a character vector where matches are sought, or an object which can be coerced by \code{as.character} to a character vector. # @return character vector # @export # @seealso \code{\link{sqlEscape}}, \code{\link{sqlTrim}} sqlEscapeTrim <- function(str) { sqlEscape(sqlTrim(str)) }
/scratch/gouwar.j/cran-all/cranData/CITAN/R/string.R
bca_ci <- function(theta, alternative = "two.sided", conf.level = 0.95) { if (alternative == "two.sided") { alpha <- 1- conf.level } else { alpha <- (1 - conf.level) * 2 } low <- alpha/2 high <- 1- alpha/2 sims <- length(theta) z.inv <- length(theta[theta < mean(theta)])/sims z <- qnorm(z.inv) U <- (sims - 1) * (mean(theta) - theta) top <- sum(U^3) under <- 6 * (sum(U^2))^{3/2} a <- top/under lower.inv <- pnorm(z + (z + qnorm(low))/(1 - a * (z + qnorm(low)))) lower <- quantile(theta, lower.inv) upper.inv <- pnorm(z + (z + qnorm(high))/(1 - a * (z + qnorm(high)))) upper <- quantile(theta, upper.inv) return(c(lower, upper)) }
/scratch/gouwar.j/cran-all/cranData/CIfinder/R/bca_ci.R
bisect <- function (ftn, precis = 6, max.iter = 100, uplow = "low") { tiny <- (10^-(precis))/2 hi <- 1 lo <- -1 dp <- 2 niter <- 1 while (niter <= max.iter && any(dp > tiny | is.na(hi))) { dp <- 0.5 * dp mid <- pmax(-1, pmin(1, round((hi + lo)/2, 10))) scor <- ftn(round(tan(pi * (mid + 1)/4), 10)) check <- (scor <= 0) | is.na(scor) hi[check] <- mid[check] lo[!check] <- mid[!check] niter <- niter + 1 } if (uplow == "low") { best <- lo } else { best <- hi } return(tan((best + 1) * pi/4)) }
/scratch/gouwar.j/cran-all/cranData/CIfinder/R/bisect.R
gart_nam_ci <- function(x1, n1, x0, n0, skew = TRUE, level = 0.95, alternative = "two.sided") { p1hat <- x1 / n1 p0hat <- x0 / n0 if (alternative == "two.sided") { alpha <- 1 - level } else { alpha <- (1 - level) * 2 } myfun <- function(phi, skewswitch = skew, lev = level) { scorephi(phi = phi, x1 = x1, x0 = x0, n1 = n1, n0 = n0, conf.level = level, alternative = alternative)$score } mydsct <- function(phi, skewswitch = skew, lev = level) { scorephi(phi = phi, x1 = x1, x0 = x0, n1 = n1, n0 = n0, conf.level = level, alternative = alternative)$dsct } point_FE <- bisect( ftn = function(phi) { myfun(phi, lev = 0) - 0 }, precis = 6, uplow = "low" ) point_FE[myfun(phi = 1, lev = 0) == 0] <- 1 point <- point_FE point[myfun(phi = 1, lev = 0) == 0] <- 1 point[x1 == 0 & x0 == 0] <- NA point[(x1 > 0 & x0 == 0) & skew == FALSE] <- Inf point[x1 == n1 & x0 == n0] <- 1 at_MLE <- scorephi( phi = ifelse(is.na(point), 1, point), x1, n1, x0, n0, skew = TRUE, conf.level = 0.95, alternative = alternative ) p1t_MLE <- at_MLE$p1t p0t_MLE <- at_MLE$p0t wt_MLE <- at_MLE$wt p1hat_w <- p1hat p0hat_w <- p0hat p1t_w <- p1t_MLE p0t_w <- p0t_MLE wt_MLE <- NULL qtnorm <- qnorm(1 - alpha / 2) lower <- bisect(ftn = function(phi) { myfun(phi) - qtnorm }, precis = 6, uplow = "low") upper <- bisect(ftn = function(phi) { myfun(phi) + qtnorm }, precis = 6, uplow = "up") lower[x1 == 0] <- 0 upper[x0 == 0] <- Inf inputs <- cbind(x1 = x1, n1 = n1, x0 = x0, n0 = n0) estimates <- list( phi_mle = point, Lower = lower, Upper = upper, level = level, alternative = alternative, inputs, p1hat = p1hat_w, p0hat = p0hat_w, p1mle = p1t_w, p0mle = p0t_w, V = at_MLE$V ) return(estimates) }
/scratch/gouwar.j/cran-all/cranData/CIfinder/R/gart_nam_ci.R
#' Estimate the confidence intervals for positive predictive value (PPV) and negative predictive value (NPV) based on different methods #' #' @param x1 number of positives for both reference(true) marker and testing marker. #' @param n1 number of positives for reference (true) marker. #' @param x0 number of negatives for both reference(true) marker and testing marker. #' @param n0 number of positives for reference (true) marker. #' @param prevalence disease prevalence. #' @param method current support "gart and nam", "walter", "mover-j", "pepe", "zhou", or "delta"; Default is "gart and nam"; Check the \code{Details} for additional information for each method. #' @param conf.level confidence level. default 0.95. #' @param bias_correction Logical, indicating whether to apply bias correction in the score denominator. default FALSE. This argument can be used only for `gart and nam` method. #' @param continuity.correction logical. default FALSE. 0.5 will be applied if TRUE except the \code{zhou}'s method where \eqn{\frac{z_{\alpha/2}^2}{2}} is used. #' @param ... Other arguments passed on to method (e.g., defining the `Beta(ai,bi)` prior distributions in mover-j method for each group (default `ai = bi = 0.5` for Jeffreys method)) #' @details #' Six methods are supported in current version: "gart and nam", "walter", "mover-j", "pepe", "zhou", and "delta". #' #' Among those, \strong{gart and nam}, \strong{walter}, and \strong{mover-j} construct the confidence intervals for PPV and NPV by converting the confidence intervals for the ratio of two binomial proportions (\eqn{\phi=\frac{p_1}{p_0}}) where #'\eqn{\phi_{PPV}=\frac{(1-specificity)}{sensitivity}} and \eqn{\phi_{NPV}=\frac{(1-sensitivity)}{specificity}}. #'The sensitivity is estimated by \eqn{sensitivity=\frac{x_1}{n_1}} and the specificity by \eqn{specificity=\frac{x_0}{n_0}}. The confidence intervals for \eqn{\phi_{PPV}} and \eqn{\phi_{NPV}} #'are converted to the corresponding confidence intervals for PPV and NPV using the following equations: #'\itemize{ #'\item \eqn{PPV=\frac{\rho}{\rho+(1-\rho)*\phi_{PPV}}} #' #'\item \eqn{NPV=\frac{1-\rho}{(1-\rho)+\rho*\phi_{NPV}}} #' #'where \eqn{\rho} denotes the \code{prevalence}. #' #'} #'\enumerate{ #' \item The \strong{gart and nam} method constructs the confidence interval for \eqn{\phi} based on score method with skewness correction. See the details in the paper listed in the \code{Reference} section. #' This method can be applied to special situations where `x1=n1` or `x0=n0` but not for `x1=0` and/or `x0=0`. `continuity.correction` can be considered where `x1=0` and/or `x0=0`. #' #' \item The \strong{walter} method constructs the confidence interval for \eqn{\phi} based on \eqn{log(\phi)}. 0.5 is added to `x1`, `x0`, `n1`, and `n0`. Thus, no continuity correct should be applied additionally. This method has shown skewness concerns for #' small ratios and sample sizes. #' #' \item The \strong{mover-j} method constructs the confidence interval for \eqn{\phi} from separate intervals for the individual group rates (i.e., \eqn{p_1} and \eqn{p_0}). #' By applying the equal-tailed Jeffreys method (default 0.5 to each group), it may achieve a skewness-corrected interval for \eqn{\phi}. \cr #' \cr #' The \strong{pepe}, \strong{zhou}, and \strong{delta} are three direct confidence interval methods for PPV and NPV. #' \cr #' \item The \strong{pepe} method finds the confidence intervals for PPV and NPV via diagnostic likelihood ratios (DLR) and associated logit(PPV) and logit(NPV). This method is not applicable for special #' cases when `x1=0`, `x0=0`, `x1=n1` or `x0=n0`. Continuity correction should be considered for those special cases. #' #' \item The \strong{zhou} method can return confidence intervals from the four methods described in the paper. Without continuity correction, it will return the confidence intervals #' for PPV and NPV based on standard delta method and based on logit transformed method. If \code{continuity.correction=TRUE}, \eqn{\frac{z_{\alpha/2}^2}{2}} will be added to `x1`, `x0`, `n1`, and `n0`, and the function will return the adjusted and adjusted logit confidence intervals #' as described in the paper. #' #' \item The \strong{delta} method constructs the confidence intervals based on the Wald-type formulation. The estimates and variances of PPV and NPV are calculated based equations described in the Zhou's paper listed in the \code{Reference} section. #'} #' @return A list object contains the method and the estimates of sensitivity, specificity, PPV, NPV and their confidence intervals. #' @importFrom ratesci scoreci #' @import Rdpack kableExtra #' @references #' \enumerate{ #' \item \insertRef{gn_1988}{CIfinder} #' #' \item \insertRef{zhou_2007}{CIfinder} #' #' \item \insertRef{laud_2017}{CIfinder} #' #' \item \insertRef{pepe_2003}{CIfinder} #'} #' @importFrom ratesci moverci #' @importFrom stats pnorm quantile #' @export #' @examples #' ppv_npv_ci(60, 65, 113, 113, prevalence = 0.02) ppv_npv_ci <- function (x1, n1, x0, n0, prevalence, method = "gart and nam", conf.level = 0.95, bias_correction = FALSE, continuity.correction = FALSE, ...) { if(any(c(x1, n1, x0, n0) < 0)) { stop("All input numbers must be non-negative") } if(n1 < x1 | n0 < x0) { stop("n1 or n0 cann't be less than x1 or x0") } if(prevalence < 0 | prevalence > 1) { stop("prevalence must be in [0, 1]") } if (method == "walter" & continuity.correction) { warning("0.5 has been applied as default in Walter method. continuity.correction is not used") } if (method != "gart and nam" & bias_correction) { stop("bias correction is only applicable to gart and nam method") } prev <- prevalence # confidence interval for phi_ppv x11 <- x1 x10 <- n0-x0 x01 <- n1-x1 x00 <- x0 if (method == "gart and nam") { out <- get_gn_ci(x10 = x10, x11 = x11, x01 = x01, x00=x00, n1 = n1, n0 = n0, prev = prev, conf.level = conf.level, bias_correction = bias_correction, continuity.correction = continuity.correction) } if (method == "walter") { out <- get_walter_ci(x10 = x10, x11 = x11, x01 = x01, x00 = x00, n1 = n1, n0 = n0, prev = prev, conf.level = conf.level) } if (method == "pepe") { out <- get_pepe_ci(x11 = x11, x10 = x10, x01 = x01, x00 = x00, n1 = n1, n0 = n0, prev = prev, conf.level = conf.level, continuity.correction = continuity.correction) } if (method == "mover-j") { out <- get_moverj_ci(x10 = x10, x11 = x11, x01 = x01, x00 = x00, n1 = n1, n0 = n0, prev =prev, conf.level = conf.level, continuity.correction = continuity.correction, ...) } if (method == "zhou") { out <- get_zhou_ci(x10 = x10, x11 = x11, x01 = x01, x00 = x00, n1 = n1, n0 = n0, prev = prev, conf.level = conf.level, continuity.correction = continuity.correction) } if (method == "delta") { out <- get_delta_ci(x10 = x10, x11 = x11, x01 = x01, x00 = x00, n1 = n1, n0 = n0, conf.level = conf.level, prev = prev) } return(out) } get_gn_ci <- function (x10, x11, x01, x00, n1, n0, conf.level, prev, bias_correction, continuity.correction) { if ((x11==0 | x00==0) & !continuity.correction) { stop("x1 or x0 must be greater than zero for Gart and Nam method, or consider to use continuity correction") } # sen, spe, phi, etc sen <- x11/n1 spe <- x00/n0 phi_ppv <- (1-spe)/sen phi_npv <- (1-sen)/spe ppv_est <- prev/(prev + (1 - prev) * phi_ppv) npv_est <- (1 - prev)/(1 - prev + prev * phi_npv) ##calculate the confidence interval for phi_ppv = (1-spe)/sen fit_phi_ppv <- ratesci::scoreci(x1 = x10, n1 = n0, x2 = x11, n2 = n1, distrib = "bin", contrast = "RR", level = conf.level, bcf = bias_correction, cc = continuity.correction) phi_ppv_mle <- fit_phi_ppv$estimates[2] phi_ppv_l <- fit_phi_ppv$estimates[1] phi_ppv_u <- fit_phi_ppv$estimates[3] ppv_mle <- prev/(prev + (1 - prev) * fit_phi_ppv$estimates[2]) ppv_u <- prev/(prev + (1 - prev) * fit_phi_ppv$estimates[1]) ppv_l <- prev/(prev + (1 - prev) * fit_phi_ppv$estimates[3]) ##calculate the confidence interval for phi_npv = (1-sen)/spe fit_phi_npv <- ratesci::scoreci(x1 = x01, n1 = n1, x2 = x00, n2 = n0, distrib = "bin", contrast = "RR", level = conf.level, bcf = bias_correction, cc = continuity.correction) phi_npv_mle <- fit_phi_npv$estimates[2] phi_npv_l <- fit_phi_npv$estimates[1] phi_npv_u <- fit_phi_npv$estimates[3] npv_mle <- (1 - prev)/(1 - prev + prev * fit_phi_npv$estimates[2]) npv_l <- (1 - prev)/(1 - prev + prev * fit_phi_npv$estimates[3]) npv_u <- (1 - prev)/(1 - prev + prev * fit_phi_npv$estimates[1]) return(list(method = "gart and nam", sensitivity = sen, specificity = spe, phi_ppv = c(phi_ppv_est = phi_ppv, phi_ppv_l = phi_ppv_l, phi_ppv_u = phi_ppv_u, phi_ppv_mle = phi_ppv_mle), ppv=c(ppv_est = ppv_est, ppv_l = ppv_l, ppv_u = ppv_u, ppv_mle=ppv_mle), phi_npv = c(phi_npv_est = phi_npv, phi_npv_l = phi_npv_l, phi_npv_u = phi_npv_u, phi_npv_mle = phi_npv_mle), npv=c(npv_est = npv_est, npv_l = npv_l, npv_u = npv_u, npv_mle=npv_mle))) } get_pepe_ci <- function(x11, x10, x01, x00, n1, n0, prev, conf.level, continuity.correction) { z <- qnorm(1-(1-conf.level)/2) if (continuity.correction) { x11 <- x11 + 0.5 x10 <- x10 + 0.5 x01 <- x01 + 0.5 x00 <- x00 + 0.5 n1 <- x11 + x01 n0 <- x10 + x00 } sen <- x11 / n1 spe <- x00 / n0 phi_ppv <- (1-spe)/sen phi_npv <- (1-sen)/spe ppv_est <- prev/(prev + (1 - prev) * phi_ppv) npv_est <- (1 - prev)/(1 - prev + prev * phi_npv) dlr1 <- sen / (1 - spe) dlr0 <- (1 - sen) / spe var_log_dlr1 <- function(sen, spe, n1, n0) { (1 - sen) / (n1 * sen) + spe / (n0 * (1 - spe)) } var_log_dlr0 <- function(sen, spe, n1, n0) { sen / (n1 * (1 - sen)) + (1 - spe) / (n0 * spe) } log_dlr1_u <- log(dlr1) + z * sqrt(var_log_dlr1(sen, spe, n1, n0)) log_dlr1_l <- log(dlr1) - z * sqrt(var_log_dlr1(sen, spe, n1, n0)) dlr1_ci <- exp(c(log_dlr1_l, log_dlr1_u)) log_dlr1_ci <- c(log_dlr1_l, log_dlr1_u) logit_ppv_ci <- log(prev / (1 - prev)) + log_dlr1_ci ppv_ci <- exp(logit_ppv_ci) / (1 + exp(logit_ppv_ci)) log_dlr0_u <- log(dlr0) + z * sqrt(var_log_dlr0(sen, spe, n1, n0)) log_dlr0_l <- log(dlr0) - z * sqrt(var_log_dlr0(sen, spe, n1, n0)) dlr0_ci <- exp(c(log_dlr0_l, log_dlr0_u)) log_dlr0_ci <- c(log_dlr0_l, log_dlr0_u) logit_npv_ci <- (-log(prev / (1 - prev))) - log_dlr0_ci npv_ci <- 1/ (1 + exp(-logit_npv_ci)) return(list(method = "pepe", sensitivity = sen, specificity = spe, log_dlr_pos = c(log_dlr_pos = log(dlr1), log_dlr_pos_l = log_dlr1_l, log_dlr_pos_u = log_dlr1_u), dlr_pos = c(dlr_pos = dlr1, dlr_pos_l = dlr1_ci[1], dlr_pos_u = dlr1_ci[2]), ppv=c(ppv_est = ppv_est, ppv_l = ppv_ci[1], ppv_u = ppv_ci[2]), log_dlr_neg = c(log_dlr_neg = log(dlr0), log_dlr_neg_l = log_dlr0_l, log_dlr_neg_u = log_dlr0_u), dlr_neg = c(dlr_neg = dlr0, dlr_neg_l = dlr0_ci[1], dlr_neg_u = dlr0_ci[2]), npv=c(npv_est = npv_est, npv_l = npv_ci[2], npv_u = npv_ci[1]))) } get_moverj_ci <- function(x10, x11, x01, x00, n1, n0, prev, conf.level, continuity.correction, ...) { # sen, spe, phi, etc sen <- x11/n1 spe <- x00/n0 phi_ppv <- (1-spe)/sen phi_npv <- (1-sen)/spe ppv_est <- prev/(prev + (1 - prev) * phi_ppv) npv_est <- (1 - prev)/(1 - prev + prev * phi_npv) phi_ppv_ests <- moverci(x10, n0, x11, n1, level = conf.level, contrast = "RR", distrib = "bin", type = "jeff", cc = continuity.correction, ...) phi_ppv_l <- phi_ppv_ests[1] phi_ppv_u <- phi_ppv_ests[3] ppv_u <- prev/(prev + (1 - prev) * phi_ppv_l) ppv_l <- prev/(prev + (1 - prev) * phi_ppv_u) phi_npv_ests <- moverci(x01, n1, x00, n0, level = conf.level, contrast = "RR", distrib = "bin", type = "jeff", cc = continuity.correction, ...) phi_npv_l <- phi_npv_ests[1] phi_npv_u <- phi_npv_ests[3] npv_l <- (1 - prev)/(1 - prev + prev * phi_npv_u) npv_u <- (1 - prev)/(1 - prev + prev * phi_npv_l) return(list(method = "mover-j", sensitivity = sen, specificity = spe, phi_ppv = c(phi_ppv_est = phi_ppv_ests[2], phi_ppv_l = phi_ppv_l, phi_ppv_u = phi_ppv_u), ppv=c(ppv_est = ppv_est, ppv_l = ppv_l, ppv_u = ppv_u), phi_npv = c(phi_npv_est = phi_npv_ests[2], phi_npv_l = phi_npv_l, phi_npv_u = phi_npv_u), npv=c(npv_est = npv_est, npv_l = npv_l, npv_u = npv_u))) } get_delta_ci <- function(x10, x11, x01, x00, n1, n0, prev, conf.level) { z <- qnorm(1-(1-conf.level)/2) sen <- x11 / n1 spe <- x00 / n0 sen_var <- (sen*(1-sen))/n1 spe_var <- (spe*(1-spe))/n0 ## delta method ppv_est <-(sen*prev)/(sen*prev + (1-prev)*(1-spe)) npv_est <- ((1-prev)*spe)/(prev * (1-sen) + (1-prev) * spe) ppv_var <- ((prev*(1-spe)*(1-prev))^2*sen_var + (prev*sen*(1-prev))^2*spe_var)/(sen*prev + (1-spe)*(1-prev))^4 npv_var <- ((spe*(1-prev)*prev)^2*sen_var + ((1-sen)*(1-prev)*prev)^2*spe_var)/((1-sen)*prev+spe*(1-prev))^4 ppv_u <- ppv_est + z * sqrt(ppv_var) ppv_l <- ppv_est - z * sqrt(ppv_var) npv_u <- npv_est + z * sqrt(npv_var) npv_l <- npv_est - z * sqrt(npv_var) return(list(method = "delta", sensitivity = sen, specificity = spe, ppv=c(ppv_est = ppv_est, ppv_l = ppv_l, ppv_u = ppv_u), npv=c(npv_est = npv_est, npv_l = npv_l, npv_u = npv_u))) } get_zhou_ci <- function(x10, x11, x01, x00, n1, n0, prev, conf.level, continuity.correction) { z <- qnorm(1-(1-conf.level)/2) if (continuity.correction) { k = qnorm(1-(1-conf.level)/2) c.correct = k^2/2 x11 <- x11 + c.correct x10 <- x10 + c.correct x01 <- x01 + c.correct x00 <- x00 + c.correct n1 <- x11 + x01 n0 <- x10 + x00 } ## sen, spe and vars sen <- x11 / n1 spe <- x00 / n0 sen_var <- (sen*(1-sen))/n1 spe_var <- (spe*(1-spe))/n0 ## delta method ppv_est <-(sen*prev)/(sen*prev + (1-prev)*(1-spe)) npv_est <- ((1-prev)*spe)/(prev * (1-sen) + (1-prev) * spe) ppv_var <- ((prev*(1-spe)*(1-prev))^2*sen_var + (prev*sen*(1-prev))^2*spe_var)/(sen*prev + (1-spe)*(1-prev))^4 npv_var <- ((spe*(1-prev)*prev)^2*sen_var + ((1-sen)*(1-prev)*prev)^2*spe_var)/((1-sen)*prev+spe*(1-prev))^4 ppv_u <- ppv_est + z * sqrt(ppv_var) ppv_l <- ppv_est - z * sqrt(ppv_var) npv_u <- npv_est + z * sqrt(npv_var) npv_l <- npv_est - z * sqrt(npv_var) # logit transformation logit_ppv_est <- log((sen*prev)/((1-spe)*(1-prev))) logit_npv_est <- log((spe*(1-prev))/((1-sen)*prev)) logit_ppv_var <- ((1-sen)/sen)/n1 + (spe/(1-spe))/n0 logit_npv_var <- (sen/(1-sen))/n1 + ((1-spe)/spe)/n0 ppv_logit_transformed_u <- exp(logit_ppv_est + z * sqrt(logit_ppv_var))/(1 + exp(logit_ppv_est + z * sqrt(logit_ppv_var))) ppv_logit_transformed_l <- exp(logit_ppv_est - z * sqrt(logit_ppv_var))/(1 + exp(logit_ppv_est - z * sqrt(logit_ppv_var))) npv_logit_transformed_u <- exp(logit_npv_est + z * sqrt(logit_npv_var))/(1 + exp(logit_npv_est + z * sqrt(logit_npv_var))) npv_logit_transformed_l <- exp(logit_npv_est - z * sqrt(logit_npv_var))/(1 + exp(logit_npv_est - z * sqrt(logit_npv_var))) return(list(method = "zhou", sensitivity = sen, specificity = spe, ppv=c(ppv_est = ppv_est, ppv_l = ppv_l, ppv_u = ppv_u), npv=c(npv_est = npv_est, npv_l = npv_l, npv_u = npv_u), ppv_logit_transformed=c(ppv_est = ppv_est, ppv_l = ppv_logit_transformed_l, ppv_u = ppv_logit_transformed_u), npv_logit_transformed=c(npv_est = npv_est, npv_l = npv_logit_transformed_l, npv_u = npv_logit_transformed_u))) } walter_ci <- function(x1, n1, x0, n0, conf.level) { z <- qnorm(1-(1-conf.level)/2) p0 <- x0 / n0 p1 <- x1 / n1 q0 <- 1 - p0 q1 <- 1 - p1 phi <- p1 / p0 log_phi <- log((x1 + 0.5) / (n1 + 0.5)) - log((x0 + 0.5) / (n0 + 0.5)) u <- 1 / (x1 + 0.5) - 1 / (n1 + 0.5) + 1 / (x0 + 0.5) - 1 / (n0 + 0.5) lower <- exp(log_phi) * exp(-z * sqrt(u)) upper <- exp(log_phi) * exp(z * sqrt(u)) return(c(phi = phi, lower = lower, upper = upper)) } get_walter_ci <- function(x10, x11, x01, x00, n1, n0, prev, conf.level) { sen <- x11/n1 spe <- x00/n0 phi_ppv <- (1-spe)/sen phi_npv <- (1-sen)/spe ppv_est <- prev/(prev + (1 - prev) * phi_ppv) npv_est <- (1 - prev)/(1 - prev + prev * phi_npv) ##calculate the confidence interval for phi_ppv = (1-spe)/sen fit_phi_ppv <- walter_ci(x1 = x10, n1 = n0, x0 = x11, n0 = n1, conf.level = conf.level) ppv_u <- prev/(prev + (1 - prev) * fit_phi_ppv[2]) ppv_l <- prev/(prev + (1 - prev) * fit_phi_ppv[3]) ##calculate the confidence interval for phi_npv = (1-sen)/spe fit_phi_npv <- walter_ci(x1 = x01, n1 = n1, x0 = x00, n0 = n0, conf.level = conf.level) npv_u <- (1 - prev)/(1 - prev + prev * fit_phi_npv[2]) npv_l <- (1 - prev)/(1 - prev + prev * fit_phi_npv[3]) return(list(method = "walter", sensitivity = sen, specificity = spe, phi_ppv = c(fit_phi_ppv[1], fit_phi_ppv[2], fit_phi_ppv[3]), ppv=c(ppv_est = ppv_est, ppv_l = unname(ppv_l), ppv_u = unname(ppv_u)), phi_npv = c(fit_phi_npv[1], fit_phi_npv[2], fit_phi_npv[3]), npv=c(npv_est = npv_est, npv_l = unname(npv_l), npv_u = unname(npv_u)))) }
/scratch/gouwar.j/cran-all/cranData/CIfinder/R/ppv_npv_ci.R
scorephi <- function(phi, x1, n1, x0, n0, skew = TRUE, cc = FALSE, conf.level = 0.95, alternative = "two.sided") { if (alternative == "two.sided") { alpha <- 1- conf.level } else { alpha <- (1 - conf.level) * 2 } p1hat <- x1 / n1 p0hat <- x0 / n0 x <- x1 + x0 N <- n1 + n0 bias <- 0 lambda <- ifelse(cc, N/(N-1), 1) #see page 346 LAUD, 2017 Sphi <- p1hat - p0hat * phi # Ap0^2+bp0+c=0 A <- N * phi B <- (-(n1 * phi + x1 + n0 + x0 * phi)) C <- x num <- (-B - sqrt(pmax(0, B^2 - 4 * A * C))) p0t <- ifelse(A == 0, -C / B, ifelse((num == 0 | C == 0), 0, num / (2 * A))) p1t <- p0t * phi V <- pmax(0, (p1t * (1 - p1t) / n1 + (phi^2) * p0t * (1 - p0t) / n0)*lambda) mu3 <- (p1t * (1 - p1t) * (1 - 2 * p1t) / (n1^2) - (phi^3) * p0t * (1 - p0t) * (1 - 2 * p0t) / (n0^2)) V[is.na(V)] <- Inf ##apply to equation(3), page 336, LAUD 2017 scterm <- mu3 / (6 * V^(3 / 2)) scterm[mu3 == 0] <- 0 score1 <- Sphi / sqrt(V) score1[Sphi == 0] <- 0 A <- scterm B <- 1 C <- -(score1 + scterm) num <- (-B + sqrt(pmax(0, B^2 - 4 * A * C))) dsct <- B^2 - 4 * A * C score <- ifelse((skew == FALSE | scterm == 0), score1, num / (2 * A) ) if (skew == TRUE) { qtnorm <- stats::qnorm(1 - alpha / 2) scoresimp <- score1 - (qtnorm^2 - 1) * scterm score[!is.na(dsct) & dsct < 0] <- scoresimp[!is.na(dsct) & dsct < 0] } pval <- stats::pnorm(score) outlist <- list( score = score, p1t = p1t, Sphi = Sphi, num = num, V = V, p0t = p0t, mu3 = mu3, pval = pval, dsct = dsct ) return(outlist) }
/scratch/gouwar.j/cran-all/cranData/CIfinder/R/scorephi.R
#' Compute the confidence interval for a single proportion based on different methods #' #' @param x number of successes #' @param n number of trials #' @param method one of these options "all", "clopper.pearson", "wald", "wislon", "wislon.correct", "agresti", or "beta" #' @param alternative indicates "two.sided", "one.sided" #' @param conf.level confidence level #' @param prior the prior values for "beta" method #' #' @return Estimated confidence intervals for the probability of success #' @importFrom stats qbeta binom.test qnorm prop.test #' @export #' #' @examples #' single_prop_ci(53, 57, method = "all") single_prop_ci <- function(x, n, method = "all", alternative = "two.sided", conf.level=0.95, prior = c(1, 1)) { if (method == "all"){ return(list(clopper_ci = clopper_ci(x, n, test = alternative, conf.level = conf.level), wilson = wilson_ci(x, n, test = alternative, conf.level = conf.level), wilson.correct =wilson.correct_ci(x, n, test = alternative, conf.level = conf.level), wald = wald_ci(x, n, test = alternative, conf.level = conf.level), agresti = agresti_ci(x, n, test = alternative, conf.level = conf.level), beta_binomial = beta_binomial(x, n, test = alternative, conf.level = conf.level, prior = prior))) } outrange <- x > n | x < 0 if (any(outrange)) { stop("x must be non-nagative and less or equal to n;") } if (method == "clopper.pearson"){ return(clopper_ci = clopper_ci(x, n, test = alternative, conf.level = conf.level)) } if (method == "wilson"){ return(wilson = wilson_ci(x, n, test = alternative, conf.level = conf.level)) } if (method == "wilson.correct"){ return(wilson.correct = wilson.correct_ci(x, n, test = alternative, conf.level = conf.level)) } if (method == "wald"){ return(wald = wald_ci(x, n, test = alternative, conf.level = conf.level)) } if (method == "agresti"){ return(agresti = agresti_ci(x, n, test = alternative, conf.level = conf.level)) } if (method == "beta"){ return(beta_binomial = beta_binomial(x, n, test = alternative, conf.level = conf.level, prior = prior)) } } wilson_ci <- function(x, n, test = "two.sided", conf.level = 0.95) { limits <- prop.test(x, n, alternative = test, conf.level = conf.level, correct = FALSE)$conf.int limits <- c(limits[1], limits[2]) names(limits) <- c('wilson_lower','wilson_upper') limits } wilson.correct_ci <- function(x, n, test = "two.sided", conf.level = 0.95) { limits <- prop.test(x, n, alternative = test, conf.level = conf.level, correct = TRUE)$conf.int limits <- c(limits[1], limits[2]) names(limits) <- c('wilson.correct_lower','wilson.correct_upper') limits } wald_ci <- function(x, n, test = "two.sided", conf.level = 0.95) { p <- x/n se <- sqrt(p * (1 - p)/n) if (test == "two.sided") { conf.level <- conf.level z <- c(qnorm((1 - conf.level)/2), qnorm(1 - (1 - conf.level)/2)) limits <- p + z * se names(limits) <- c('wald_lower','wald_upper') limits } else { conf.level <- 1-(1-conf.level)*2 z <- c(qnorm((1 - conf.level)/2), qnorm(1 - (1 - conf.level)/2)) limits <- p + z * se if (test == "less"){ ci <- c(0, max(limits)) names(ci) <- c('wald_lower','wald_upper') return(ci) } if (test == "greater"){ ci <- c(min(limits), 1) names(ci) <- c('wald_lower','wald_upper') return(ci) } } } agresti_ci <- function(x, n, test = "two.sided", conf.level = 0.95) { if (test == "two.sided") { conf.level <- conf.level z <- c(qnorm((1 - conf.level)/2), qnorm(1 - (1 - conf.level)/2)) n_tilde <- n + (z[1])^2 p_tilde <- (1/n_tilde)*(x + (z[1])^2/2) se <- sqrt((p_tilde/n_tilde)*(1-p_tilde)) limits <- p_tilde + z * se names(limits) <- c('agresti_lower','agresti_upper') limits } else { conf.level <- 1-(1-conf.level)*2 z <- c(qnorm((1 - conf.level)/2), qnorm(1 - (1 - conf.level)/2)) n_tilde <- n + (z[1])^2 p_tilde <- (1/n_tilde)*(x + (z[1])^2/2) se <- sqrt((p_tilde/n_tilde)*(1-p_tilde)) limits <- p_tilde + z * se if (test == "less"){ ci <- c(0, max(limits)) names(ci) <- c('agresti_lower','agresti_upper') return(ci) } if (test == "greater"){ ci <- c(min(limits), 1) names(ci) <- c('agresti_lower','agresti_upper') return(ci) } } } clopper_ci <- function(x, n, test = "two.sided", conf.level=0.95) { limits <- as.numeric(binom.test(x, n, alternative = test, conf.level=conf.level)$conf.int) names(limits) <- c('cp_lower','cp_upper') limits } beta_binomial <- function(x, n, test = "two.sided", conf.level = 0.95, prior = c(1,1)){ if (test == "two.sided") { conf.level <- conf.level limit <- (1-conf.level)/2 limits <- qbeta(c(limit, 1-limit), x+prior[1],n-x+prior[2]) names(limits) <- c('beta_lower','beta_upper') limits } else { conf.level <- 1-(1-conf.level)*2 limit <- (1-conf.level)/2 limits <- qbeta(c(limit, 1-limit), x+prior[1],n-x+prior[2]) if (test == "less"){ ci <- c(0, max(limits)) names(ci) <- c('beta_lower','beta_upper') return(ci) } if (test == "greater"){ ci <- c(min(limits), 1) names(ci) <- c('beta_lower','beta_upper') return(ci) } } }
/scratch/gouwar.j/cran-all/cranData/CIfinder/R/single_prop_ci.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----global, include=FALSE---------------------------------------------------- library(CIfinder) library(kableExtra) ## ----eval = FALSE------------------------------------------------------------- # install.packages("CIfinder") ## ----echo=FALSE--------------------------------------------------------------- bdat <- data.frame(Case = c(31, 3, 34), Control = c(12, 32, 44)) rownames(bdat) <- c("Poor_Signature", "Good_Signature", "Total") kable(bdat, caption = "Table 1. Breast cancer data from a molecular signature classifier") %>% kable_classic(full_width = F, html_font = "Cambria") ## ----gn----------------------------------------------------------------------- library(CIfinder) ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "gart and nam") ## ----zhou1-------------------------------------------------------------------- ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "zhou") ## ----zhou2-------------------------------------------------------------------- ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "zhou", continuity.correction = TRUE) ## ----echo=FALSE--------------------------------------------------------------- bdat <- data.frame(Case = c(31, 3, 34), Control = c(0, 44, 44)) rownames(bdat) <- c("Poor_Signature", "Good_Signature", "Total") kable(bdat, caption = "Table 1. Example of a special testing data") %>% kable_classic(full_width = F, html_font = "Cambria") ## ----gn2---------------------------------------------------------------------- ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "gart and nam") ## ----walter------------------------------------------------------------------- ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "walter") ## ----zhou3-------------------------------------------------------------------- ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "zhou", continuity.correction = TRUE)
/scratch/gouwar.j/cran-all/cranData/CIfinder/inst/doc/CIfinder.R
--- title: "Computing the confidence intervals for predictive values" author: "Dadong Zhang, Jingye Wang, Johan Surtihadi" output: rmarkdown::html_vignette bibliography: REFERENCES.bib date: '`r format(Sys.Date())`' vignette: > %\VignetteIndexEntry{Eestimating confidence interval for predictive values} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r global, include=FALSE} library(CIfinder) library(kableExtra) ``` ## Introduction CIfinder is an R package intended to provide functions to compute confidence intervals for the positive predictive value (PPV) and negative predictive value (NPV) based on varied scenarios. In prospective studies where the proportion of diseased subjects provides an unbiased estimate of the disease prevalence, the confidence intervals for PPV and NPV can be estimated by methods that are applicable to single proportions. In this case, the package provides six methods for cocmputing the confidence intervals: "clopper.pearson", "wald", "wilson", "wilson.correct", "agresti", and "beta". In situations where the proportion of diseased subjects does not correspond to the disease prevalence (e.g. case-control studies), this package provides two types of solutions: I) three methods to estimate confidence intervals for PPV and NPV via ratio of two binomial proportions, including Gart & Nam (1988) <https://doi.org/10.2307/2531848>, Walter (1975) <https://doi.org/10.1093/biomet/62.2.371>, and MOVER-J (Laud, 2017) <https://doi.org/10.1002/pst.1813>; II) three direct methods to compute the confidence intervals, including Pepe (2003) <https://doi.org/10.1002/sim.2185>, Zhou (2007) <doi:10.1002/sim.2677>, and Delta <https://doi.org/10.1002/sim.2677>. For more information, please see the Details and References sections in the user's manual. ## Installation You can install the latest version of `CIfinder` by: ``` {r eval = FALSE} install.packages("CIfinder") ``` ## Example use To demonstrate the utility of the `CIfinder::ppv_npv_ci()` function for calculating the confidence intervals for PPV and NPV, we will use a case-control study published by van de Vijver et al. (2002) <https://doi.org/10.1056/NEJMoa021967>. In the study, Cases were defined as those that have metastasis within 5 years of tumour excision, while controls were those that did not. Each tumor was classified as having a good or poor gene signature which was defined as having a signature correlation coefficient above or below the ‘optimized sensitivity’ threshold, respectively. This ‘optimized sensitivity’ threshold is defined as the correlation value that would result in a misclassification of at most 10 per cent of the cases. The performance of their 70-gene signature as prognosticator for metastasis is summarized in Table 1 below: ```{r echo=FALSE} bdat <- data.frame(Case = c(31, 3, 34), Control = c(12, 32, 44)) rownames(bdat) <- c("Poor_Signature", "Good_Signature", "Total") kable(bdat, caption = "Table 1. Breast cancer data from a molecular signature classifier") %>% kable_classic(full_width = F, html_font = "Cambria") ``` ### Generate the confidence interval for $PPV$ or $NPV$ Since this was a case-control study, the proportion of cases (34/(34+44)=43.6%) is not an unbiased estimate of its prevalence (assumed 7%). PPV and NPV and their confidence intervals can't be estimated directly. To calculate the confidence interval based "gart and nam" method: ```{r gn} library(CIfinder) ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "gart and nam") ``` In this output, phi_ppv denotes $\phi_{PPV}=\frac{1-specificity}{sensitivity}$ in the function to estimate $PPV=\frac{\rho}{\rho+(1-\rho)\phi_{PPV}}$, where $\rho$ is the prevalence. Similarly, phi_npv denotes $\phi_{NPV}=\frac{1-sensitivity}{specificity}$ in the function to estimate $NPV=\frac{1-\rho}{(1-\rho)+\rho\phi_{NPV}}$. ppv and npv provide the results for the estimates, lower confidence limit, upper confidence limit and the maximum likelihood estimate based on score method described in the Gart and Nam paper. To calculate the confidence interval based "zhou's method" ```{r zhou1} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "zhou") ``` In this output, since continuity correction isn't specified, the estimates and confidence intervals in `ppv` and `npv` are same as the standard delta method where the `ppv_logit_transformed` and `npv_logit_transformed` refer the standard logit method described in the paper. If `continuity.correction` is being specified: ```{r zhou2} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "zhou", continuity.correction = TRUE) ``` In this case, a continuity correction value $\frac{z_{\alpha/2}^2}{2}$ is applied. The `ppv` and `npv` outputs refer the "Adjusted" in the paper and `ppv_logit_transformed` and `npv_logit_transformed` denote the "Adjusted logit" method described in the paper. ### Confidence interval for special cases Assume we have a special case data where $x_0=n_0$: ```{r echo=FALSE} bdat <- data.frame(Case = c(31, 3, 34), Control = c(0, 44, 44)) rownames(bdat) <- c("Poor_Signature", "Good_Signature", "Total") kable(bdat, caption = "Table 1. Example of a special testing data") %>% kable_classic(full_width = F, html_font = "Cambria") ``` In this situation, `Pepe`, `Delta`, and `Zhou` (standard logit) methods can not be used without continuity correction. `Walter` method can be used, but there may have skewness concerns. `gart and nam` and `mover-j` could be considered. ```{r gn2} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "gart and nam") ``` Comparing to the `Walter` output: ```{r walter} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "walter") ``` Note, for `walter`, no continuity.correction should be used as 0.5 has been used as described by the original paper. Also comparing to the Zhou's adjusted methods: ```{r zhou3} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "zhou", continuity.correction = TRUE) ``` ## Feedback and Report issues We appreciate any feedback, comments and suggestions. If you have any questions or issues to use the package, please reach out to the developers.
/scratch/gouwar.j/cran-all/cranData/CIfinder/inst/doc/CIfinder.Rmd
--- title: "Computing the confidence intervals for predictive values" author: "Dadong Zhang, Jingye Wang, Johan Surtihadi" output: rmarkdown::html_vignette bibliography: REFERENCES.bib date: '`r format(Sys.Date())`' vignette: > %\VignetteIndexEntry{Eestimating confidence interval for predictive values} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r global, include=FALSE} library(CIfinder) library(kableExtra) ``` ## Introduction CIfinder is an R package intended to provide functions to compute confidence intervals for the positive predictive value (PPV) and negative predictive value (NPV) based on varied scenarios. In prospective studies where the proportion of diseased subjects provides an unbiased estimate of the disease prevalence, the confidence intervals for PPV and NPV can be estimated by methods that are applicable to single proportions. In this case, the package provides six methods for cocmputing the confidence intervals: "clopper.pearson", "wald", "wilson", "wilson.correct", "agresti", and "beta". In situations where the proportion of diseased subjects does not correspond to the disease prevalence (e.g. case-control studies), this package provides two types of solutions: I) three methods to estimate confidence intervals for PPV and NPV via ratio of two binomial proportions, including Gart & Nam (1988) <https://doi.org/10.2307/2531848>, Walter (1975) <https://doi.org/10.1093/biomet/62.2.371>, and MOVER-J (Laud, 2017) <https://doi.org/10.1002/pst.1813>; II) three direct methods to compute the confidence intervals, including Pepe (2003) <https://doi.org/10.1002/sim.2185>, Zhou (2007) <doi:10.1002/sim.2677>, and Delta <https://doi.org/10.1002/sim.2677>. For more information, please see the Details and References sections in the user's manual. ## Installation You can install the latest version of `CIfinder` by: ``` {r eval = FALSE} install.packages("CIfinder") ``` ## Example use To demonstrate the utility of the `CIfinder::ppv_npv_ci()` function for calculating the confidence intervals for PPV and NPV, we will use a case-control study published by van de Vijver et al. (2002) <https://doi.org/10.1056/NEJMoa021967>. In the study, Cases were defined as those that have metastasis within 5 years of tumour excision, while controls were those that did not. Each tumor was classified as having a good or poor gene signature which was defined as having a signature correlation coefficient above or below the ‘optimized sensitivity’ threshold, respectively. This ‘optimized sensitivity’ threshold is defined as the correlation value that would result in a misclassification of at most 10 per cent of the cases. The performance of their 70-gene signature as prognosticator for metastasis is summarized in Table 1 below: ```{r echo=FALSE} bdat <- data.frame(Case = c(31, 3, 34), Control = c(12, 32, 44)) rownames(bdat) <- c("Poor_Signature", "Good_Signature", "Total") kable(bdat, caption = "Table 1. Breast cancer data from a molecular signature classifier") %>% kable_classic(full_width = F, html_font = "Cambria") ``` ### Generate the confidence interval for $PPV$ or $NPV$ Since this was a case-control study, the proportion of cases (34/(34+44)=43.6%) is not an unbiased estimate of its prevalence (assumed 7%). PPV and NPV and their confidence intervals can't be estimated directly. To calculate the confidence interval based "gart and nam" method: ```{r gn} library(CIfinder) ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "gart and nam") ``` In this output, phi_ppv denotes $\phi_{PPV}=\frac{1-specificity}{sensitivity}$ in the function to estimate $PPV=\frac{\rho}{\rho+(1-\rho)\phi_{PPV}}$, where $\rho$ is the prevalence. Similarly, phi_npv denotes $\phi_{NPV}=\frac{1-sensitivity}{specificity}$ in the function to estimate $NPV=\frac{1-\rho}{(1-\rho)+\rho\phi_{NPV}}$. ppv and npv provide the results for the estimates, lower confidence limit, upper confidence limit and the maximum likelihood estimate based on score method described in the Gart and Nam paper. To calculate the confidence interval based "zhou's method" ```{r zhou1} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "zhou") ``` In this output, since continuity correction isn't specified, the estimates and confidence intervals in `ppv` and `npv` are same as the standard delta method where the `ppv_logit_transformed` and `npv_logit_transformed` refer the standard logit method described in the paper. If `continuity.correction` is being specified: ```{r zhou2} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 32, n0 = 44, prevalence = 0.07, method = "zhou", continuity.correction = TRUE) ``` In this case, a continuity correction value $\frac{z_{\alpha/2}^2}{2}$ is applied. The `ppv` and `npv` outputs refer the "Adjusted" in the paper and `ppv_logit_transformed` and `npv_logit_transformed` denote the "Adjusted logit" method described in the paper. ### Confidence interval for special cases Assume we have a special case data where $x_0=n_0$: ```{r echo=FALSE} bdat <- data.frame(Case = c(31, 3, 34), Control = c(0, 44, 44)) rownames(bdat) <- c("Poor_Signature", "Good_Signature", "Total") kable(bdat, caption = "Table 1. Example of a special testing data") %>% kable_classic(full_width = F, html_font = "Cambria") ``` In this situation, `Pepe`, `Delta`, and `Zhou` (standard logit) methods can not be used without continuity correction. `Walter` method can be used, but there may have skewness concerns. `gart and nam` and `mover-j` could be considered. ```{r gn2} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "gart and nam") ``` Comparing to the `Walter` output: ```{r walter} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "walter") ``` Note, for `walter`, no continuity.correction should be used as 0.5 has been used as described by the original paper. Also comparing to the Zhou's adjusted methods: ```{r zhou3} ppv_npv_ci(x1 = 31, n1 = 34, x0 = 44, n0 = 44, prevalence = 0.07, method = "zhou", continuity.correction = TRUE) ``` ## Feedback and Report issues We appreciate any feedback, comments and suggestions. If you have any questions or issues to use the package, please reach out to the developers.
/scratch/gouwar.j/cran-all/cranData/CIfinder/vignettes/CIfinder.Rmd
#' @rdname CIplot #' @include CIplot.glm.R #' #' @method CIplot ORci #' @export #' #' @keywords plot #' @keywords ORci #' CIplot.ORci <- function(x, xlog = TRUE, xlab = "Odds Ratio", v = 1, ...) { xi <- x conf.level <- attr(x, "conf.level") xi <- unclass(x) CIplot.default(xi, xlog = xlog, xlab = xlab, conf.level = conf.level, v = v, ...) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.ORci.R
#' Plot Confidential Interval #' #' A function to plot confidential interval for #' such as \code{htest}, \code{TukeyHSD}, #' \code{glht} (\pkg{multcomp}), #' \code{glm} (logistic regression only!) #' and \code{posthocTGH} (\pkg{userfriendlyscience}) objects. #' #' @importFrom stats coefficients confint #' @importFrom graphics abline arrows axis box plot points #' #' @export #' #' #' @note \code{CIplot} was made based on \code{plot.TukeyHSD}. #' \preformatted{ #' # File src/library/stats/R/TukeyHSD.R #' # Part of the R package, https://www.R-project.org #' # #' # Copyright (C) 2000-2001 Douglas M. Bates #' # Copyright (C) 2002-2015 The R Core Team #' } #' #' @seealso \code{plot}, \code{axis}, \code{points}, \code{par}. #' #' @keywords plot #' CIplot <- function(x, ...) UseMethod("CIplot")
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.R
#' @rdname CIplot #' @include CIplot.htest.R #' #' @aliases CIplot.TukeyHSD #' #' @method CIplot TukeyHSD #' @export #' #' @examples #' #' ##### 'TukeyHSD' objects #' require(graphics) #' #' ## Tukey test #' aov1 <- aov(breaks ~ tension + wool, data = warpbreaks) #' x <- TukeyHSD(aov1) #' #' oldpar <- par(no.readonly = TRUE) #' par(mfrow = c(1, 2)) #' CIplot(x, las = 1) #' par(oldpar) #' #' ## example of line type and color #' aov1 <- aov(breaks ~ tension, data = warpbreaks) #' x <- TukeyHSD(aov1) #' CIplot(x, las = 1, #' pcol = 2:4, pcolbg = 2:4, cicol = 2:4, #' vlty = 1, vcol = "gray") #' #' @keywords plot #' @keywords TukeyHSD #' CIplot.TukeyHSD <- function(x, xlab = "Differences in mean", v = 0, ...) { conf.level <- attr(x, "conf.level") for (i in seq_along(x)) { xi <- x[[i]] CIplot.default(xi, xlab = xlab, v = v, ...) } }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.TukeyHSD.R
#' @rdname CIplot #' @include CIplot.R #' #' @method CIplot default #' @export #' #' @param x \code{default}: \code{matrix} or \code{data.frame} class #' with 3 columns ('any name', \code{lwr}, \code{upr}), #' or an object: \code{htest}, \code{TukeyHSD}, #' \code{glht} (\pkg{multcomp}), #' \code{glm} (logistic regression only!) #' or \code{posthocTGH} (\pkg{userfriendlyscience}). #' @param xlog (logical) if \code{log} is \code{TRUE}, #' the x axis is drawn logarithmically. #' Default is \code{FALSE}. #' @param xlab a title for the plot. #' @param xlim the x limits (x1, x2) of the plot. #' @param yname If \code{yname} is \code{TRUE}, #' the name of comparison between groups are shown. #' @param las numeric in {0,1,2,3}; the style of axis labels. #' Default is 0. see also \code{par}. #' @param pch plotting 'character', i.e., symbol to use. #' @param pcol color code or name of the points. #' @param pcolbg background (fill) color for the open plot symbols #' given by 'pch = 21:25'. #' @param pcex character (or symbol) expansion of points. #' @param conf.level \code{default} and \code{glm} object only. #' the confidence interval. Default is 0.95. #' see also \code{\link{ORci}}. #' @param cilty line types of conficence intervals. #' @param cilwd line width of conficence intervals. #' @param cicol color code or name of conficence intervals. #' @param v the x-value(s) for vertical line. #' @param vlty line types of vertical line. #' @param vlwd line width of vertical line. #' @param vcol color code or name of vertical line. #' @param main a main title for the plot. #' @param \dots other options for x-axis. #' #' @examples #' ##### default (matrix or data.frame) #' require(graphics) #' x <- matrix(c(3, 1, 5, #' 4, 2, 6), 2, 3, byrow = TRUE) #' colnames(x) <- c("esti", "lwr", "upr") #' rownames(x) <- c("A", "B") #' CIplot(x, xlab = "difference", v = 2, las = 1) #' #' @keywords plot #' ## x: matrix or data.frame(estimation, lwr, upr) ## v: required CIplot.default <- function(x, xlog = FALSE, xlim = NULL, xlab = NULL, ## x-axis yname = TRUE, las = 0, ## y-axis pch = 21, pcol = 1, pcolbg = "white", pcex = 1, ## points conf.level = 0.95, cilty = 1, cilwd = 1, cicol = 1, ## conf.int v, vlty = 2, vlwd = 1, vcol = 1, ## vertical main = NULL, ## Title ...) { if (ncol(x) < 3L) { stop("x is required at least 3 columns.\n") } if (is.matrix(x)) x <- as.data.frame(x) if (is.null(main)) { main <- paste0(format(100 * conf.level, digits = 2L), "% confidence interval") } xi <- x[,1:3] ## estimation, lwr, upr yvals <- nrow(xi):1L if (is.null(xlim)) xlim <- c(min(xi), max(xi)) plot(c(xi[,"lwr"], xi[,"upr"]), rep.int(yvals, 2L), type = "n", axes = FALSE, xlab = xlab, ylab = "", xlim = xlim, log = ifelse(xlog, "x", ""), ylim = c(0.5, nrow(xi) + 0.5), main = main) axis(1, ...) if (yname) { axis(2, at = nrow(xi):1, labels = dimnames(xi)[[1L]], las = las) } abline(v = v, lty = vlty, lwd = vlwd, col = vcol) arrows(xi[, "lwr"], yvals, xi[, "upr"], yvals, code = 3, angle = 90, length = 0.15, lty = cilty, lwd = cilwd, col = cicol) points(xi[, 1], yvals, pch = pch, cex = pcex, col = pcol, bg = pcolbg) box() }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.default.R
#' @rdname CIplot #' @include CIplot.TukeyHSD.R #' #' @aliases CIplot.glht #' #' @import multcomp #' #' @method CIplot glht #' @export #' #' @examples #' ##### 'glht' objects #' require(graphics) #' #' ## Tukey test #' require(multcomp) #' aov1 <- aov(breaks ~ tension, data = warpbreaks) #' x <- glht(aov1, linfct = mcp(tension = "Tukey")) #' CIplot(x, las = 1) #' #' ## Dunnett test #' x <- glht(aov1, linfct = mcp(tension = "Dunnett")) #' CIplot(x, las = 1) #' #' @keywords plot #' @keywords glht #' CIplot.glht <- function(x, xlab = "Differences in mean", v = 0, ...) { xi <- confint(x)$confint conf.level <- attr(xi, "conf.level") CIplot.default(xi, xlab = xlab, v = v, ...) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.glht.R
#' @rdname CIplot #' @include CIplot.glht.R #' #' @method CIplot glm #' @export #' # #' @param conf.level \code{glm} object only. # #' the confidence interval. Default is 0.95. # #' see also \code{\link{ORci}}. #' #' @examples #' #' ##### 'glm' object: logistic regression only! #' ## odds ratio #' require(graphics) #' require(MASS) #' data(birthwt) #' x <- glm(low ~ age + lwt + smoke + ptl + ht + ui, data = birthwt, #' family = binomial) #' CIplot(x, las = 1) #' #' @keywords plot #' @keywords glm #' CIplot.glm <- function(x, conf.level = 0.95, xlog = TRUE, xlab = "Odds Ratio", v = 1, ...) { ci <- ORci(x, conf.level = conf.level) CIplot.ORci(ci, xlog = xlog, xlab = xlab, v = v, ...) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.glm.R
#' @rdname CIplot #' @include CIplot.default.R #' #' @method CIplot htest #' @export #' #' @examples #' ##### 'htest' objects #' require(graphics) #' #' ## t test #' set.seed(1234) #' a <- rnorm(10, 10, 2); b <- rnorm(10, 8, 2) #' x <- t.test(a, b) #' CIplot(x) #' #' ## binomial test #' x <- binom.test(5, 20) #' CIplot(x, xlim = c(0, 1)) #' #' ## Fisher's exact test #' x <- matrix(c(10, 7, 8, 9), 2, 2, byrow = TRUE) #' res <- fisher.test(x) #' CIplot(res, xlog = TRUE) #' #' @keywords plot #' @keywords htest #' CIplot.htest <- function(x, xlog = FALSE, xlim = NULL, xlab = NULL, yname = FALSE, v = NULL, ...) { est <- x$estimate ci <- x$conf.int if (is.null(ci)) { warning("No information about confidential interval\n") return(invisible(NULL)) } if (length(est) == 2L) est <- est[1] - est[2] if (is.null(v)) { if (is.null(x$null.value)) { v <- ifelse(log, 1, 0) } else { v <- x$null.value } } if (is.null(xlim)) { xlim <- c(min(v, ci[1]), max(v, ci[2])) } if (is.null(xlab)) { xlab <- attr(x$null.value, "names") if (is.null(xlab)) { xlab <- ifelse(log, "ratio", "difference") } } tmp <- data.frame(estimate = est, lwr = ci[1], upr = ci[2]) CIplot.default(tmp, xlog = xlog, xlim = xlim, xlab = xlab, yname = yname, conf.level = attr(x$conf.int, "conf.level"), v = v, ...) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.htest.R
#' @rdname CIplot #' @include CIplot.R #' #' @aliases CIplot.posthocTGH #' #' @method CIplot posthocTGH #' @export #' #' @examples #' #' ##### 'posthocTGH' object #' ## Tukey or Games-Howell methos #' require(graphics) #' if (require(userfriendlyscience)) { #' x <- posthocTGH(warpbreaks$breaks, warpbreaks$tension) #' CIplot(x, las = 1) #' } #' #' @keywords plot #' @keywords posthocTGH #' CIplot.posthocTGH <- function(x, xlab = "Differences in mean", v = 0, ...) { if (x$input$method == 'tukey') { xi <- x$output$tukey } else if (x$input$method == 'games-howell') { xi <- x$output$games.howell } colnames(xi)[2:3] <- c("lwr", "upr") conf.level <- x$input$conf.level CIplot.default(xi, xlab = xlab, conf.level = conf.level, v = v, ...) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/CIplot.posthocTGH.R
#' Calculate odds ratios and their confidence intervals #' from \code{glm} object #' #' @import MASS #' #' @export #' #' @param x \code{glm} object (logistic regression only!). #' @param conf.level the confidence interval. Default is 0.95. #' @return an object \code{ORci} and \code{matirix} classes with four columns. #' \describe{ #' \item{OR}{odds ratio} #' \item{lwr}{lower conficence intarval} #' \item{upr}{upper conficence intarval} #' \item{p.value}{P value by logistic regression} #' } #' #' @examples #' require(graphics) #' require(MASS) #' data(birthwt) #' x <- glm(low ~ age + lwt + smoke + ptl + ht + ui, data = birthwt, #' family = binomial) #' OR1 <- ORci(x) #' CIplot(OR1, las = 1) ORci <- function(x, conf.level = 0.95) { est <- coefficients(x) ci <- confint(x, level = conf.level) p <- summary(x)$coefficients[-1, 4] OR <- cbind(exp(cbind(est, ci)[-1,]), p) colnames(OR) <- c("OR", "lwr", "upr", "p.value") attr(OR, "conf.level") <- conf.level attr(OR, "class") <- c("ORci", "matrix") return(OR) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/ORci.R
#' Print Methods for Odds Ratios and their Confidence Intervals #' of \code{ORci} object #' #' Print odds ratios and their confidence intervals of \code{ORci} object. #' #' @method print ORci #' @export #' #' @param x \code{ORci} object.see alse \code{\link{ORci}}. #' @param \dots other options for print such as \code{digits}. #' #' @seealso \code{glm}, \code{\link{ORci}}. #' #' @examples #' require(MASS) #' data(birthwt) #' x <- glm(low ~ age + lwt + smoke + ptl + ht + ui, data = birthwt, #' family = binomial) #' OR1 <- ORci(x) #' print(OR1, digits = 3) #' print.ORci <- function(x, ...) { attr(x, "conf.level") <- NULL attr(x, "class") <- NULL print(x, ...) }
/scratch/gouwar.j/cran-all/cranData/CIplot/R/print.ORci.R
#' C-JAMP: Copula-based joint analysis of multiple phenotypes. #' #' Functions to perform C-JAMP: \code{\link{cjamp}} fits a joint model of two #' phenotypes conditional on one or multiple predictors; \code{\link{cjamp_loop}} #' uses \code{\link{cjamp}} to fit the same copula model separately for a list of #' multiple predictors, e.g. for a genetic association study. #' #' Both functions \code{\link{cjamp}} and \code{\link{cjamp_loop}} fit a joint copula model #' of two phenotypes using the Clayton copula or 2-parameter copula, conditional on none #' or multiple predictors and covariates in the marginal models. The \code{\link[optimx]{optimx}} #' function of the \code{optimx} package is used to maximize the log-likelihood (i.e. to minimize #' the minus log-likelihood function \code{\link{minusloglik}}) to obtain #' maximum likelihood coefficient estimates of all parameters. #' For this, the BFGS optimization method is recommended. Standard error estimates #' of the coefficient estimates can be obtained by using #' the observed inverse information matrix. P-values from hypothesis tests of #' the absence of effects of each predictor on each phenotype in the marginal #' models can be obtained from large-sample Wald-type tests (see the vignette for details). #' #' It should be noted that \code{\link{cjamp}}, \code{\link{cjamp_loop}} and #' \code{\link{minusloglik}}) assume quantitative predictors and use an #' additive model, i.e. for categorical predictors with more than 2 levels, #' dummy variables have to be created beforehand. Accordingly, if single #' nucleotide variants (SNVs) are included as predictors, the computation is #' based on an additive genetic model if SNVs are provided as 0-1-2 genotypes #' and on a dominant model if SNVs are provided as 0-1 genotypes. #' #' The \code{\link{cjamp}} function returns point estimates of all parameters, #' standard error estimates and p-values for all marginal parameters (i.e. all parameters #' for \code{predictors_Y1}, \code{predictors_Y1}), the minus #' log-likelihood value as well as information about the convergence. The #' \code{\link{cjamp_loop}} function only returns point estimates, standard error #' estimates, and p-values for the specified predictors \code{predictors} and not #' the covariates \code{covariates_Y1} and \code{covariates_Y2}, in addition #' to the minus log-likelihood value as well as convergence information. #' #' It is recommended that all variables are centered and scaled before the analysis, #' which can be done through the \code{scale_var} parameter. Otherwise, if the scales #' of the variables differ, it can lead to convergence problems of the optimization. #' #' @param copula String indicating whether the joint model will be computed #' under the Clayton (\code{"Clayton"}) or 2-parameter copula #' (\code{"2param"}) model. #' @param Y1 Numeric vector containing the first phenotype. #' @param Y2 Numeric vector containing the second phenotype. #' @param predictors_Y1 Dataframe containing the predictors of \code{Y1} #' in columns (for the \code{\link{cjamp}} function). #' @param predictors_Y2 Dataframe containing the predictors of \code{Y2} #' in columns (for the \code{\link{cjamp}} function). #' @param scale_var Logical. Indicating whether all predictors will be centered and #' scaled before the analysis or not (default: FALSE). #' @param predictors Dataframe containing the predictors of \code{Y1} #' and \code{Y2} in columns for which estimates are returned #' (for the \code{\link{cjamp_loop}} function). #' @param covariates_Y1 Dataframe containing the covariates of \code{Y1} #' in columns for which estimates are not returned #' (for the \code{\link{cjamp_loop}} function). #' @param covariates_Y2 Dataframe containing the covariates of \code{Y2} #' in columns for which estimates are not returned #' (for the \code{\link{cjamp_loop}} function). #' @param optim_method String passed to the \code{\link[optimx]{optimx}} #' function. It specifies the optimization method in the #' \code{\link[optimx]{optimx}} function that is used for #' maximizing the log-likelihood function. Recommended is the #' \code{"BFGS"} optimization method (default). For further #' methods, see the description of the #' \code{\link[optimx]{optimx}} function. #' @param trace Integer passed to the \code{\link[optimx]{optimx}} #' function. It specifies the tracing information on the progress #' of the optimization. The value \code{2} gives full tracing, #' default value \code{0} blocks all details. See also the \code{\link[optimx]{optimx}} #' documentation. #' @param kkt2tol Numeric. Passed to the \code{\link[optimx]{optimx}} #' function, default value is 1E-16. It specifies the tolerance for #' the eigenvalue ratio in the Karush-Kuhn-Tucker (KKT) test for a positive definite #' Hessian matrix. See also the \code{\link[optimx]{optimx}} #' documentation. #' @param SE_est Logical indicator whether standard error estimates are #' computed for the parameters using the inverse of the observed #' information matrix (\code{TRUE}, default), or whether standard #' error estimates are not computed (\code{FALSE}). #' @param pval_est Logical indicator whether p-values are computed from #' hypothesis tests of the absence of effects of each predictor #' on each phenotype in the marginal models (\code{TRUE}, default), #' or whether p-values are not computed (\code{FALSE}). P-values #' are obtained from large sample Wald-type tests based on the #' maximum likelihood parameter estimates and the standard error #' estimates. #' @param n_iter_max Integer indicating the maximum number of optimization attempts #' of the log-likelihood function with different starting values, #' if the optimization doesn't converge (default: 10). #' @return An object of class \code{cjamp}, for which the summary function #' \code{\link{summary.cjamp}} is implemented. The output is a list #' containing estimates of the copula parameters, marginal parameters, Kendall's #' tau (as well as the upper and lower tail dependence \eqn{\lambda_l, #' \lambda_u} if the 2-parameter copula model is fitted), the standard #' error estimates of all parameters, p-values of hypothesis tests #' of the marginal parameters (i.e. of the absence of predictor effects on the #' phenotypes), the convergence code of the log-likelihood maximization #' (from the \code{\link[optimx]{optimx}} #' function, where 0 indicates successful convergence), the KKT #' conditions 1 and 2 of the convergence, and the maximum log-likelihood value. #' #' @examples #' #' # Data generation #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 100) #' phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, #' MAF_cutoff = 1, prop_causal = 1, #' tau = 0.2, b1 = 0.3, b2 = 0.3) #' predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' genodata[, 1:3]) #' #' ## Not run. When executing, the following takes about 2 minutes running time. #' ## Example 1: Analysis of multiple SNVs as predictors in one model #' #cjamp(copula = "Clayton", Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' # predictors_Y1 = predictors, predictors_Y2 = predictors, #' # optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, #' # pval_est = TRUE, n_iter_max = 10) #' #cjamp(copula = "2param", Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' # predictors_Y1 = predictors, predictors_Y2 = predictors, #' # optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, #' # pval_est = TRUE, n_iter_max = 10) #' # #' ## Example 2: Analysis of multiple SNVs in separate models #' #covariates <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) #' #predictors <- genodata #' #cjamp_loop(copula = "Clayton", Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' # predictors = predictors, covariates_Y1 = covariates, #' # covariates_Y2 = covariates, optim_method = "BFGS", trace = 0, #' # kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, #' # n_iter_max = 10) #' #' @export #' cjamp <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (pval_est & !SE_est) { stop("SE_est has to be TRUE to compute p-values.") } if (!requireNamespace("optimx", quietly = TRUE)) { stop("Package optimx needed for this function to work. Please install it.", call. = FALSE) } if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (stats::cor(Y1, Y2, use = "complete.obs", method = "kendall") < 0) { Y2 <- -Y2 warning("Dependence between Y1, Y2 is negative but copulas require positive dependence. \n Hence Y2 is transformed to -Y2 and point estimates for Y2 are in inverse direction.") } if (copula == "Clayton") { n_dep <- 1 copula_param = "phi" } if (copula == "2param") { n_dep <- 2 copula_param = "both" } if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] n_pred <- 0 } if (!is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & stats::complete.cases(predictors_Y1)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] } if (is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & stats::complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y2)[2] } if (!is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & stats::complete.cases(predictors_Y1) & stats::complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] + dim(predictors_Y2)[2] } if (scale_var) { predictors_Y1 <- data.frame(lapply(predictors_Y1, scale)) predictors_Y2 <- data.frame(lapply(predictors_Y2, scale)) } convcode <- 1 kkt <- c(FALSE, FALSE) n_iter <- 1 helpnum <- 0.4 while (!(convcode == 0 & all(kkt) & !any(is.na(kkt))) & (n_iter <= n_iter_max)) { startvalues <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) - helpnum names_pred <- names(startvalues[(n_dep + 3):length(startvalues)]) if (minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues) == Inf | is.na(minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues))) { helpnum <- (-1)^stats::rbinom(1, 1, 0.5) * stats::runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 next } res <- optimx::optimx(par = startvalues, fn = minusloglik, Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, method = optim_method, hessian = TRUE, control = list(trace = trace, kkt2tol = kkt2tol)) convcode <- res$convcode kkt <- c(res$kkt1, res$kkt2) helpnum <- (-1)^stats::rbinom(1, 1, 0.5) * stats::runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 } names(convcode) <- "convcode" names(kkt) <- c("KKT1", "KKT2") maxloglik <- NULL if (!convcode == 0) { warning("In model with predictors \n", names_pred, ": \n Optimization doesn't seem to be converged.", "\n SE estimates and pvalues are not computed. Please check.") } if (!all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n KKT conditions are not satistified.", " \n SE estimates and pvalues are not computed. Please check.") } if (!convcode == 0 | !all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n Naive parameter estimates are computed from separate marginal models.") point_estimates <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) point_estimates <- as.list(point_estimates) if (copula == "Clayton") { phi <- exp(point_estimates$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(point_estimates$log_phi) theta <- exp(point_estimates$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates[(n_dep + 1):length(point_estimates)], phi, theta, tau, lambda_l, lambda_u) point_estimates[[1]] <- exp(point_estimates[[1]]) point_estimates[[2]] <- exp(point_estimates[[2]]) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (convcode == 0 & all(kkt) & !any(is.na(kkt))) { maxloglik <- res$value names(maxloglik) <- "maxloglik" point_estimates <- res[(n_dep + 1):(n_dep + n_pred + 4)] point_estimates[1:2] <- exp(point_estimates[1:2]) if (copula == "Clayton") { phi <- exp(res$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(res$log_phi) theta <- exp(res$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates, phi, theta, tau, lambda_l, lambda_u) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } SE_estimates <- NULL if (SE_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { SE_estimates <- vector(mode = "numeric", length = (n_pred + 4)) SE_estimates[1] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 1] * (point_estimates$Y1_sigma^2)) SE_estimates[2] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 2] * (point_estimates$Y2_sigma^2)) SE_estimates[3:length(SE_estimates)] <- sqrt(diag(solve(attributes(res)$details[[3]]))[(n_dep + 3):(n_dep + n_pred + 4)]) if (copula == "Clayton") { helpvar1 <- 2 * phi/((phi + 2)^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) tau_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (helpvar1^2)) theta_SE <- lambda_l_SE <- lambda_u_SE <- NA } if (copula == "2param") { helpvar3.1 <- 2 * phi/(theta * (phi + 2)^2) helpvar3.2 <- 2 * (theta - 1)/(theta^2 * (phi + 2)) helpvar3.3 <- (2^(-1/(theta * phi))) * (log(2)/(theta * phi)) helpvar3.4 <- (2^(-1/(theta * phi))) * (log(2) * (theta - 1)/(theta^2 * phi)) helpvar3.5 <- (2^(1/theta)) * ((theta - 1) * log(2)/theta^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) theta_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * ((theta - 1)^2)) tau_SE <- sqrt(t(c(helpvar3.1, helpvar3.2)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.1, helpvar3.2)) lambda_l_SE <- sqrt(t(c(helpvar3.3, helpvar3.4)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.3, helpvar3.4)) lambda_u_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * helpvar3.5^2) } SE_estimates <- c(SE_estimates, phi_SE, theta_SE, tau_SE, lambda_l_SE, lambda_u_SE) names(SE_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (is.null(SE_estimates)){ SE_estimates <- rep(NA, length(point_estimates)) } pval <- NULL point_estimates <- unlist(point_estimates) if (pval_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { pval <- vector(mode = "numeric", length = (n_pred + 2)) pval <- 2 * stats::pnorm(as.numeric(-abs(point_estimates[3:(n_pred + 4)]/ SE_estimates[3:(n_pred + 4)]))) names(pval) <- names_pred } if (is.null(pval)){ pval <- rep(NA, (n_pred + 2)) } output <- list(point_estimates = point_estimates, SE_estimates = SE_estimates, pval = pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates", "Parameter standard error estimates", "Parameter p-values", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } #' @rdname cjamp #' @export cjamp_loop <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors = NULL, covariates_Y1 = NULL, covariates_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (is.null(predictors)) { stop("At least one predictor has to be supplied.") } if (!class(predictors) == "data.frame") { stop("Predictors has to be a dataframe.") } if (!all(sapply(predictors, is.numeric))) { predictors <- as.data.frame(data.matrix(predictors)) warning("predictors contains non-numeric Variables, which have automatically been transformed.") } if ((!class(covariates_Y1) == "data.frame" & !is.null(covariates_Y1)) | (!class(covariates_Y2) == "data.frame" & !is.null(covariates_Y2))) { stop("covariates_Y1 and covariates_Y2 have to be a dataframe or NULL.") } if (class(covariates_Y1) == "data.frame") { if (!all(sapply(covariates_Y1, is.numeric))) { covariates_Y1 <- as.data.frame(data.matrix(covariates_Y1)) warning("covariates_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(covariates_Y2) == "data.frame") { if (!all(sapply(covariates_Y2, is.numeric))) { covariates_Y2 <- as.data.frame(data.matrix(covariates_Y2)) warning("covariates_Y2 contains non-numeric Variables, which have automatically been transformed.") } } N <- dim(predictors)[2] Y1_point_estimates <- Y1_SE_estimates <- Y1_pval <- NULL Y2_point_estimates <- Y2_SE_estimates <- Y2_pval <- NULL convcode <- kkt <- maxloglik <- NULL for (i in 1:N) { names_pred_i <- names(predictors)[i] predictors_Y1 <- predictors_Y2 <- predictors[, i, drop = FALSE] if (!is.null(covariates_Y1)) { predictors_Y1 <- cbind(predictors_Y1, as.data.frame(covariates_Y1)) } if (!is.null(covariates_Y2)) { predictors_Y2 <- cbind(predictors_Y2, as.data.frame(covariates_Y2)) } n_pred_Y1 <- dim(predictors_Y1)[2] n_pred_Y2 <- dim(predictors_Y2)[2] results <- cjamp(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, scale_var = scale_var, copula = copula, optim_method = optim_method, trace = trace, kkt2tol = kkt2tol, SE_est = SE_est, pval_est = pval_est, n_iter_max = n_iter_max) Y1_point_estimates[i] <- as.numeric(results[[1]][4]) Y2_point_estimates[i] <- as.numeric(results[[1]][5 + n_pred_Y1]) Y1_SE_estimates[i] <- results[[2]][4] Y2_SE_estimates[i] <- results[[2]][5 + n_pred_Y1] Y1_pval[i] <- results[[3]][2] Y2_pval[i] <- results[[3]][3 + n_pred_Y1] names(Y1_point_estimates)[i] <- names(Y2_point_estimates)[i] <- names_pred_i names(Y1_SE_estimates)[i] <- names(Y2_SE_estimates)[i] <- names_pred_i names(Y1_pval)[i] <- names(Y2_pval)[i] <- names_pred_i convcode[i] <- results[[4]] kkt[i] <- all(results[[5]]) maxloglik[i] <- results[[6]] } output <- list(Y1_point_estimates = Y1_point_estimates, Y2_point_estimates = Y2_point_estimates, Y1_SE_estimates = Y1_SE_estimates, Y2_SE_estimates = Y2_SE_estimates, Y1_pval = Y1_pval, Y2_pval = Y2_pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates for effects of predictors on Y1", "Parameter point estimates for effects of predictors on Y2", "Parameter standard error estimates for effects on Y1", "Parameter standard error estimates for effects on Y2", "Parameter p-values for effects of predictors on Y1", "Parameter p-values for effects of predictors on Y2", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/cjamp.R
#' Compute minor allele frequency of genetic variants. #' #' Function to compute the minor allele frequency (MAF) of #' one or more genetic variants. #' #' @param genodata Numeric vector or dataframe containing the genetic variants #' in columns. Must be in allelic coding 0, 1, 2. #' @return A vector containing the minor allele frequencies of the variants. #' #' @examples #' # Example of a single variant #' set.seed(10) #' genodata <- stats::rbinom(2000, 2, 0.3) #' compute_MAF(genodata) #' #' # Example of a set of variants #' genodata <- generate_genodata() #' compute_MAF(genodata) #' #' @export #' compute_MAF <- function(genodata) { MAF <- NULL if (is.null(dim(genodata))) { dat <- genodata[!is.na(genodata)] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF > 0.5) { warning("MAF is larger than 0.5, maybe recode alleles?") } } if (!is.null(dim(genodata))) { for (i in 1:dim(genodata)[2]) { dat <- genodata[, i][!is.na(genodata[, i])] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF[i] <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF[i] > 0.5) { warning(paste("MAF of SNV ",i ," is larger than 0.5, maybe recode alleles?",sep="")) } } } names(MAF) <- names(genodata) return(MAF) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/compute_MAF.R
#' Phenotypic variance explained by genetic variants. #' #' Function to estimate the percentage of the variance of a phenotype #' that can be explained by given single nucleotide variants #' (SNVs). #' #' Four different approaches are available to estimate the percentage of #' explained phenotypic variance (Laird & Lange, 2011): #' #' (1) \code{"Rsquared_unadj"}: Unadjusted \eqn{R^2}{R2} from a linear regression of #' the phenotype conditional on all provided SNVs. #' #' (2) \code{"Rsquared_adj"}: Adjusted \eqn{R^2}{R2} from a linear regression of #' the phenotype conditional on all provided SNVs. #' #' (3) \code{"MAF_based"}: Expected explained phenotypic variance computed based on the #' MAF and effect size of the provided causal SNVs. #' #' (4) \code{"MAF_based_Y_adjusted"}: Expected explained phenotypic variance computed #' based on the MAF and effect size of the causal SNVs, with respect to the empirical #' phenotypic variance, which is the broad-sense heritability relative to the #' empirical phenotypic variance. #' #' References: #' #' Laird NM, Lange C (2011). The fundamentals of modern statistical genetics. New York: Springer. #' #' @param genodata Numeric vector or dataframe containing the genetic variant(s) in #' columns. Must be in allelic coding 0, 1, 2. #' @param phenodata Numeric vector or dataframe of the phenotype. #' @param type String (vector) specifying the estimation approach(es) that are computed. #' Available are the methods \code{"Rsquared_unadj"}, #' \code{"Rsquared_adj"}, \code{"MAF_based"}, and #' \code{"MAF_based_Y_adjusted"}. See below for more details. #' @param causal_idx Vector with entries \code{TRUE}, \code{FALSE} specifying which #' SNVs are causal. Has to be supplied for the approaches #' \code{MAF_based} and \code{MAF_based_Y_adjusted}. #' @param effect_causal Numeric vector containing the effect sizes of the causal SNVs. #' Has to be supplied for the approaches \code{MAF_based} and #' \code{MAF_based_Y_adjusted}. #' @return A list containing the estimated percentage of explained phenotypic variance. #' #' @examples #' #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) #' phenodata <- generate_phenodata_1_simple(genodata = genodata[,1], #' type = "quantitative", b = 0) #' compute_expl_var(genodata = genodata, phenodata = phenodata$Y, #' type = c("Rsquared_unadj", "Rsquared_adj"), #' causal_idx = NULL, effect_causal = NULL) #' #' @export #' compute_expl_var <- function(genodata = NULL, phenodata = NULL, type = "Rsquared_unadj", causal_idx = NULL, effect_causal = NULL) { ExplVar <- NULL if (is.null(phenodata) | is.null(genodata)) { stop("Genodata and phenodata have to be supplied.") } if (!dim(genodata)[1] == length(phenodata)) { stop("Number of observations in genodata and phenodata has to be the same.") } if (class(genodata) == "data.frame") { if (!all(sapply(genodata, is.numeric))) { genodata <- as.data.frame(data.matrix(genodata)) } } if (is.null(dim(genodata))) { if (!is.numeric(genodata)) { stop("genodata has to be numeric.") } } if (class(phenodata) == "data.frame") { if (!all(sapply(phenodata, is.numeric))) { phenodata <- as.data.frame(data.matrix(phenodata)) warning("phenodata contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(dim(phenodata))) { if (!is.numeric(phenodata)) { stop("phenodata has to be numeric.") } } if (is.null(causal_idx)) { warning("A vector indicating the causal SNVs is not supplied \n so the estimate of explained variance is based on all SNVs.") } if (any(type %in% c("MAF_based", "MAF_based_Y_adjusted")) & is.null(effect_causal)) { stop("A vector indicating the genetic effect sizes of the causal SNVs has \n to be supplied for the MAF_based and MAF_based_Y_adjusted approach.") } if (!is.null(causal_idx)) { genodata <- as.data.frame(genodata[, causal_idx]) } MAF_causal <- compute_MAF(genodata) phenodata <- as.data.frame(phenodata) dat <- as.data.frame(append(phenodata, genodata)) dat <- dat[stats::complete.cases(dat),] names(dat)[1] <- "Y" ExplVar <- list() if ("Rsquared_unadj" %in% type) { ExplVar$Rsquared_unadj <- summary(stats::lm(Y ~ ., data = dat))$r.squared } if ("Rsquared_adj" %in% type) { ExplVar$Rsquared_adj <- summary(stats::lm(Y ~ ., data = dat))$adj.r.squared } if ("MAF_based" %in% type) { ExplVar$MAF_based <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2) } if ("MAF_based_Y_adjusted" %in% type) { ExplVar$MAF_based_Y_adjusted <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2)/stats::var(dat$Y) } return(ExplVar) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/explained_variance.R
#' Generate data from the Clayton copula. #' #' Function to generate two quantitative phenotypes \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2}, #' from the bivariate Clayton copula with standard normal #' marginal distributions. #' #' @param phi Integer specifying the value of the copula parameter \eqn{\phi} for #' the dependence between the two generated phenotypes. #' @param n Sample size. #' @return A dataframe containing \code{n} observations of \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2}. #' #' @examples #' #' set.seed(10) #' dat1a <- generate_clayton_copula(n = 1000, phi = 0.5) #' dat1b <- generate_clayton_copula(n = 1000, phi = 2) #' dat1c <- generate_clayton_copula(n = 1000, phi = 8) #' par(mfrow = c(3, 1)) #' plot(dat1a$Y1, dat1a$Y2, main="Clayton copula, tau = 0.2") #' plot(dat1b$Y1, dat1b$Y2, main="Clayton copula, tau = 0.5") #' plot(dat1c$Y1, dat1c$Y2, main="Clayton copula, tau = 0.8") #' #' @export #' generate_clayton_copula <- function(n = NULL, phi = NULL) { U1 <- stats::runif(n, min = 0, max = 1) U2 <- stats::runif(n, min = 0, max = 1) Y1 <- stats::qnorm(U1, mean = 0, sd = 1) Y2.help <- (1 - U1^(-phi) * (1 - U2^(-phi/(1 + phi))))^(-1/phi) tau <- phi/(phi + 2) Y2 <- stats::qnorm(Y2.help, mean = 0, sd = 1) phenodata <- data.frame(Y1 = Y1, Y2 = Y2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/generate_copula.R
#' Functions to generate genetic data. #' #' Functions to generate genetic data in the form of single #' nucleotide variants (SNVs). The function #' \code{\link{generate_singleton_data}} generates singletons (i.e. SNVs with #' one observed minor allele); \code{\link{generate_doubleton_data}} #' generates doubletons (i.e. SNVs with two observed minor alleles), and the #' function \code{\link{generate_genodata}} generates \code{n_ind} #' observations of \code{n_SNV} SNVs with random minor allele frequencies. #' #' @param n_ind Integer specifying the number of observations that are generated. #' @param n_SNV Integer specifying the number of SNVs that are generated. #' @return A dataframe containing \code{n_ind} observations of \code{n_SNV} SNVs. #' #' @examples #' set.seed(10) #' genodata1 <- generate_singleton_data() #' compute_MAF(genodata1) #' #' genodata2 <- generate_doubleton_data() #' compute_MAF(genodata2) #' #' genodata3 <- generate_genodata() #' compute_MAF(genodata3) #' #' @export #' generate_genodata <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) for (i in 1:n_SNV) { MAFhelp <- round(stats::runif(1, 0, 0.5), 3) n0 <- round((1 - MAFhelp)^2 * n_ind) n2 <- round(MAFhelp^2 * n_ind) n1 <- n_ind - n0 - n2 helpvec <- c(rep(0, n0), rep(1, n1), rep(2, n2)) genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } #' @rdname generate_genodata #' @export generate_singleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, rep(0, n_ind - 1)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } #' @rdname generate_genodata #' @export generate_doubleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, 1, rep(0, n_ind - 2)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/generate_genodata.R
#' Functions to generate phenotype data. #' #' Functions to generate standard normal or binary phenotypes based on provided genetic #' data, for specified effect sizes. #' The functions \code{\link{generate_phenodata_1_simple}} and #' \code{\link{generate_phenodata_1}} generate one phenotype Y conditional on #' single nucleotide variants (SNVs) and two covariates. #' \code{\link{generate_phenodata_2_bvn}} as well as \code{\link{generate_phenodata_2_copula}} #' generate two phenotypes \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2} with dependence Kendall's tau conditional on #' the provided SNVs and two covariates. #' #' In more detail, the function \code{\link{generate_phenodata_1_simple}} #' generates a quantitative or binary phenotype Y with n observations, #' conditional on the specified SNVs with given effect sizes and conditional #' on one binary and one standard normally-distributed covariate with #' specified effect sizes. n is given through the provided SNVs. #' #' \code{\link{generate_phenodata_1}} provides an extension of #' \code{\link{generate_phenodata_1_simple}} and allows to further select #' the percentage of causal SNVs, a minor allele frequency cutoff on the #' causal SNVs, and varying effect directions. n is given through the #' provided SNVs. #' #' The function \code{\link{generate_phenodata_2_bvn}} generates #' two quantitative phenotypes \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2} conditional on one binary and one #' standard normally-distributed covariate \eqn{X_1}{X1}, \eqn{X_2}{X2} from the bivariate #' normal distribution so that they have have dependence \eqn{\tau} given #' by Kendall's \code{tau}. #' #' The function \code{\link{generate_phenodata_2_copula}} generates #' two quantitative phenotypes \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2} conditional on one binary and one #' standard normally-distributed covariate \eqn{X_1}{X1}, \eqn{X_2}{X2} from the Clayton copula #' so that \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2} are marginally normally distributed and have dependence #' Kendall's tau specified by \code{tau} or \code{phi}, using the function #' \code{\link{generate_clayton_copula}}. #' #' The genetic effect sizes are the specified numeric values \code{b} and #' \code{b1, b2}, respectively, in the functions \code{\link{generate_phenodata_1_simple}} #' and \code{\link{generate_phenodata_2_bvn}}. In #' \code{\link{generate_phenodata_1}} and \code{\link{generate_phenodata_2_copula}}, #' the genetic effect sizes are computed by multiplying \code{b} or \code{b1, b2}, #' respectively, with the absolute value of the log10-transformed #' minor allele frequencies, so that rarer variants have larger effect sizes. #' #' @param genodata Numeric input vector or dataframe containing the genetic #' variant(s) in columns. Must be in allelic coding 0, 1, 2. #' @param type String with value \code{"quantitative"} or \code{"binary"} #' specifying whether normally-distributed or binary phenotypes #' are generated. #' @param a Numeric vector specifying the effect sizes of the covariates \eqn{X_1}{X1}, \eqn{X_2}{X2} #' in the data generation. #' @param a1 Numeric vector specifying the effect sizes of the covariates \eqn{X_1}{X1}, \eqn{X_2}{X2} #' on the first phenotype in the data generation. #' @param a2 Numeric vector specifying the effect sizes of the covariates \eqn{X_1}{X1}, \eqn{X_2}{X2} #' on the second phenotype in the data generation. #' @param b Integer or vector specifying the genetic effect size(s) of #' the provided SNVs (\code{genodata}) in the data generation. #' @param b1 Integer or vector specifying the genetic effect size(s) of #' the provided SNVs (\code{genodata}) on the first phenotype #' in the data generation. #' @param b2 Integer or vector specifying the genetic effect size(s) of #' the provided SNVs (\code{genodata}) on the second phenotype #' in the data generation. #' @param phi Integer specifying the parameter \eqn{\phi} for #' the dependence between the two generated phenotypes. #' @param tau Integer specifying Kendall's tau, which determines the #' dependence between the two generated phenotypes. #' @param MAF_cutoff Integer specifying a minor allele frequency cutoff to #' determine among which SNVs the causal SNVs are #' sampled for the phenotype generation. #' @param prop_causal Integer specifying the desired percentage of causal SNVs #' among all SNVs. #' @param direction String with value \code{"a"}, \code{"b"}, or \code{"c"} #' specifying whether all causal SNVs have a positive effect on #' the phenotypes (\code{"a"}), 20\% of the causal SNVs have a #' negative effect and 80\% a positive effect on the phenotypes #' (\code{"b"}), or 50\% of the causal SNVs have a negative #' effect and 50\% a positive effect on the phenotypes (\code{"c"}). #' @return A dataframe containing n observations of the phenotype Y or phenotypes #' \eqn{Y_1}{Y1}, \eqn{Y_2}{Y2} and of the covariates \eqn{X_1}{X1}, \eqn{X_2}{X2}. #' #' @examples #' #' # Generate genetic data: #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) #' compute_MAF(genodata) #' #' # Generate different phenotype data: #' phenodata1 <- generate_phenodata_1_simple(genodata = genodata[,1], #' type = "quantitative", b = 0) #' phenodata2 <- generate_phenodata_1_simple(genodata = genodata[,1], #' type = "quantitative", b = 2) #' phenodata3 <- generate_phenodata_1_simple(genodata = genodata, #' type = "quantitative", b = 2) #' phenodata4 <- generate_phenodata_1_simple(genodata = genodata, #' type = "quantitative", #' b = seq(0.1, 2, 0.1)) #' phenodata5 <- generate_phenodata_1_simple(genodata = genodata[,1], #' type = "binary", b = 0) #' phenodata6 <- generate_phenodata_1(genodata = genodata[,1], #' type = "quantitative", b = 0, #' MAF_cutoff = 1, prop_causal = 0.1, #' direction = "a") #' phenodata7 <- generate_phenodata_1(genodata = genodata, #' type = "quantitative", b = 0.6, #' MAF_cutoff = 0.1, prop_causal = 0.05, #' direction = "a") #' phenodata8 <- generate_phenodata_1(genodata = genodata, #' type = "quantitative", #' b = seq(0.1, 2, 0.1), #' MAF_cutoff = 0.1, prop_causal = 0.05, #' direction = "a") #' phenodata9 <- generate_phenodata_2_bvn(genodata = genodata[,1], #' tau = 0.5, b1 = 0, b2 = 0) #' phenodata10 <- generate_phenodata_2_bvn(genodata = genodata, #' tau = 0.5, b1 = 0, b2 = 0) #' phenodata11 <- generate_phenodata_2_bvn(genodata = genodata, #' tau = 0.5, b1 = 1, #' b2 = seq(0.1,2,0.1)) #' phenodata12 <- generate_phenodata_2_bvn(genodata = genodata, #' tau = 0.5, b1 = 1, b2 = 2) #' par(mfrow = c(3, 1)) #' hist(phenodata12$Y1) #' hist(phenodata12$Y2) #' plot(phenodata12$Y1, phenodata12$Y2) #' #' phenodata13 <- generate_phenodata_2_copula(genodata = genodata[,1], #' MAF_cutoff = 1, prop_causal = 1, #' tau = 0.5, b1 = 0, b2 = 0) #' phenodata14 <- generate_phenodata_2_copula(genodata = genodata, #' MAF_cutoff = 1, prop_causal = 0.5, #' tau = 0.5, b1 = 0, b2 = 0) #' phenodata15 <- generate_phenodata_2_copula(genodata = genodata, #' MAF_cutoff = 1, prop_causal = 0.5, #' tau = 0.5, b1 = 0, b2 = 0) #' phenodata16 <- generate_phenodata_2_copula(genodata = genodata, #' MAF_cutoff = 1, prop_causal = 0.5, #' tau = 0.2, b1 = 0.3, #' b2 = seq(0.1, 2, 0.1)) #' phenodata17 <- generate_phenodata_2_copula(genodata = genodata, #' MAF_cutoff = 1, prop_causal = 0.5, #' tau = 0.2, b1 = 0.3, b2 = 0.3) #' par(mfrow = c(3, 1)) #' hist(phenodata17$Y1) #' hist(phenodata17$Y2) #' plot(phenodata17$Y1, phenodata17$Y2) #' #' #' #' #' #' #' @name generate_phenodata NULL #' @rdname generate_phenodata #' @export generate_phenodata_1_simple <- function(genodata = NULL, type = "quantitative", b = 0, a = c(0, 0.5, 0.5)) { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + genodata %*% b + stats::rnorm(n_ind, 0, 1) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * X1 + a[3] * X2 + b * genodata))) Y <- stats::rbinom(n_ind, 1, P) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } #' @rdname generate_phenodata #' @export generate_phenodata_1 <- function(genodata = NULL, type = "quantitative", b = 0.6, a = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied") } genodata <- as.data.frame(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.data.frame(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b <- b[causal_idx] alpha_g <- b * abs(log10(compute_MAF(geno_causal))) # if direction b or c is specified, change direction of effect for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in%help_idx_2)) + 1) * alpha_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g } epsilon1 <- stats::rnorm(n_ind, mean = 0, sd = sigma1) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y <- as.numeric(Y) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * scale(X1, center = T, scale = F) + a[3] * scale(X2, center = T, scale = F) + geno_causal %*% alpha_g))) Y <- stats::rbinom(n_ind, 1, P) Y <- as.numeric(Y) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } #' @rdname generate_phenodata #' @export generate_phenodata_2_bvn <- function(genodata = NULL, tau = NULL, b1 = 0, b2 = 0, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5)) { if (!requireNamespace("MASS", quietly = TRUE)) { stop("MASS package needed for this function to work. Please install it.", call. = FALSE) } if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } # generate the two covariates X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) # set the weight of the nongenetic covariates set the residual variances sigma1 <- 1 sigma2 <- 1 if (is.null(tau)) { stop("Tau has to be provided.") } rho <- sin(tau * pi/2) mu <- c(0, 0) sigma <- matrix(c(sigma1, rho, rho, sigma2), 2, 2) epsilon <- MASS::mvrnorm(n = n_ind, mu = mu, Sigma = sigma) epsilon1 <- epsilon[, 1] epsilon2 <- epsilon[, 2] Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + genodata %*% b1 + epsilon1 Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + genodata %*% b2 + epsilon2 phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) return(phenodata) } #' @rdname generate_phenodata #' @export generate_phenodata_2_copula <- function(genodata = NULL, phi = NULL, tau = 0.5, b1 = 0.6, b2 = 0.6, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 sigma2 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b1 <- b1[causal_idx] b2 <- b2[causal_idx] alpha_g <- b1 * abs(log10(compute_MAF(geno_causal))) beta_g <- b2 * abs(log10(compute_MAF(geno_causal))) # if b or c is specified, change effect direction for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * beta_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * beta_g } # compute copula parameter between the two phenotypes from tau if tau is given if (!is.null(tau)) { phi <- (2 * tau)/(1 - tau) } res_copula <- generate_clayton_copula(n = n_ind, phi = phi) epsilon1 <- res_copula$Y1 epsilon2 <- res_copula$Y2 if (is.null(tau)) { tau <- phi/(phi + 2) } Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y1 <- as.numeric(Y1) Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + geno_causal %*% beta_g + epsilon2 Y2 <- as.numeric(Y2) phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/generate_phenodata.R
#' Naive estimates of the copula and marginal parameters. #' #' Function to compute naive estimates of the copula parameter(s) #' and maximum likelihood (ML) estimates of the marginal parameters in a joint #' copula model of \code{Y1} and \code{Y2} given the predictors of \code{Y1} #' and \code{Y2}. The main use of the function is to provide parameter #' starting values for the optimization of the log-likelihood function of the #' joint copula model in \code{\link{cjamp}} in order to obtain maximum #' likelihood estimates in the copula model. #' #' The estimates of the copula parameter(s) include estimates of \eqn{\phi} #' (if \code{copula_param == "phi"}), \eqn{\theta} (if #' \code{copula_param == "theta"}) or both (if \code{copula_param == "both"}). #' They are obtained by computing Kendall's tau between \code{Y1} and \code{Y2} #' and using the relationship \eqn{\tau = \phi/(\phi+2)} of the Clayton #' copula to obtain an estimate of \eqn{\phi} and \eqn{\tau = (\theta-1)/\theta} #' of the Gumbel copula to obtain an estimate of \eqn{\theta}. #' #' The ML estimates of the marginal parameters include estimates of the log standard #' deviations of \code{Y1}, \code{Y2} given their predictors (\eqn{log(\sigma1), log(\sigma2)}) #' and of the effects of \code{predictors_Y1} on \code{Y1} and #' \code{predictors_Y2} on \code{Y2}. The estimates of the marginal effects are #' obtained from linear regression models of \code{Y1} given \code{predictors_Y1} #' and \code{Y2} given \code{predictors_Y2}, respectively. If single nucleotide #' variants (SNVs) are included as predictors, the genetic effect estimates #' are obtained from an underlying additive genetic model if SNVs are provided #' as 0-1-2 genotypes and from an underlying dominant model if SNVs are provided #' as 0-1 genotypes. #' #' @param Y1 Numeric vector containing the first phenotype. #' @param Y2 Numeric vector containing the second phenotype. #' @param predictors_Y1 Dataframe containing the predictors of \code{Y1} #' in columns. #' @param predictors_Y2 Dataframe containing the predictors of \code{Y2} #' in columns. #' @param copula_param String indicating whether estimates should be computed #' for \eqn{\phi} (\code{"phi"}), for \eqn{\theta} #' (\code{"theta"}), or both (\code{"both"}). #' @return Vector of the numeric estimates of the copula parameters #' \eqn{log(\phi)} and/or \eqn{log(\theta-1)}, of the marginal #' parameters (\eqn{log(\sigma1), log(\sigma2)}, and estimates #' of the effects of the predictors \code{predictors_Y1} #' on \code{Y1} and \code{predictors_Y2} on \code{Y2}). #' #' @examples #' # Generate genetic data: #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) #' #' # Generate phenotype data: #' phenodata <- generate_phenodata_2_copula(genodata = genodata, MAF_cutoff = 1, #' prop_causal = 0.5, tau = 0.2, #' b1 = 0.3, b2 = 0.3) #' predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' SNV = genodata$SNV1) #' #' get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, predictors_Y2 = predictors, #' copula_param = "both") #' #' @export #' get_estimates_naive <- function(Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, copula_param = "both") { if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } dataframe_Y1 <- data.frame(Y1 = Y1) dataframe_Y2 <- data.frame(Y2 = Y2) n_ind <- dim(dataframe_Y1)[1] if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y1)) { predictors_Y1 <- data.frame(predictors_Y1) } if (!is.null(predictors_Y2)) { predictors_Y2 <- data.frame(predictors_Y2) } if (!n_ind == dim(dataframe_Y2)[1]) { stop("Variables must have same length.") } if (!is.null(predictors_Y1)) { if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y2)) { if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y1)) { dataframe_Y1 <- cbind(dataframe_Y1, predictors_Y1) } if (!is.null(predictors_Y2)) { dataframe_Y2 <- cbind(dataframe_Y2, predictors_Y2) } res_Y1 <- stats::lm(Y1 ~ ., data = dataframe_Y1) res_Y2 <- stats::lm(Y2 ~ ., data = dataframe_Y2) param_Y1_sigma <- log(stats::sd(res_Y1$residuals, na.rm = T)) names(param_Y1_sigma) <- "Y1_log_sigma" param_Y2_sigma <- log(stats::sd(res_Y2$residuals, na.rm = T)) names(param_Y2_sigma) <- "Y2_log_sigma" tau <- stats::cor(Y1, Y2, use = "complete.obs", method = c("kendall")) if (tau == 0) { tau <- 1e-04 } # to avoid technical breakdown of function log_phi <- log(2 * tau/(1 - tau)) log_theta <- log((1/(1 - tau)) - 1) param_Y1_Y2 <- c(log_phi, log_theta) names(param_Y1_Y2) <- c("log_phi", "log_theta_minus1") if (copula_param == "phi") { param_Y1_Y2 <- param_Y1_Y2[1] } if (copula_param == "theta") { param_Y1_Y2 <- param_Y1_Y2[2] } param_Y1_predictors <- res_Y1$coefficients names(param_Y1_predictors) <- paste("Y1_", names(param_Y1_predictors), sep = "") param_Y2_predictors <- res_Y2$coefficients names(param_Y2_predictors) <- paste("Y2_", names(param_Y2_predictors), sep = "") if (any(is.na(param_Y1_Y2))) { warning("One or both dependence parameters could not be estimated.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { warning("One or both marginal variances could not be estimated.") } if (any(is.na(param_Y1_predictors)) | any(is.na(param_Y2_predictors))) { warning("One or more marginal parameters could not be estimated.") } estimates <- c(param_Y1_Y2, param_Y1_sigma, param_Y2_sigma, param_Y1_predictors, param_Y2_predictors) return(estimates) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/get_estimates_naive.R
#' Minus log-likelihood of copula models. #' #' Function to compute the minus log-likelihood of the joint distribution #' of \code{Y1} and \code{Y2} given the predictors \code{predictors_Y1} #' of \code{Y1} and \code{predictors_Y2} of \code{Y2} in a copula model #' for given parameter values \code{parameters}. Implemented are the #' Clayton and 2-parameter copula. The function assumes quantitative #' predictors and uses an additive model, i.e. for categorical predictors #' with more than 2 levels, dummy variables have to be created beforehand. #' Accordingly, if single nucleotide variants (SNVs) are included as #' predictors, the computation is based on an additive genetic model if #' SNVs are provided as 0-1-2 genotypes and on a dominant model if SNVs #' are provided as 0-1 genotypes. #' #' The number of predictors is not fixed and also different predictors #' can be supplied for \code{Y1} and \code{Y2}. However, for the functioning #' of the log-likelihood function, the \code{parameters} vector has to be #' supplied in a pre-specified form and formatting: #' #' The vector has to include the copula parameter(s), marginal parameters #' for \code{Y1}, and marginal parameters for \code{Y2} in this order. #' For example, for the 2-parameter copula with parameters \eqn{\phi, \theta} #' and marginal models #' #' \deqn{Y_1 = \alpha_0 + \alpha_1 \cdot X_1 + \alpha_2 \cdot X_2 + \epsilon_1, \ \epsilon_1 \sim N(0,\sigma_1^2),}{Y1 = \alpha0 + \alpha1*X1 + \alpha2*X2 + \epsilon1, \epsilon1 ~ N(0,\sigma1^2),} #' \deqn{Y_1 = \beta_0 + \beta_1 \cdot X_1 + \epsilon_2, \ \epsilon_2 \sim N(0,\sigma_2^2),}{Y1 = \beta0 + \beta1*X1 + \epsilon2, \epsilon2 ~ N(0,\sigma2^2),} #' #' the parameter vector has be #' \deqn{(log(\phi), log(\theta-1), log(\sigma_1), log(\sigma_2), \alpha_0, \alpha_2, \alpha_1, \beta_0, \beta_1)^T.}{(log(\phi), log(\theta-1), log(\sigma1), log(\sigma2), \alpha0, \alpha2, \alpha1, \beta0, \beta1).} #' \eqn{log(\phi)} and \eqn{log(\theta-1)} have to be provided instead of #' \eqn{\phi, \theta} and \eqn{log(\sigma_1)}{log(\sigma1)}, \eqn{log(\sigma_2)}{log(\sigma2)} instead of #' \eqn{\sigma_1}{\sigma1}, \eqn{\sigma_2}{\sigma2} for computational reasons when the log-likelihood #' function is optimized in \code{\link{cjamp}}. As further necessary format, #' the vector has to be named and the names of the copula parameter(s) has/have #' to be \code{log_phi} and/or \code{log_theta_minus1}. #' #' @param copula String indicating whether the likelihood should be computed #' under the Clayton (\code{"Clayton"}) or 2-parameter copula #' (\code{"2param"}) model. #' @param Y1 Numeric vector containing the first phenotype. #' @param Y2 Numeric vector containing the second phenotype. #' @param predictors_Y1 Dataframe containing the predictors of \code{Y1} #' in columns. #' @param predictors_Y2 Dataframe containing predictors of \code{Y2} #' in columns. #' @param parameters Named integer vector containing the parameter estimates #' of the marginal and copula parameters, for which the #' log-likelihood will be computed. For details and the #' necessary format of the vector, see the details below. #' @return Minus log-likelihood value (integer). #' #' @examples #' # Generate genetic data: #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) #' #' # Generate phenotype data: #' phenodata <- generate_phenodata_2_copula(genodata = genodata, MAF_cutoff = 1, #' prop_causal = 0.5, tau = 0.2, #' b1 = 0.3, b2 = 0.3) #' #' # Example 1: Log-likelihood of null model without covariates & genetic effects #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = NULL, predictors_Y2 = NULL, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = NULL, #' predictors_Y2 = NULL, parameters = estimates, copula = "2param") #' #' # Example 2: Log-likelihood of null model with covariates, without genetic effects #' predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, #' predictors_Y2 = predictors, parameters = estimates, copula = "2param") #' #' # Example 3: Log-likelihood of model with covariates & genetic effect on Y1 only #' predictors_Y1 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' SNV = genodata$SNV1) #' predictors_Y2 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors_Y1, #' predictors_Y2 = predictors_Y2, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_Y1, #' predictors_Y2 = predictors_Y2, parameters = estimates, #' copula = "2param") #' #' # Example 4: Log-likelihood of model with covariates & genetic effect on Y2 only #' predictors_Y1 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) #' predictors_Y2 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' SNV = genodata$SNV1) #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors_Y1, #' predictors_Y2 = predictors_Y2, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_Y1, #' predictors_Y2 = predictors_Y2, parameters = estimates, #' copula = "2param") #' #' # Example 5: Log-likelihood of model without covariates, with genetic effects #' predictors <- data.frame(SNV = genodata$SNV1) #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, #' predictors_Y2 = predictors, parameters = estimates, copula = "2param") #' #' # Example 6: Log-likelihood of model with covariates & genetic effects #' predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, #' predictors_Y2 = predictors, parameters = estimates, copula = "2param") #' #' # Example 7: Log-likelihood of model with covariates & multiple genetic effects #' predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:5]) #' estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' copula_param = "both") #' minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, #' predictors_Y2 = predictors, parameters = estimates, copula = "2param") #' #' @export #' minusloglik <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, parameters = NULL) { if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (!is.null(predictors_Y1)) { n_Y1_pred <- dim(predictors_Y1)[2] } else { n_Y1_pred <- 0 } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (copula == "Clayton") { param_Y1_Y2 <- parameters[1] n_dep <- 1 if (!names(param_Y1_Y2) == "log_phi") { stop("Estimate for phi is not provided.") } } if (copula == "2param") { param_Y1_Y2 <- parameters[1:2] n_dep <- 2 if (!identical(names(param_Y1_Y2), c("log_phi", "log_theta_minus1"))) { stop("Estimates for phi/theta are not provided.") } } param_Y1_sigma <- parameters[n_dep + 1] param_Y2_sigma <- parameters[n_dep + 2] no_p <- length(parameters) param_Y1_predictors <- parameters[(n_dep + 3):(n_dep + 3 + n_Y1_pred)] param_Y2_predictors <- parameters[(no_p - n_Y2_pred):no_p] if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } n_ind <- length(Y1) if (!is.null(predictors_Y1)) { predictors_Y1 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y1) } else { predictors_Y1 <- data.frame(One = rep(1, n_ind)) } if (!is.null(predictors_Y2)) { predictors_Y2 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y2) } else { predictors_Y2 <- data.frame(One = rep(1, n_ind)) } if (!n_ind == length(Y2)) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } if (is.null(param_Y1_Y2) | any(is.na(param_Y1_Y2))) { stop("Estimate(s) of dependence betwee Y1 and Y2 is (are) not provided.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { stop("One or both marginal variances are not provided") } if (any(is.na(param_Y1_predictors))) { warning(paste("Effect estimate of ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " on Y1 is missing. Variable ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y1 <- predictors_Y1[, !is.na(param_Y1_predictors)] param_Y1_predictors <- param_Y1_predictors[!is.na(param_Y1_predictors)] } if (any(is.na(param_Y2_predictors))) { warning(paste("Effect estimates of ", names(predictors_Y2)[which(is.na(param_Y2_predictors))], " on Y2 is missing. Variable ", names(predictors_Y2)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y2 <- predictors_Y2[, !is.na(param_Y2_predictors)] param_Y2_predictors <- param_Y2_predictors[!is.na(param_Y2_predictors)] } if (copula == "Clayton") { phi <- exp(param_Y1_Y2[1]) } else if (copula == "2param") { phi <- exp(param_Y1_Y2[1]) theta <- exp(param_Y1_Y2[2]) + 1 } else { stop("copula has to be specified") } minusloglik <- 0 predictors_Y1 <- as.matrix(predictors_Y1) predictors_Y2 <- as.matrix(predictors_Y2) for (i in 1:n_ind) { lik.pt1.1 <- stats::pnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt1.2 <- stats::pnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) lik.pt2 <- stats::dnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt3 <- stats::dnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) if (copula == "Clayton") { fun <- ((lik.pt1.1)^(-phi) - 1) + ((lik.pt1.2)^(-phi) - 1) joints <- (fun + 1)^(-1/phi) d1.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1) * (fun + 1)^(1/phi + 1) lik <- dd.joints * (fun * (1 + phi) * (fun + 1)^(-1)) } if (copula == "2param") { fun <- ((lik.pt1.1)^(-phi) - 1)^theta + ((lik.pt1.2)^(-phi) - 1)^theta joints <- (fun^(1/theta) + 1)^(-1/phi) d1.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.1)^(-phi) - 1)^(theta - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.2)^(-phi) - 1)^(theta - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1/theta) * (fun^(1/theta) + 1)^(1/phi + 1) lik <- dd.joints * ((theta - 1) * phi + fun^(1/theta) * (1 + phi) * (fun^(1/theta) + 1)^(-1)) } minusloglik <- minusloglik - log(lik) } return(as.numeric(minusloglik)) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/loglik_functions.R
#' Compute likelihood ratio tests. #' #' Functions to compute likelihood ratio tests of two nested copula models #' with the same marginal models, and of marginal parameters in the same copula #' model but with different nested marginal models where one or more parameters #' are set to 0 (Yilmaz & Lawless, 2011). #' #' References: #' #' Yilmaz YE, Lawless JF (2011). Likelihood ratio procedures and tests of fit in parametric and semiparametric copula models with censored data. Lifetime Data Analysis, 17(3): 386-408. #' #' @param minlogl_null Minus log-likelihood of the null model, which is nested #' within the larger alternative model \code{minlogl_altern}. #' @param minlogl_altern Minus log-likelihood of the alternative model, which #' contains the null model \code{minlogl_null}. #' @param df Degrees of freedom in the likelihood ratio test of marginal #' parameters in the same copula model, i.e. the number of #' parameters that are in the alternative model but that are not #' contained in the smaller nested null model. #' @return List including the \eqn{\chi^2} value and p-value of the likelihood #' ratio test. #' #' @examples #' #' # Example 1: Test whether 2-parameter copula model has a better #' # model fit compared to Clayton copula (no). #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 100) #' phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, #' MAF_cutoff = 1, prop_causal = 1, #' tau = 0.2, b1 = 0.3, b2 = 0.3) #' predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' SNV = genodata$SNV1) #' estimates_c <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' copula_param = "phi") #' minusloglik_Clayton <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' parameters = estimates_c, copula = "Clayton") #' estimates_2p <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' copula_param = "both") #' minusloglik_2param <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors, #' predictors_Y2 = predictors, #' parameters = estimates_2p, copula = "2param") #' lrt_copula(minusloglik_Clayton, minusloglik_2param) #' #' # Example 2: Test marginal parameters (alternative model has better fit). #' set.seed(10) #' genodata <- generate_genodata(n_SNV = 20, n_ind = 100) #' phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, #' MAF_cutoff = 1, prop_causal = 1, #' tau = 0.2, b1 = 2, b2 = 2) #' predictors_1 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) #' estimates_1 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors_1, #' predictors_Y2 = predictors_1, #' copula_param = "phi") #' minusloglik_1 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors_1, #' predictors_Y2 = predictors_1, #' parameters = estimates_1, copula = "Clayton") #' predictors_2 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' SNV = genodata$SNV1) #' estimates_2 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors_2, #' predictors_Y2 = predictors_2, #' copula_param = "phi") #' minusloglik_2 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' predictors_Y1 = predictors_2, #' predictors_Y2 = predictors_2, #' parameters = estimates_2, copula = "Clayton") #' lrt_param(minusloglik_1, minusloglik_2, df=2) #' #' @name lrt NULL #' @rdname lrt #' @export lrt_copula <- function(minlogl_null = NULL, minlogl_altern = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern)) { stop("minlogl_null and minlogl_altern have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - (0.5 + 0.5 * stats::pchisq(chisq, df = 1)) return(list(chisq = chisq, pval = pval)) } #' @rdname lrt #' @export lrt_param <- function(minlogl_null = NULL, minlogl_altern = NULL, df = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern) | is.null(df)) { stop("minlogl_null, minlogl_altern and df have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - stats::pchisq(chisq, df = df) return(list(chisq = chisq, pval = pval)) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/lrt.R
#' Summary function. #' #' Summary function for the \code{\link{cjamp}} and \code{\link{cjamp_loop}} #' functions. #' #' @param object \code{cjamp} object (output of the \code{\link{cjamp}} #' or \code{\link{cjamp_loop}} function). #' @param ... Additional arguments affecting the summary produced. #' #' @return Formatted data frame of the results. #' #' @examples #' ## Not run. When executing, the following takes about 2 minutes running time. #' ## Summary of regular cjamp function #' #set.seed(10) #' #genodata <- generate_genodata(n_SNV = 20, n_ind = 100) #' #phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, #' # MAF_cutoff = 1, prop_causal = 1, #' # tau = 0.2, b1 = 0.3, b2 = 0.3) #' #predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, #' # genodata[, 1:3]) #' #results <- cjamp(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' # predictors_Y1 = predictors, predictors_Y2 = predictors, #' # copula = "2param", optim_method = "BFGS", trace = 0, #' # kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, #' # n_iter_max = 10) #' #summary(results) #' # #' ## Summary of looped cjamp function #' #covariates <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) #' #predictors <- genodata #' #results <- cjamp_loop(Y1 = phenodata$Y1, Y2 = phenodata$Y2, #' # covariates_Y1 = covariates, #' # covariates_Y2 = covariates, #' # predictors = predictors, copula = "Clayton", #' # optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, #' # SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) #' #summary(results) #' #' @export #' summary.cjamp <- function(object = NULL, ...) { if (is.null(object) | !class(object) == "cjamp") { stop("cjamp object has to be supplied.") } # for input from cjamp function: if ("Parameter point estimates" %in% names(object)) { length_res <- length(object$"Parameter p-values") res_out <- data.frame(point_estimates = object$"Parameter point estimates"[3:(length_res+2)], SE_estimates = object$"Parameter standard error estimates"[3:(length_res+2)], pvalues = object$"Parameter p-values") print(paste("C-JAMP estimates of marginal parameters.")) print(res_out) } # for input from cjamp_loop function: if ("Parameter p-values for effects of predictors on Y1" %in% names(object)) { res_out_1 <- data.frame(point_estimates = object$"Parameter point estimates for effects of predictors on Y1", SE_estimates = object$"Parameter standard error estimates for effects on Y1", pvalues = object$"Parameter p-values for effects of predictors on Y1") rownames(res_out_1) <- paste("Y1", rownames(res_out_1), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y1.")) print(res_out_1) res_out_2 <- data.frame(point_estimates = object$"Parameter point estimates for effects of predictors on Y2", SE_estimates = object$"Parameter standard error estimates for effects on Y2", pvalues = object$"Parameter p-values for effects of predictors on Y2") rownames(res_out_2) <- paste("Y2", rownames(res_out_2), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y2.")) print(res_out_2) res_out <- data.frame(rbind(res_out_1, res_out_2)) } invisible(res_out) }
/scratch/gouwar.j/cran-all/cranData/CJAMP/R/summary_function.R
## ---- echo=FALSE--------------------------------------------------------- generate_clayton_copula <- function(n = NULL, phi = NULL) { U1 <- runif(n, min = 0, max = 1) U2 <- runif(n, min = 0, max = 1) Y1 <- qnorm(U1, mean = 0, sd = 1) Y2.help <- (1 - U1^(-phi) * (1 - U2^(-phi/(1 + phi))))^(-1/phi) tau <- phi/(phi + 2) Y2 <- qnorm(Y2.help, mean = 0, sd = 1) phenodata <- data.frame(Y1 = Y1, Y2 = Y2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) } ## ------------------------------------------------------------------------ # Generate phenotype data from the Clayton copula: set.seed(10) dat1a <- generate_clayton_copula(n = 1000, phi = 0.5) dat1b <- generate_clayton_copula(n = 1000, phi = 2) dat1c <- generate_clayton_copula(n = 1000, phi = 8) par(mfrow = c(1, 3)) plot(dat1a$Y1, dat1a$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.2"))) plot(dat1b$Y1, dat1b$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.5"))) plot(dat1c$Y1, dat1c$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.8"))) ## ---- echo=FALSE--------------------------------------------------------- generate_singleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, rep(0, n_ind - 1)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ## ---- echo=FALSE--------------------------------------------------------- generate_doubleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, 1, rep(0, n_ind - 2)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ## ---- echo=FALSE--------------------------------------------------------- generate_genodata <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) for (i in 1:n_SNV) { MAFhelp <- round(runif(1, 0, 0.5), 3) n0 <- round((1 - MAFhelp)^2 * n_ind) n2 <- round(MAFhelp^2 * n_ind) n1 <- n_ind - n0 - n2 helpvec <- c(rep(0, n0), rep(1, n1), rep(2, n2)) genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ## ---- echo=FALSE--------------------------------------------------------- compute_MAF <- function(genodata) { MAF <- NULL if (is.null(dim(genodata))) { dat <- genodata[!is.na(genodata)] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF > 0.5) { warning("MAF is larger than 0.5, maybe recode alleles?") } } if (!is.null(dim(genodata))) { for (i in 1:dim(genodata)[2]) { dat <- genodata[, i][!is.na(genodata[, i])] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF[i] <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF[i] > 0.5) { warning(paste("MAF of SNV ",i ," is larger than 0.5, maybe recode alleles?",sep="")) } } } names(MAF) <- names(genodata) return(MAF) } ## ---- echo=FALSE--------------------------------------------------------- generate_phenodata_1_simple <- function(genodata = NULL, type = "quantitative", b = 0, a = c(0, 0.5, 0.5)) { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- rnorm(n_ind, mean = 0, sd = 1) X2 <- rbinom(n_ind, size = 1, prob = 0.5) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + genodata %*% b + rnorm(n_ind, 0, 1) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * X1 + a[3] * X2 + b * genodata))) Y <- rbinom(n_ind, 1, P) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } ## ---- echo=FALSE--------------------------------------------------------- generate_phenodata_1 <- function(genodata = NULL, type = "quantitative", b = 0.6, a = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied") } genodata <- as.data.frame(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.data.frame(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b <- b[causal_idx] alpha_g <- b * abs(log10(compute_MAF(geno_causal))) # if direction b or c is specified, change direction of effect for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in%help_idx_2)) + 1) * alpha_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g } epsilon1 <- stats::rnorm(n_ind, mean = 0, sd = sigma1) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y <- as.numeric(Y) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * scale(X1, center = T, scale = F) + a[3] * scale(X2, center = T, scale = F) + geno_causal %*% alpha_g))) Y <- stats::rbinom(n_ind, 1, P) Y <- as.numeric(Y) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } ## ---- echo=FALSE--------------------------------------------------------- generate_phenodata_2_bvn <- function(genodata = NULL, tau = NULL, b1 = 0, b2 = 0, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5)) { if (!requireNamespace("MASS", quietly = TRUE)) { stop("MASS package needed for this function to work. Please install it.", call. = FALSE) } if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } # generate the two covariates X1 <- rnorm(n_ind, mean = 0, sd = 1) X2 <- rbinom(n_ind, size = 1, prob = 0.5) # set the weight of the nongenetic covariates set the residual variances sigma1 <- 1 sigma2 <- 1 if (is.null(tau)) { stop("Tau has to be provided.") } rho <- sin(tau * pi/2) mu <- c(0, 0) sigma <- matrix(c(sigma1, rho, rho, sigma2), 2, 2) epsilon <- MASS::mvrnorm(n = n_ind, mu = mu, Sigma = sigma) epsilon1 <- epsilon[, 1] epsilon2 <- epsilon[, 2] Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + genodata %*% b1 + epsilon1 Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + genodata %*% b2 + epsilon2 phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) return(phenodata) } ## ---- echo=FALSE--------------------------------------------------------- generate_phenodata_2_copula <- function(genodata = NULL, phi = NULL, tau = 0.5, b1 = 0.6, b2 = 0.6, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 sigma2 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b1 <- b1[causal_idx] b2 <- b2[causal_idx] alpha_g <- b1 * abs(log10(compute_MAF(geno_causal))) beta_g <- b2 * abs(log10(compute_MAF(geno_causal))) # if b or c is specified, change effect direction for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * beta_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * beta_g } # compute copula parameter between the two phenotypes from tau if tau is given if (!is.null(tau)) { phi <- (2 * tau)/(1 - tau) } res_copula <- generate_clayton_copula(n = n_ind, phi = phi) epsilon1 <- res_copula$Y1 epsilon2 <- res_copula$Y2 if (is.null(tau)) { tau <- phi/(phi + 2) } Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y1 <- as.numeric(Y1) Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + geno_causal %*% beta_g + epsilon2 Y2 <- as.numeric(Y2) phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) } ## ------------------------------------------------------------------------ # Generate genetic data: set.seed(10) genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) compute_MAF(genodata) # Generate phenotype data from the bivariate normal distribution given covariates: phenodata_bvn <- generate_phenodata_2_bvn(genodata = genodata, tau = 0.5, b1 = 1, b2 = 2) plot(phenodata_bvn$Y1, phenodata_bvn$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of bivariate normal ", Y[1], ", ", Y[2], " with ", tau, "=0.5"))) # Generate phenotype data from the Clayton copula given covariates: phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, MAF_cutoff = 1, prop_causal = 1, tau = 0.5, b1 = 0.3, b2 = 0.3) plot(phenodata$Y1, phenodata$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " from the Clayton copula with ", tau, "=0.5"))) ## ---- echo=FALSE--------------------------------------------------------- compute_expl_var <- function(genodata = NULL, phenodata = NULL, type = "Rsquared_unadj", causal_idx = NULL, effect_causal = NULL) { ExplVar <- NULL if (is.null(phenodata) | is.null(genodata)) { stop("Genodata and phenodata have to be supplied.") } if (!dim(genodata)[1] == length(phenodata)) { stop("Number of observations in genodata and phenodata has to be the same.") } if (class(genodata) == "data.frame") { if (!all(sapply(genodata, is.numeric))) { genodata <- as.data.frame(data.matrix(genodata)) } } if (is.null(dim(genodata))) { if (!is.numeric(genodata)) { stop("genodata has to be numeric.") } } if (class(phenodata) == "data.frame") { if (!all(sapply(phenodata, is.numeric))) { phenodata <- as.data.frame(data.matrix(phenodata)) warning("phenodata contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(dim(phenodata))) { if (!is.numeric(phenodata)) { stop("phenodata has to be numeric.") } } if (is.null(causal_idx)) { warning("A vector indicating the causal SNVs is not supplied \n so the estimate of explained variance is based on all SNVs.") } if (any(type %in% c("MAF_based", "MAF_based_Y_adjusted")) & is.null(effect_causal)) { stop("A vector indicating the genetic effect sizes of the causal SNVs has \n to be supplied for the MAF_based and MAF_based_Y_adjusted approach.") } if (!is.null(causal_idx)) { genodata <- as.data.frame(genodata[, causal_idx]) } MAF_causal <- compute_MAF(genodata) phenodata <- as.data.frame(phenodata) dat <- as.data.frame(append(phenodata, genodata)) dat <- dat[complete.cases(dat),] names(dat)[1] <- "Y" ExplVar <- list() if ("Rsquared_unadj" %in% type) { ExplVar$Rsquared_unadj <- summary(lm(Y ~ ., data = dat))$r.squared } if ("Rsquared_adj" %in% type) { ExplVar$Rsquared_adj <- summary(lm(Y ~ ., data = dat))$adj.r.squared } if ("MAF_based" %in% type) { ExplVar$MAF_based <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2) } if ("MAF_based_Y_adjusted" %in% type) { ExplVar$MAF_based_Y_adjusted <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2)/var(dat$Y) } return(ExplVar) } ## ------------------------------------------------------------------------ compute_expl_var(genodata = genodata, phenodata = phenodata$Y1, type = c("Rsquared_unadj", "Rsquared_adj", "MAF_based", "MAF_based_Y_adjusted"), causal_idx = rep(TRUE,20), effect_causal = c(0.3 * abs(log10(compute_MAF(genodata$SNV1))), rep(0,19))) ## ---- echo=FALSE--------------------------------------------------------- get_estimates_naive <- function(Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, copula_param = "both") { if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } dataframe_Y1 <- data.frame(Y1 = Y1) dataframe_Y2 <- data.frame(Y2 = Y2) n_ind <- dim(dataframe_Y1)[1] if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y1)) { predictors_Y1 <- data.frame(predictors_Y1) } if (!is.null(predictors_Y2)) { predictors_Y2 <- data.frame(predictors_Y2) } if (!n_ind == dim(dataframe_Y2)[1]) { stop("Variables must have same length.") } if (!is.null(predictors_Y1)) { if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y2)) { if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y1)) { dataframe_Y1 <- cbind(dataframe_Y1, predictors_Y1) } if (!is.null(predictors_Y2)) { dataframe_Y2 <- cbind(dataframe_Y2, predictors_Y2) } res_Y1 <- lm(Y1 ~ ., data = dataframe_Y1) res_Y2 <- lm(Y2 ~ ., data = dataframe_Y2) param_Y1_sigma <- log(sd(res_Y1$residuals, na.rm = T)) #param_Y1_sigma <- log(sd(Y1, na.rm = T)) names(param_Y1_sigma) <- "Y1_log_sigma" param_Y2_sigma <- log(sd(res_Y2$residuals, na.rm = T)) #param_Y2_sigma <- log(sd(Y2, na.rm = T)) names(param_Y2_sigma) <- "Y2_log_sigma" tau <- cor(Y1, Y2, use = "complete.obs", method = c("kendall")) if (tau == 0) { tau <- 1e-04 } # to avoid technical breakdown of function log_phi <- log(2 * tau/(1 - tau)) log_theta <- log((1/(1 - tau)) - 1) param_Y1_Y2 <- c(log_phi, log_theta) names(param_Y1_Y2) <- c("log_phi", "log_theta_minus1") if (copula_param == "phi") { param_Y1_Y2 <- param_Y1_Y2[1] } if (copula_param == "theta") { param_Y1_Y2 <- param_Y1_Y2[2] } param_Y1_predictors <- res_Y1$coefficients names(param_Y1_predictors) <- paste("Y1_", names(param_Y1_predictors), sep = "") param_Y2_predictors <- res_Y2$coefficients names(param_Y2_predictors) <- paste("Y2_", names(param_Y2_predictors), sep = "") if (any(is.na(param_Y1_Y2))) { warning("One or both dependence parameters could not be estimated.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { warning("One or both marginal variances could not be estimated.") } if (any(is.na(param_Y1_predictors)) | any(is.na(param_Y2_predictors))) { warning("One or more marginal parameters could not be estimated.") } estimates <- c(param_Y1_Y2, param_Y1_sigma, param_Y2_sigma, param_Y1_predictors, param_Y2_predictors) return(estimates) } ## ------------------------------------------------------------------------ predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") ## ---- echo=FALSE--------------------------------------------------------- minusloglik <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, parameters = NULL) { if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (!is.null(predictors_Y1)) { n_Y1_pred <- dim(predictors_Y1)[2] } else { n_Y1_pred <- 0 } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (copula == "Clayton") { param_Y1_Y2 <- parameters[1] n_dep <- 1 if (!names(param_Y1_Y2) == "log_phi") { stop("Estimate for phi is not provided.") } } if (copula == "2param") { param_Y1_Y2 <- parameters[1:2] n_dep <- 2 if (!identical(names(param_Y1_Y2), c("log_phi", "log_theta_minus1"))) { stop("Estimates for phi/theta are not provided.") } } param_Y1_sigma <- parameters[n_dep + 1] param_Y2_sigma <- parameters[n_dep + 2] no_p <- length(parameters) param_Y1_predictors <- parameters[(n_dep + 3):(n_dep + 3 + n_Y1_pred)] param_Y2_predictors <- parameters[(no_p - n_Y2_pred):no_p] if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } n_ind <- length(Y1) if (!is.null(predictors_Y1)) { predictors_Y1 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y1) } else { predictors_Y1 <- data.frame(One = rep(1, n_ind)) } if (!is.null(predictors_Y2)) { predictors_Y2 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y2) } else { predictors_Y2 <- data.frame(One = rep(1, n_ind)) } if (!n_ind == length(Y2)) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } if (is.null(param_Y1_Y2) | any(is.na(param_Y1_Y2))) { stop("Estimate(s) of dependence betwee Y1 and Y2 is (are) not provided.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { stop("One or both marginal variances are not provided") } if (any(is.na(param_Y1_predictors))) { warning(paste("Effect estimate of ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " on Y1 is missing. Variable ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y1 <- predictors_Y1[, !is.na(param_Y1_predictors)] param_Y1_predictors <- param_Y1_predictors[!is.na(param_Y1_predictors)] } if (any(is.na(param_Y2_predictors))) { warning(paste("Effect estimates of ", names(predictors_Y2)[which(is.na(param_Y2_predictors))], " on Y2 is missing. Variable ", names(predictors_Y2)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y2 <- predictors_Y2[, !is.na(param_Y2_predictors)] param_Y2_predictors <- param_Y2_predictors[!is.na(param_Y2_predictors)] } if (copula == "Clayton") { phi <- exp(param_Y1_Y2[1]) } else if (copula == "2param") { phi <- exp(param_Y1_Y2[1]) theta <- exp(param_Y1_Y2[2]) + 1 } else { stop("copula has to be specified") } minusloglik <- 0 predictors_Y1 <- as.matrix(predictors_Y1) predictors_Y2 <- as.matrix(predictors_Y2) for (i in 1:n_ind) { lik.pt1.1 <- pnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt1.2 <- pnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) lik.pt2 <- dnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt3 <- dnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) if (copula == "Clayton") { fun <- ((lik.pt1.1)^(-phi) - 1) + ((lik.pt1.2)^(-phi) - 1) joints <- (fun + 1)^(-1/phi) d1.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1) * (fun + 1)^(1/phi + 1) lik <- dd.joints * (fun * (1 + phi) * (fun + 1)^(-1)) } if (copula == "2param") { fun <- ((lik.pt1.1)^(-phi) - 1)^theta + ((lik.pt1.2)^(-phi) - 1)^theta joints <- (fun^(1/theta) + 1)^(-1/phi) d1.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.1)^(-phi) - 1)^(theta - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.2)^(-phi) - 1)^(theta - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1/theta) * (fun^(1/theta) + 1)^(1/phi + 1) lik <- dd.joints * ((theta - 1) * phi + fun^(1/theta) * (1 + phi) * (fun^(1/theta) + 1)^(-1)) } minusloglik <- minusloglik - log(lik) } return(as.numeric(minusloglik)) } ## ------------------------------------------------------------------------ predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:5]) estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates, copula = "2param") ## ---- echo=FALSE--------------------------------------------------------- lrt_copula <- function(minlogl_null = NULL, minlogl_altern = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern)) { stop("minlogl_null and minlogl_altern have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - (0.5 + 0.5 * pchisq(chisq, df = 1)) return(list(chisq = chisq, pval = pval)) } ## ------------------------------------------------------------------------ # Example: Test whether 2-parameter copula model has a better # model fit compared to Clayton copula (no). predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) estimates_c <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "phi") minusloglik_Clayton <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates_c, copula = "Clayton") estimates_2p <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") minusloglik_2param <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates_2p, copula = "2param") lrt_copula(minusloglik_Clayton, minusloglik_2param) ## ---- echo=FALSE--------------------------------------------------------- lrt_param <- function(minlogl_null = NULL, minlogl_altern = NULL, df = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern) | is.null(df)) { stop("minlogl_null, minlogl_altern and df have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - pchisq(chisq, df = df) return(list(chisq = chisq, pval = pval)) } ## ------------------------------------------------------------------------ # Example: Test marginal parameters (alternative model has better fit). predictors_1 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) estimates_1 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_1, predictors_Y2 = predictors_1, copula = "phi") minusloglik_1 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_1, predictors_Y2 = predictors_1, parameters = estimates_1, copula = "Clayton") predictors_2 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) estimates_2 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_2, predictors_Y2 = predictors_2, copula = "phi") minusloglik_2 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_2, predictors_Y2 = predictors_2, parameters = estimates_2, copula = "Clayton") lrt_param(minusloglik_1, minusloglik_2, df=2) ## ---- echo=FALSE--------------------------------------------------------- cjamp <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (pval_est & !SE_est) { stop("SE_est has to be TRUE to compute p-values.") } if (!requireNamespace("optimx", quietly = TRUE)) { stop("Package optimx needed for this function to work. Please install it.", call. = FALSE) } if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (cor(Y1, Y2, use = "complete.obs", method = "kendall") < 0) { Y2 <- -Y2 warning("Dependence between Y1, Y2 is negative but copulas require positive dependence. \n Hence Y2 is transformed to -Y2 and point estimates for Y2 are in inverse direction.") } if (copula == "Clayton") { n_dep <- 1 copula_param = "phi" } if (copula == "2param") { n_dep <- 2 copula_param = "both" } if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] n_pred <- 0 } if (!is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y1)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] } if (is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y2)[2] } if (!is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y1) & complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] + dim(predictors_Y2)[2] } if (scale_var) { predictors_Y1 <- data.frame(lapply(predictors_Y1, scale)) predictors_Y2 <- data.frame(lapply(predictors_Y2, scale)) } convcode <- 1 kkt <- c(FALSE, FALSE) n_iter <- 1 helpnum <- 0.4 while (!(convcode == 0 & all(kkt) & !any(is.na(kkt))) & (n_iter <= n_iter_max)) { startvalues <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) - helpnum names_pred <- names(startvalues[(n_dep + 3):length(startvalues)]) if (minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues) == Inf | is.na(minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues))) { helpnum <- (-1)^rbinom(1, 1, 0.5) * runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 next } res <- optimx::optimx(par = startvalues, fn = minusloglik, Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, method = optim_method, hessian = TRUE, control = list(trace = trace, kkt2tol = kkt2tol)) convcode <- res$convcode kkt <- c(res$kkt1, res$kkt2) helpnum <- (-1)^rbinom(1, 1, 0.5) * runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 } names(convcode) <- "convcode" names(kkt) <- c("KKT1", "KKT2") maxloglik <- NULL if (!convcode == 0) { warning("In model with predictors \n", names_pred, ": \n Optimization doesn't seem to be converged.", "\n SE estimates and pvalues are not computed. Please check.") } if (!all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n KKT conditions are not satistified.", " \n SE estimates and pvalues are not computed. Please check.") } if (!convcode == 0 | !all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n Naive parameter estimates are computed from separate marginal models.") point_estimates <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) point_estimates <- as.list(point_estimates) if (copula == "Clayton") { phi <- exp(point_estimates$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(point_estimates$log_phi) theta <- exp(point_estimates$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates[(n_dep + 1):length(point_estimates)], phi, theta, tau, lambda_l, lambda_u) point_estimates[[1]] <- exp(point_estimates[[1]]) point_estimates[[2]] <- exp(point_estimates[[2]]) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (convcode == 0 & all(kkt) & !any(is.na(kkt))) { maxloglik <- res$value names(maxloglik) <- "maxloglik" point_estimates <- res[(n_dep + 1):(n_dep + n_pred + 4)] point_estimates[1:2] <- exp(point_estimates[1:2]) if (copula == "Clayton") { phi <- exp(res$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(res$log_phi) theta <- exp(res$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates, phi, theta, tau, lambda_l, lambda_u) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } SE_estimates <- NULL if (SE_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { SE_estimates <- vector(mode = "numeric", length = (n_pred + 4)) SE_estimates[1] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 1] * (point_estimates$Y1_sigma^2)) SE_estimates[2] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 2] * (point_estimates$Y2_sigma^2)) SE_estimates[3:length(SE_estimates)] <- sqrt(diag(solve(attributes(res)$details[[3]]))[(n_dep + 3):(n_dep + n_pred + 4)]) if (copula == "Clayton") { helpvar1 <- 2 * phi/((phi + 2)^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) tau_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (helpvar1^2)) theta_SE <- lambda_l_SE <- lambda_u_SE <- NA } if (copula == "2param") { helpvar3.1 <- 2 * phi/(theta * (phi + 2)^2) helpvar3.2 <- 2 * (theta - 1)/(theta^2 * (phi + 2)) helpvar3.3 <- (2^(-1/(theta * phi))) * (log(2)/(theta * phi)) helpvar3.4 <- (2^(-1/(theta * phi))) * (log(2) * (theta - 1)/(theta^2 * phi)) helpvar3.5 <- (2^(1/theta)) * ((theta - 1) * log(2)/theta^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) theta_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * ((theta - 1)^2)) tau_SE <- sqrt(t(c(helpvar3.1, helpvar3.2)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.1, helpvar3.2)) lambda_l_SE <- sqrt(t(c(helpvar3.3, helpvar3.4)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.3, helpvar3.4)) lambda_u_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * helpvar3.5^2) } SE_estimates <- c(SE_estimates, phi_SE, theta_SE, tau_SE, lambda_l_SE, lambda_u_SE) names(SE_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (is.null(SE_estimates)){ SE_estimates <- rep(NA, length(point_estimates)) } pval <- NULL point_estimates <- unlist(point_estimates) if (pval_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { pval <- vector(mode = "numeric", length = (n_pred + 2)) pval <- 2 * pnorm(as.numeric(-abs(point_estimates[3:(n_pred + 4)]/ SE_estimates[3:(n_pred + 4)]))) names(pval) <- names_pred } if (is.null(pval)){ pval <- rep(NA, (n_pred + 2)) } output <- list(point_estimates = point_estimates, SE_estimates = SE_estimates, pval = pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates", "Parameter standard error estimates", "Parameter p-values", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } ## ------------------------------------------------------------------------ # Restrict example to sample size 100 to decrease running time: predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:3])[1:100,] cjamp_res <- cjamp(copula = "2param", Y1 = phenodata$Y1[1:100], Y2 = phenodata$Y2[1:100], predictors_Y1 = predictors, predictors_Y2 = predictors, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) cjamp_res ## ---- echo=FALSE--------------------------------------------------------- cjamp_loop <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors = NULL, covariates_Y1 = NULL, covariates_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (is.null(predictors)) { stop("At least one predictor has to be supplied.") } if (!class(predictors) == "data.frame") { stop("Predictors has to be a dataframe.") } if (!all(sapply(predictors, is.numeric))) { predictors <- as.data.frame(data.matrix(predictors)) warning("predictors contains non-numeric Variables, which have automatically been transformed.") } if ((!class(covariates_Y1) == "data.frame" & !is.null(covariates_Y1)) | (!class(covariates_Y2) == "data.frame" & !is.null(covariates_Y2))) { stop("covariates_Y1 and covariates_Y2 have to be a dataframe or NULL.") } if (class(covariates_Y1) == "data.frame") { if (!all(sapply(covariates_Y1, is.numeric))) { covariates_Y1 <- as.data.frame(data.matrix(covariates_Y1)) warning("covariates_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(covariates_Y2) == "data.frame") { if (!all(sapply(covariates_Y2, is.numeric))) { covariates_Y2 <- as.data.frame(data.matrix(covariates_Y2)) warning("covariates_Y2 contains non-numeric Variables, which have automatically been transformed.") } } N <- dim(predictors)[2] Y1_point_estimates <- Y1_SE_estimates <- Y1_pval <- NULL Y2_point_estimates <- Y2_SE_estimates <- Y2_pval <- NULL convcode <- kkt <- maxloglik <- NULL for (i in 1:N) { names_pred_i <- names(predictors)[i] predictors_Y1 <- predictors_Y2 <- predictors[, i, drop = FALSE] if (!is.null(covariates_Y1)) { predictors_Y1 <- cbind(predictors_Y1, as.data.frame(covariates_Y1)) } if (!is.null(covariates_Y2)) { predictors_Y2 <- cbind(predictors_Y2, as.data.frame(covariates_Y2)) } n_pred_Y1 <- dim(predictors_Y1)[2] n_pred_Y2 <- dim(predictors_Y2)[2] results <- cjamp(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, scale_var = scale_var, copula = copula, optim_method = optim_method, trace = trace, kkt2tol = kkt2tol, SE_est = SE_est, pval_est = pval_est, n_iter_max = n_iter_max) Y1_point_estimates[i] <- as.numeric(results[[1]][4]) Y2_point_estimates[i] <- as.numeric(results[[1]][5 + n_pred_Y1]) Y1_SE_estimates[i] <- results[[2]][4] Y2_SE_estimates[i] <- results[[2]][5 + n_pred_Y1] Y1_pval[i] <- results[[3]][2] Y2_pval[i] <- results[[3]][3 + n_pred_Y1] names(Y1_point_estimates)[i] <- names(Y2_point_estimates)[i] <- names_pred_i names(Y1_SE_estimates)[i] <- names(Y2_SE_estimates)[i] <- names_pred_i names(Y1_pval)[i] <- names(Y2_pval)[i] <- names_pred_i convcode[i] <- results[[4]] kkt[i] <- all(results[[5]]) maxloglik[i] <- results[[6]] } output <- list(Y1_point_estimates = Y1_point_estimates, Y2_point_estimates = Y2_point_estimates, Y1_SE_estimates = Y1_SE_estimates, Y2_SE_estimates = Y2_SE_estimates, Y1_pval = Y1_pval, Y2_pval = Y2_pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates for effects of predictors on Y1", "Parameter point estimates for effects of predictors on Y2", "Parameter standard error estimates for effects on Y1", "Parameter standard error estimates for effects on Y2", "Parameter p-values for effects of predictors on Y1", "Parameter p-values for effects of predictors on Y2", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } ## ------------------------------------------------------------------------ # Restrict example to sample size 100 to decrease running time: covariates <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2)[1:100,] predictors <- genodata[1:100,1:5] cjamp_loop_res <- cjamp_loop(copula = "Clayton", Y1 = phenodata$Y1[1:100], Y2 = phenodata$Y2[1:100], predictors = predictors, covariates_Y1 = covariates, covariates_Y2 = covariates, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) cjamp_loop_res ## ---- echo=FALSE--------------------------------------------------------- summary.cjamp <- function(results = NULL) { if (is.null(results) | !class(results)=="cjamp") { stop("cjamp object has to be supplied.") } # for input from cjamp function: if ("Parameter point estimates" %in% names(results)) { length_res <- length(results$"Parameter p-values") res_out <- data.frame(point_estimates = results$"Parameter point estimates"[3:(length_res+2)], SE_estimates = results$"Parameter standard error estimates"[3:(length_res+2)], pvalues = results$"Parameter p-values") print(paste("C-JAMP estimates of marginal parameters.")) print(res_out) } # for input from cjamp_loop function: if ("Parameter p-values for effects of predictors on Y1" %in% names(results)) { res_out_1 <- data.frame(point_estimates = results$"Parameter point estimates for effects of predictors on Y1", SE_estimates = results$"Parameter standard error estimates for effects on Y1", pvalues = results$"Parameter p-values for effects of predictors on Y1") rownames(res_out_1) <- paste("Y1", rownames(res_out_1), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y1.")) print(res_out_1) res_out_2 <- data.frame(point_estimates = results$"Parameter point estimates for effects of predictors on Y2", SE_estimates = results$"Parameter standard error estimates for effects on Y2", pvalues = results$"Parameter p-values for effects of predictors on Y2") rownames(res_out_2) <- paste("Y2", rownames(res_out_2), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y2.")) print(res_out_2) res_out <- data.frame(rbind(res_out_1, res_out_2)) } invisible(res_out) } ## ------------------------------------------------------------------------ # Summary of regular cjamp function summary(cjamp_res) # Summary of looped cjamp function summary(cjamp_loop_res)
/scratch/gouwar.j/cran-all/cranData/CJAMP/inst/doc/cjamp.R
--- title: "C-JAMP: Copula-based Joint Analysis of Multiple Phenotypes" author: "Stefan Konigorski" date: "March 20, 2019" output: pdf_document vignette: > %\VignetteIndexEntry{C-JAMP: Copula-based Joint Analysis of Multiple Phenotypes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## Overview The general goal of C-JAMP (Copula-based Joint Analysis of Multiple Phenotypes) is to jointly model two (or more) traits $Y_1, Y_2$ of a phenotype conditional on covariates using copula functions, in order to estimate and test the association of the covariates with either trait. Copulas are functions used to construct a joint distribution by combining the marginal distributions with a dependence structure (Joe 1997, Nelsen 2006). In contrast to multivariate linear regression models, which model the linear dependence of two random variables coming from a bivariate normal distribution with a certain Pearson’s correlation, more general dependencies can be flexibly investigated using copula functions. This can be helpful when the conditional mean of $Y_i$ given $Y_j$ is not linear in $Y_j$. Additional properties of copula models are that they allow an investigation of the dependence structure between the phenotypes separately from the marginal distributions. Also, the marginal distributions can come from different families and not necessarily from the normal distribution. Copula models can be used to make inference about the marginal parameters and to identify markers associated with one or multiple phenotypes. Through the joint modeling of multiple traits, the power of the association test with a given trait can be increased, also if the markers are only associated with one trait. This is of special interest for genetic association studies, and in particular for the analysis of rare genetic variants, where the low power of association tests is one of the main challenges in empirical studies. The potential of C-JAMP to increase the power of association tests is supported by the results of empirical applications of C-JAMP in real-data analyses (Konigorski, Yilmaz & Bull, 2014; Konigorski, Yilmaz, Pischon, 2016). The functions in this package implement C-JAMP for fitting joint models based on the Clayton and 2-parameter copula, of two normally-distributed traits $Y_1, Y_2$ conditional on multiple predictors, and allow obtaining coefficient and standard error estimates of the copula parameters (modeling the dependence between $Y_1, Y_2$) and marginal parameters (modeling the effect of the predictors on $Y_1$ and on $Y_2$), as well as performing Wald-type hypothesis tests of the marginal parameters. Summary functions provide a user-friendly output. In addition, likelihood-ratio tests for testing nested copula models are available. Furthermore, functions are available to generate genetic data, and phenotypic data from bivariate normal distrutions and bivariate distributions based on copula functions. Finally, for genetic association analyses, functions are available to calculate the amount of phenotypic variance that can be explained by the genetic markers. ## Background on copula functions In more detail, a d-dimensional copula can be defined as a function $C:[0,1]^d \to [0,1]$, which is a joint cumulative distribution function with uniform marginal cumulative distribution functions. Hence, $C$ is the distribution of a multivariate random vector, and can be considered independent of the margins. For $Y_1, \dots, Y_d$ and a covariate vector $x$, the joint distribution $F$ of $Y_1, \dots, Y_d$, conditional on $x$, can be constructed by combining the marginal distributions of $Y_1, \dots, Y_d$, $F_1, \dots, F_d$, conditional on $x$, using a copula function $C_\psi$ with dependence parameter(s) $\psi$: $$ F(Y_1, \dots, Y_d|x)= C_\psi (F_1 (Y_1|x), \dots, F_d(Y_d|x)). $$ For continuous marginal distributions, the copula $C_\psi$ is unique and the multivariate distribution can be constructed from the margins in a uniquely defined way (Sklar, 1959). Popular copula functions include the Clayton family $$ C_\phi (u_1, \dots, u_d, \phi) = \left( \sum_{i=1}^d u_i^{-\phi} - (d-1) \right)^{ -\frac{1}{\phi}} $$ with $\phi>0$, and the Gumbel-Hougaard family $$ C_\theta (u_1, \dots, u_d, \theta) = exp\left( - \left[ \sum_{i=1}^d(-log(u_i))^\theta \right]^{\frac{1}{\theta}} \right) $$ with $\theta>1$. A third family which includes both Clayton and Gumbel-Hougaard copula (for $\theta=1$ and $\phi \to 0$) is the 2-paramater copula family $$ C_\psi (u_1, \dots, u_d, \phi, \theta) = \left( \left[ \sum_{i=1}^d \left( u_i^{-\phi}-1 \right)^\theta \right]^{\frac{1}{\theta}} + 1 \right)^{-\frac{1}{\phi}} $$ with $0 \leq u_1, u_2 \leq 1$, and the copula parameters $\psi=(\phi,\theta), \phi>0, \theta \geq 1$, which allows a flexible modeling of both the lower- and upper-tail dependence. For the 2-parameter copula family, Kendall’s tau can be derived as (Joe, 1997) $$ \tau = 1 - \frac{2}{\theta(\phi+2)}. $$ Additional dependence parameters of interest are the lower and upper tail dependence measures $\lambda_L, \lambda_U$, which explain the amount of dependence between extreme values. For the 2-parameter copula family, these dependence measures become (Joe, 1997) $$ \lambda_L=2^{-\frac{1}{\theta\phi}}, \ \lambda_U= 2-2^{\frac{1}{\theta}}.$$ Data $Y_1, Y_2$ can be sampled from the Clayton copula (with standard normal margins) using the `generate_clayton_copula()` function. This uses the following steps to generate standard normal $Y_1, Y_2$ from the Clayton copula $C_\phi (\Phi(Y_1), \Phi(Y_2)) = C_\phi (U_1, U_2)$, where $\Phi$ is the standard normal cumulative distribution function: 1. Generate uniform random variables $U_1, \tilde{U}_2 \sim Unif(0,1)$. 1. Generate $Y_1$ from the inverse standard normal distribution of $U_1$, $Y_1 := \Phi^{-1}(U_1)$. 1. In order to obtain the second variable $Y_2$, use the conditional distribution of $U_2$ given $U_1$, set $\tilde{U}_2 = \frac{\partial C(U_1, U_2)}{\partial U_1}$ and solve for $U_2$. This yields $U_2 = \left( 1 - U_1^{-\phi} \cdot \left( 1 - \tilde{U}_2^{-\frac{\phi}{1 + \phi}} \right) \right)^{-\frac{1}{\phi}}$. 1. Generate $Y_2$ from the inverse standard normal distribution of $U_2$, $Y_2 := \Phi^{-1}(U_2)$. ```{r, echo=FALSE} generate_clayton_copula <- function(n = NULL, phi = NULL) { U1 <- runif(n, min = 0, max = 1) U2 <- runif(n, min = 0, max = 1) Y1 <- qnorm(U1, mean = 0, sd = 1) Y2.help <- (1 - U1^(-phi) * (1 - U2^(-phi/(1 + phi))))^(-1/phi) tau <- phi/(phi + 2) Y2 <- qnorm(Y2.help, mean = 0, sd = 1) phenodata <- data.frame(Y1 = Y1, Y2 = Y2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) } ``` ```{r} # Generate phenotype data from the Clayton copula: set.seed(10) dat1a <- generate_clayton_copula(n = 1000, phi = 0.5) dat1b <- generate_clayton_copula(n = 1000, phi = 2) dat1c <- generate_clayton_copula(n = 1000, phi = 8) par(mfrow = c(1, 3)) plot(dat1a$Y1, dat1a$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.2"))) plot(dat1b$Y1, dat1b$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.5"))) plot(dat1c$Y1, dat1c$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.8"))) ``` ## Data generation functions In order to generate sample data for simulation studies and to illustrate C-JAMP, different functions are provided. Firstly, the functions `generate_singleton_data()`, `generate_doubleton_data()` and `generate_genodata()` can be used to generate genetic data in the form of single nucleotide variants (SNVs). `generate_singleton_data()` generates singletons (i.e., SNVs with one observed minor allele); `generate_doubleton_data()` generates doubletons (i.e., SNVs with two observed minor alleles), and the function `generate_genodata()` generates $n$ observations of $k$ SNVs with random minor allele frequencies. The minor allele frequencies can be computed using the function `compute_MAF()`. Next, `generate_phenodata_1_simple()`, `generate_phenodata_1()`, `generate_phenodata_2_bvn()` and `generate_phenodata_2_copula()` can be used to generate phenotype data based on SNV input data, covariates, and a specification of the covariate effect sizes. Here, the functions `generate_phenodata_1_simple()` and `generate_phenodata_1()` generate one normally-distributed or binary phenotype $Y$ conditional on provided SNVs and two generated covariates $X_1$, $X_2$. The functions `generate_phenodata_2_bvn()` and `generate_phenodata_2_copula()` generate two phenotypes $Y_1$, $Y_2$ with dependence Kendall's $\tau$ conditional on the provided SNVs and covariates $X_1$, $X_2$ from the bivariate normal distribution or the Clayton copula function with standard normal marginal distributions. `generate_phenodata_2_copula()` is using the function `generate_clayton_copula()` described above. ```{r, echo=FALSE} generate_singleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, rep(0, n_ind - 1)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ``` ```{r, echo=FALSE} generate_doubleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, 1, rep(0, n_ind - 2)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ``` ```{r, echo=FALSE} generate_genodata <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) for (i in 1:n_SNV) { MAFhelp <- round(runif(1, 0, 0.5), 3) n0 <- round((1 - MAFhelp)^2 * n_ind) n2 <- round(MAFhelp^2 * n_ind) n1 <- n_ind - n0 - n2 helpvec <- c(rep(0, n0), rep(1, n1), rep(2, n2)) genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ``` ```{r, echo=FALSE} compute_MAF <- function(genodata) { MAF <- NULL if (is.null(dim(genodata))) { dat <- genodata[!is.na(genodata)] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF > 0.5) { warning("MAF is larger than 0.5, maybe recode alleles?") } } if (!is.null(dim(genodata))) { for (i in 1:dim(genodata)[2]) { dat <- genodata[, i][!is.na(genodata[, i])] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF[i] <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF[i] > 0.5) { warning(paste("MAF of SNV ",i ," is larger than 0.5, maybe recode alleles?",sep="")) } } } names(MAF) <- names(genodata) return(MAF) } ``` ```{r, echo=FALSE} generate_phenodata_1_simple <- function(genodata = NULL, type = "quantitative", b = 0, a = c(0, 0.5, 0.5)) { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- rnorm(n_ind, mean = 0, sd = 1) X2 <- rbinom(n_ind, size = 1, prob = 0.5) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + genodata %*% b + rnorm(n_ind, 0, 1) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * X1 + a[3] * X2 + b * genodata))) Y <- rbinom(n_ind, 1, P) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } ``` ```{r, echo=FALSE} generate_phenodata_1 <- function(genodata = NULL, type = "quantitative", b = 0.6, a = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied") } genodata <- as.data.frame(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.data.frame(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b <- b[causal_idx] alpha_g <- b * abs(log10(compute_MAF(geno_causal))) # if direction b or c is specified, change direction of effect for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in%help_idx_2)) + 1) * alpha_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g } epsilon1 <- stats::rnorm(n_ind, mean = 0, sd = sigma1) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y <- as.numeric(Y) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * scale(X1, center = T, scale = F) + a[3] * scale(X2, center = T, scale = F) + geno_causal %*% alpha_g))) Y <- stats::rbinom(n_ind, 1, P) Y <- as.numeric(Y) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } ``` ```{r, echo=FALSE} generate_phenodata_2_bvn <- function(genodata = NULL, tau = NULL, b1 = 0, b2 = 0, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5)) { if (!requireNamespace("MASS", quietly = TRUE)) { stop("MASS package needed for this function to work. Please install it.", call. = FALSE) } if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } # generate the two covariates X1 <- rnorm(n_ind, mean = 0, sd = 1) X2 <- rbinom(n_ind, size = 1, prob = 0.5) # set the weight of the nongenetic covariates set the residual variances sigma1 <- 1 sigma2 <- 1 if (is.null(tau)) { stop("Tau has to be provided.") } rho <- sin(tau * pi/2) mu <- c(0, 0) sigma <- matrix(c(sigma1, rho, rho, sigma2), 2, 2) epsilon <- MASS::mvrnorm(n = n_ind, mu = mu, Sigma = sigma) epsilon1 <- epsilon[, 1] epsilon2 <- epsilon[, 2] Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + genodata %*% b1 + epsilon1 Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + genodata %*% b2 + epsilon2 phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) return(phenodata) } ``` ```{r, echo=FALSE} generate_phenodata_2_copula <- function(genodata = NULL, phi = NULL, tau = 0.5, b1 = 0.6, b2 = 0.6, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 sigma2 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b1 <- b1[causal_idx] b2 <- b2[causal_idx] alpha_g <- b1 * abs(log10(compute_MAF(geno_causal))) beta_g <- b2 * abs(log10(compute_MAF(geno_causal))) # if b or c is specified, change effect direction for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * beta_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * beta_g } # compute copula parameter between the two phenotypes from tau if tau is given if (!is.null(tau)) { phi <- (2 * tau)/(1 - tau) } res_copula <- generate_clayton_copula(n = n_ind, phi = phi) epsilon1 <- res_copula$Y1 epsilon2 <- res_copula$Y2 if (is.null(tau)) { tau <- phi/(phi + 2) } Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y1 <- as.numeric(Y1) Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + geno_causal %*% beta_g + epsilon2 Y2 <- as.numeric(Y2) phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) } ``` ```{r} # Generate genetic data: set.seed(10) genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) compute_MAF(genodata) # Generate phenotype data from the bivariate normal distribution given covariates: phenodata_bvn <- generate_phenodata_2_bvn(genodata = genodata, tau = 0.5, b1 = 1, b2 = 2) plot(phenodata_bvn$Y1, phenodata_bvn$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of bivariate normal ", Y[1], ", ", Y[2], " with ", tau, "=0.5"))) # Generate phenotype data from the Clayton copula given covariates: phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, MAF_cutoff = 1, prop_causal = 1, tau = 0.5, b1 = 0.3, b2 = 0.3) plot(phenodata$Y1, phenodata$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " from the Clayton copula with ", tau, "=0.5"))) ``` For the analysis of genetic associations with the phenotypes, the amount of variability in the phenotypes that can be explained by the SNVs might be of interest. This can be computed based on four different approaches using the function `compute_expl_var()` (Laird & Lange, 2011), which is described in more detail in the help pages of the function. ```{r, echo=FALSE} compute_expl_var <- function(genodata = NULL, phenodata = NULL, type = "Rsquared_unadj", causal_idx = NULL, effect_causal = NULL) { ExplVar <- NULL if (is.null(phenodata) | is.null(genodata)) { stop("Genodata and phenodata have to be supplied.") } if (!dim(genodata)[1] == length(phenodata)) { stop("Number of observations in genodata and phenodata has to be the same.") } if (class(genodata) == "data.frame") { if (!all(sapply(genodata, is.numeric))) { genodata <- as.data.frame(data.matrix(genodata)) } } if (is.null(dim(genodata))) { if (!is.numeric(genodata)) { stop("genodata has to be numeric.") } } if (class(phenodata) == "data.frame") { if (!all(sapply(phenodata, is.numeric))) { phenodata <- as.data.frame(data.matrix(phenodata)) warning("phenodata contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(dim(phenodata))) { if (!is.numeric(phenodata)) { stop("phenodata has to be numeric.") } } if (is.null(causal_idx)) { warning("A vector indicating the causal SNVs is not supplied \n so the estimate of explained variance is based on all SNVs.") } if (any(type %in% c("MAF_based", "MAF_based_Y_adjusted")) & is.null(effect_causal)) { stop("A vector indicating the genetic effect sizes of the causal SNVs has \n to be supplied for the MAF_based and MAF_based_Y_adjusted approach.") } if (!is.null(causal_idx)) { genodata <- as.data.frame(genodata[, causal_idx]) } MAF_causal <- compute_MAF(genodata) phenodata <- as.data.frame(phenodata) dat <- as.data.frame(append(phenodata, genodata)) dat <- dat[complete.cases(dat),] names(dat)[1] <- "Y" ExplVar <- list() if ("Rsquared_unadj" %in% type) { ExplVar$Rsquared_unadj <- summary(lm(Y ~ ., data = dat))$r.squared } if ("Rsquared_adj" %in% type) { ExplVar$Rsquared_adj <- summary(lm(Y ~ ., data = dat))$adj.r.squared } if ("MAF_based" %in% type) { ExplVar$MAF_based <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2) } if ("MAF_based_Y_adjusted" %in% type) { ExplVar$MAF_based_Y_adjusted <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2)/var(dat$Y) } return(ExplVar) } ``` ```{r} compute_expl_var(genodata = genodata, phenodata = phenodata$Y1, type = c("Rsquared_unadj", "Rsquared_adj", "MAF_based", "MAF_based_Y_adjusted"), causal_idx = rep(TRUE,20), effect_causal = c(0.3 * abs(log10(compute_MAF(genodata$SNV1))), rep(0,19))) ``` ## C-JAMP: Copula-based joint analysis of multiple phenotypes C-JAMP is implemented for the joint analysis of two phenotypes $Y_1, Y_2$ conditional on one or multiple predictors $x$ with linear marginal models. Functions are available to fit the joint model $$ F(Y_1, Y_2|x)= C_\psi (F_1 (Y_1|x), F_2 (Y_2|x)) $$ for the Clayton and 2-parameter copula, with marginal models $$Y_1 = \alpha^T X + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2 ) $$ $$Y_2 = \beta^T X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2 ). $$ Maximum likelihood estimates for all parameters $(\psi, \alpha, \beta, \sigma_1, \sigma_2)$ can be obtained using the function `get_estimates_naive()`, which is based on the ´lm()´ function. ```{r, echo=FALSE} get_estimates_naive <- function(Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, copula_param = "both") { if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } dataframe_Y1 <- data.frame(Y1 = Y1) dataframe_Y2 <- data.frame(Y2 = Y2) n_ind <- dim(dataframe_Y1)[1] if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y1)) { predictors_Y1 <- data.frame(predictors_Y1) } if (!is.null(predictors_Y2)) { predictors_Y2 <- data.frame(predictors_Y2) } if (!n_ind == dim(dataframe_Y2)[1]) { stop("Variables must have same length.") } if (!is.null(predictors_Y1)) { if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y2)) { if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y1)) { dataframe_Y1 <- cbind(dataframe_Y1, predictors_Y1) } if (!is.null(predictors_Y2)) { dataframe_Y2 <- cbind(dataframe_Y2, predictors_Y2) } res_Y1 <- lm(Y1 ~ ., data = dataframe_Y1) res_Y2 <- lm(Y2 ~ ., data = dataframe_Y2) param_Y1_sigma <- log(sd(res_Y1$residuals, na.rm = T)) #param_Y1_sigma <- log(sd(Y1, na.rm = T)) names(param_Y1_sigma) <- "Y1_log_sigma" param_Y2_sigma <- log(sd(res_Y2$residuals, na.rm = T)) #param_Y2_sigma <- log(sd(Y2, na.rm = T)) names(param_Y2_sigma) <- "Y2_log_sigma" tau <- cor(Y1, Y2, use = "complete.obs", method = c("kendall")) if (tau == 0) { tau <- 1e-04 } # to avoid technical breakdown of function log_phi <- log(2 * tau/(1 - tau)) log_theta <- log((1/(1 - tau)) - 1) param_Y1_Y2 <- c(log_phi, log_theta) names(param_Y1_Y2) <- c("log_phi", "log_theta_minus1") if (copula_param == "phi") { param_Y1_Y2 <- param_Y1_Y2[1] } if (copula_param == "theta") { param_Y1_Y2 <- param_Y1_Y2[2] } param_Y1_predictors <- res_Y1$coefficients names(param_Y1_predictors) <- paste("Y1_", names(param_Y1_predictors), sep = "") param_Y2_predictors <- res_Y2$coefficients names(param_Y2_predictors) <- paste("Y2_", names(param_Y2_predictors), sep = "") if (any(is.na(param_Y1_Y2))) { warning("One or both dependence parameters could not be estimated.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { warning("One or both marginal variances could not be estimated.") } if (any(is.na(param_Y1_predictors)) | any(is.na(param_Y2_predictors))) { warning("One or more marginal parameters could not be estimated.") } estimates <- c(param_Y1_Y2, param_Y1_sigma, param_Y2_sigma, param_Y1_predictors, param_Y2_predictors) return(estimates) } ``` ```{r} predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") ``` For these or any other parameter estimates, the log-likelihood (or rather the minus log-likelihood) of the copula model can be computed with the function `minusloglik()` for the Clayton and 2-parameter copula: ```{r, echo=FALSE} minusloglik <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, parameters = NULL) { if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (!is.null(predictors_Y1)) { n_Y1_pred <- dim(predictors_Y1)[2] } else { n_Y1_pred <- 0 } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (copula == "Clayton") { param_Y1_Y2 <- parameters[1] n_dep <- 1 if (!names(param_Y1_Y2) == "log_phi") { stop("Estimate for phi is not provided.") } } if (copula == "2param") { param_Y1_Y2 <- parameters[1:2] n_dep <- 2 if (!identical(names(param_Y1_Y2), c("log_phi", "log_theta_minus1"))) { stop("Estimates for phi/theta are not provided.") } } param_Y1_sigma <- parameters[n_dep + 1] param_Y2_sigma <- parameters[n_dep + 2] no_p <- length(parameters) param_Y1_predictors <- parameters[(n_dep + 3):(n_dep + 3 + n_Y1_pred)] param_Y2_predictors <- parameters[(no_p - n_Y2_pred):no_p] if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } n_ind <- length(Y1) if (!is.null(predictors_Y1)) { predictors_Y1 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y1) } else { predictors_Y1 <- data.frame(One = rep(1, n_ind)) } if (!is.null(predictors_Y2)) { predictors_Y2 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y2) } else { predictors_Y2 <- data.frame(One = rep(1, n_ind)) } if (!n_ind == length(Y2)) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } if (is.null(param_Y1_Y2) | any(is.na(param_Y1_Y2))) { stop("Estimate(s) of dependence betwee Y1 and Y2 is (are) not provided.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { stop("One or both marginal variances are not provided") } if (any(is.na(param_Y1_predictors))) { warning(paste("Effect estimate of ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " on Y1 is missing. Variable ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y1 <- predictors_Y1[, !is.na(param_Y1_predictors)] param_Y1_predictors <- param_Y1_predictors[!is.na(param_Y1_predictors)] } if (any(is.na(param_Y2_predictors))) { warning(paste("Effect estimates of ", names(predictors_Y2)[which(is.na(param_Y2_predictors))], " on Y2 is missing. Variable ", names(predictors_Y2)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y2 <- predictors_Y2[, !is.na(param_Y2_predictors)] param_Y2_predictors <- param_Y2_predictors[!is.na(param_Y2_predictors)] } if (copula == "Clayton") { phi <- exp(param_Y1_Y2[1]) } else if (copula == "2param") { phi <- exp(param_Y1_Y2[1]) theta <- exp(param_Y1_Y2[2]) + 1 } else { stop("copula has to be specified") } minusloglik <- 0 predictors_Y1 <- as.matrix(predictors_Y1) predictors_Y2 <- as.matrix(predictors_Y2) for (i in 1:n_ind) { lik.pt1.1 <- pnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt1.2 <- pnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) lik.pt2 <- dnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt3 <- dnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) if (copula == "Clayton") { fun <- ((lik.pt1.1)^(-phi) - 1) + ((lik.pt1.2)^(-phi) - 1) joints <- (fun + 1)^(-1/phi) d1.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1) * (fun + 1)^(1/phi + 1) lik <- dd.joints * (fun * (1 + phi) * (fun + 1)^(-1)) } if (copula == "2param") { fun <- ((lik.pt1.1)^(-phi) - 1)^theta + ((lik.pt1.2)^(-phi) - 1)^theta joints <- (fun^(1/theta) + 1)^(-1/phi) d1.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.1)^(-phi) - 1)^(theta - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.2)^(-phi) - 1)^(theta - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1/theta) * (fun^(1/theta) + 1)^(1/phi + 1) lik <- dd.joints * ((theta - 1) * phi + fun^(1/theta) * (1 + phi) * (fun^(1/theta) + 1)^(-1)) } minusloglik <- minusloglik - log(lik) } return(as.numeric(minusloglik)) } ``` ```{r} predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:5]) estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates, copula = "2param") ``` It should be noted that the `minusloglik()` function (and the `cjamp()`, `cjamp_loop()` functions below) assume quantitative predictors and use an additive model. That means that for the analysis of categorical predictors with more than 2 levels, dummy variables have to be created beforehand. Accordingly, if single nucleotide variants (SNVs) are included as predictors, the computation is based on an additive genetic model if SNVs are provided as 0-1-2 genotypes and on a dominant model if SNVs are provided as 0-1 genotypes. The `lrt_copula()` can be used to test the model fit of different nested copula models with the same marginal models. For this, likelihood ratio tests are performed. In more detail, to test the fit of the 1-parameter Clayton copula model fit versus the 2-parameter copula, i.e. $H_0: \phi \to 0$, the likelihood ratio test statistic $$ logLR = 2 \cdot \left(L\left(\hat{\alpha},\hat{\beta},\hat{\psi}\right) - L\left(\hat{\alpha}(\psi_0),\hat{\beta}(\psi_0),\hat{\psi} \right)\right)$$ can be used, where $\hat{\psi}=(\hat{\phi}, \hat{\theta})$, $\hat{\psi_0}=\left(\hat{\phi}(\theta=1), 1\right)$, see Yilmaz & Lawless (2011). Here, $\hat{\alpha}(\psi_0)$ and $\hat{\beta}(\psi_0)$ are the maximum likelihood estimates of $\alpha$ and $\beta$ under the null model $\psi=\psi_0$. P-values are obtained by using that $logLR$ is asymptotically distributed as $0.5 + 0.5\chi_1^2$ under the null hypothesis $\psi=\psi_0$ and under the assumption that other free parameters in $\psi_0$ don’t lie on the boundary of the parameter space (Self & Liang, 1987). ```{r, echo=FALSE} lrt_copula <- function(minlogl_null = NULL, minlogl_altern = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern)) { stop("minlogl_null and minlogl_altern have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - (0.5 + 0.5 * pchisq(chisq, df = 1)) return(list(chisq = chisq, pval = pval)) } ``` ```{r} # Example: Test whether 2-parameter copula model has a better # model fit compared to Clayton copula (no). predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) estimates_c <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "phi") minusloglik_Clayton <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates_c, copula = "Clayton") estimates_2p <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") minusloglik_2param <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates_2p, copula = "2param") lrt_copula(minusloglik_Clayton, minusloglik_2param) ``` Log-likelihood ratio tests of marginal parameters within the same copula model can be performed using the `lrt_param()` function: ```{r, echo=FALSE} lrt_param <- function(minlogl_null = NULL, minlogl_altern = NULL, df = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern) | is.null(df)) { stop("minlogl_null, minlogl_altern and df have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - pchisq(chisq, df = df) return(list(chisq = chisq, pval = pval)) } ``` ```{r} # Example: Test marginal parameters (alternative model has better fit). predictors_1 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) estimates_1 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_1, predictors_Y2 = predictors_1, copula = "phi") minusloglik_1 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_1, predictors_Y2 = predictors_1, parameters = estimates_1, copula = "Clayton") predictors_2 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) estimates_2 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_2, predictors_Y2 = predictors_2, copula = "phi") minusloglik_2 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_2, predictors_Y2 = predictors_2, parameters = estimates_2, copula = "Clayton") lrt_param(minusloglik_1, minusloglik_2, df=2) ``` Finally, to obtain maximum likelihood estimates of the parameters $(\psi, \alpha, \beta, \sigma_1, \sigma_2)$ as well as standard error estimates under the Clayton or 2-parameter copula models, the function `cjamp()` can be used. `cjamp()` uses the `optimx()` function in the optimx package to maximize the log-likelihood function (i.e., minimize `minusloglik()`). For this, the BFGS optimization method is recommended. In order to deal with convergence problems, several checks are built-in, and different starting values for the optimization algorithm are automatically tried. Standard error estimates of the parameter estimates are obtained from the observed inverse information matrix. Finally, p-values are computed for the marginal parameter estimates from hypothesis tests of the absence of effects of each predictor on each phenotype in the marginal models. ```{r, echo=FALSE} cjamp <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (pval_est & !SE_est) { stop("SE_est has to be TRUE to compute p-values.") } if (!requireNamespace("optimx", quietly = TRUE)) { stop("Package optimx needed for this function to work. Please install it.", call. = FALSE) } if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (cor(Y1, Y2, use = "complete.obs", method = "kendall") < 0) { Y2 <- -Y2 warning("Dependence between Y1, Y2 is negative but copulas require positive dependence. \n Hence Y2 is transformed to -Y2 and point estimates for Y2 are in inverse direction.") } if (copula == "Clayton") { n_dep <- 1 copula_param = "phi" } if (copula == "2param") { n_dep <- 2 copula_param = "both" } if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] n_pred <- 0 } if (!is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y1)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] } if (is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y2)[2] } if (!is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y1) & complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] + dim(predictors_Y2)[2] } if (scale_var) { predictors_Y1 <- data.frame(lapply(predictors_Y1, scale)) predictors_Y2 <- data.frame(lapply(predictors_Y2, scale)) } convcode <- 1 kkt <- c(FALSE, FALSE) n_iter <- 1 helpnum <- 0.4 while (!(convcode == 0 & all(kkt) & !any(is.na(kkt))) & (n_iter <= n_iter_max)) { startvalues <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) - helpnum names_pred <- names(startvalues[(n_dep + 3):length(startvalues)]) if (minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues) == Inf | is.na(minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues))) { helpnum <- (-1)^rbinom(1, 1, 0.5) * runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 next } res <- optimx::optimx(par = startvalues, fn = minusloglik, Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, method = optim_method, hessian = TRUE, control = list(trace = trace, kkt2tol = kkt2tol)) convcode <- res$convcode kkt <- c(res$kkt1, res$kkt2) helpnum <- (-1)^rbinom(1, 1, 0.5) * runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 } names(convcode) <- "convcode" names(kkt) <- c("KKT1", "KKT2") maxloglik <- NULL if (!convcode == 0) { warning("In model with predictors \n", names_pred, ": \n Optimization doesn't seem to be converged.", "\n SE estimates and pvalues are not computed. Please check.") } if (!all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n KKT conditions are not satistified.", " \n SE estimates and pvalues are not computed. Please check.") } if (!convcode == 0 | !all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n Naive parameter estimates are computed from separate marginal models.") point_estimates <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) point_estimates <- as.list(point_estimates) if (copula == "Clayton") { phi <- exp(point_estimates$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(point_estimates$log_phi) theta <- exp(point_estimates$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates[(n_dep + 1):length(point_estimates)], phi, theta, tau, lambda_l, lambda_u) point_estimates[[1]] <- exp(point_estimates[[1]]) point_estimates[[2]] <- exp(point_estimates[[2]]) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (convcode == 0 & all(kkt) & !any(is.na(kkt))) { maxloglik <- res$value names(maxloglik) <- "maxloglik" point_estimates <- res[(n_dep + 1):(n_dep + n_pred + 4)] point_estimates[1:2] <- exp(point_estimates[1:2]) if (copula == "Clayton") { phi <- exp(res$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(res$log_phi) theta <- exp(res$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates, phi, theta, tau, lambda_l, lambda_u) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } SE_estimates <- NULL if (SE_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { SE_estimates <- vector(mode = "numeric", length = (n_pred + 4)) SE_estimates[1] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 1] * (point_estimates$Y1_sigma^2)) SE_estimates[2] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 2] * (point_estimates$Y2_sigma^2)) SE_estimates[3:length(SE_estimates)] <- sqrt(diag(solve(attributes(res)$details[[3]]))[(n_dep + 3):(n_dep + n_pred + 4)]) if (copula == "Clayton") { helpvar1 <- 2 * phi/((phi + 2)^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) tau_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (helpvar1^2)) theta_SE <- lambda_l_SE <- lambda_u_SE <- NA } if (copula == "2param") { helpvar3.1 <- 2 * phi/(theta * (phi + 2)^2) helpvar3.2 <- 2 * (theta - 1)/(theta^2 * (phi + 2)) helpvar3.3 <- (2^(-1/(theta * phi))) * (log(2)/(theta * phi)) helpvar3.4 <- (2^(-1/(theta * phi))) * (log(2) * (theta - 1)/(theta^2 * phi)) helpvar3.5 <- (2^(1/theta)) * ((theta - 1) * log(2)/theta^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) theta_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * ((theta - 1)^2)) tau_SE <- sqrt(t(c(helpvar3.1, helpvar3.2)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.1, helpvar3.2)) lambda_l_SE <- sqrt(t(c(helpvar3.3, helpvar3.4)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.3, helpvar3.4)) lambda_u_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * helpvar3.5^2) } SE_estimates <- c(SE_estimates, phi_SE, theta_SE, tau_SE, lambda_l_SE, lambda_u_SE) names(SE_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (is.null(SE_estimates)){ SE_estimates <- rep(NA, length(point_estimates)) } pval <- NULL point_estimates <- unlist(point_estimates) if (pval_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { pval <- vector(mode = "numeric", length = (n_pred + 2)) pval <- 2 * pnorm(as.numeric(-abs(point_estimates[3:(n_pred + 4)]/ SE_estimates[3:(n_pred + 4)]))) names(pval) <- names_pred } if (is.null(pval)){ pval <- rep(NA, (n_pred + 2)) } output <- list(point_estimates = point_estimates, SE_estimates = SE_estimates, pval = pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates", "Parameter standard error estimates", "Parameter p-values", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } ``` ```{r} # Restrict example to sample size 100 to decrease running time: predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:3])[1:100,] cjamp_res <- cjamp(copula = "2param", Y1 = phenodata$Y1[1:100], Y2 = phenodata$Y2[1:100], predictors_Y1 = predictors, predictors_Y2 = predictors, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) cjamp_res ``` If the goal is to test a large number of predictors in the same marginal models (such as in genetic association studies), the wrapper function `cjamp_loop()` provides an easy use of the `cjamp()` function and only extracts the coefficient and standard error estimates as well as the p-values for the predictor(s) of interest, and not for all other covariates. ```{r, echo=FALSE} cjamp_loop <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors = NULL, covariates_Y1 = NULL, covariates_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (is.null(predictors)) { stop("At least one predictor has to be supplied.") } if (!class(predictors) == "data.frame") { stop("Predictors has to be a dataframe.") } if (!all(sapply(predictors, is.numeric))) { predictors <- as.data.frame(data.matrix(predictors)) warning("predictors contains non-numeric Variables, which have automatically been transformed.") } if ((!class(covariates_Y1) == "data.frame" & !is.null(covariates_Y1)) | (!class(covariates_Y2) == "data.frame" & !is.null(covariates_Y2))) { stop("covariates_Y1 and covariates_Y2 have to be a dataframe or NULL.") } if (class(covariates_Y1) == "data.frame") { if (!all(sapply(covariates_Y1, is.numeric))) { covariates_Y1 <- as.data.frame(data.matrix(covariates_Y1)) warning("covariates_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(covariates_Y2) == "data.frame") { if (!all(sapply(covariates_Y2, is.numeric))) { covariates_Y2 <- as.data.frame(data.matrix(covariates_Y2)) warning("covariates_Y2 contains non-numeric Variables, which have automatically been transformed.") } } N <- dim(predictors)[2] Y1_point_estimates <- Y1_SE_estimates <- Y1_pval <- NULL Y2_point_estimates <- Y2_SE_estimates <- Y2_pval <- NULL convcode <- kkt <- maxloglik <- NULL for (i in 1:N) { names_pred_i <- names(predictors)[i] predictors_Y1 <- predictors_Y2 <- predictors[, i, drop = FALSE] if (!is.null(covariates_Y1)) { predictors_Y1 <- cbind(predictors_Y1, as.data.frame(covariates_Y1)) } if (!is.null(covariates_Y2)) { predictors_Y2 <- cbind(predictors_Y2, as.data.frame(covariates_Y2)) } n_pred_Y1 <- dim(predictors_Y1)[2] n_pred_Y2 <- dim(predictors_Y2)[2] results <- cjamp(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, scale_var = scale_var, copula = copula, optim_method = optim_method, trace = trace, kkt2tol = kkt2tol, SE_est = SE_est, pval_est = pval_est, n_iter_max = n_iter_max) Y1_point_estimates[i] <- as.numeric(results[[1]][4]) Y2_point_estimates[i] <- as.numeric(results[[1]][5 + n_pred_Y1]) Y1_SE_estimates[i] <- results[[2]][4] Y2_SE_estimates[i] <- results[[2]][5 + n_pred_Y1] Y1_pval[i] <- results[[3]][2] Y2_pval[i] <- results[[3]][3 + n_pred_Y1] names(Y1_point_estimates)[i] <- names(Y2_point_estimates)[i] <- names_pred_i names(Y1_SE_estimates)[i] <- names(Y2_SE_estimates)[i] <- names_pred_i names(Y1_pval)[i] <- names(Y2_pval)[i] <- names_pred_i convcode[i] <- results[[4]] kkt[i] <- all(results[[5]]) maxloglik[i] <- results[[6]] } output <- list(Y1_point_estimates = Y1_point_estimates, Y2_point_estimates = Y2_point_estimates, Y1_SE_estimates = Y1_SE_estimates, Y2_SE_estimates = Y2_SE_estimates, Y1_pval = Y1_pval, Y2_pval = Y2_pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates for effects of predictors on Y1", "Parameter point estimates for effects of predictors on Y2", "Parameter standard error estimates for effects on Y1", "Parameter standard error estimates for effects on Y2", "Parameter p-values for effects of predictors on Y1", "Parameter p-values for effects of predictors on Y2", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } ``` ```{r} # Restrict example to sample size 100 to decrease running time: covariates <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2)[1:100,] predictors <- genodata[1:100,1:5] cjamp_loop_res <- cjamp_loop(copula = "Clayton", Y1 = phenodata$Y1[1:100], Y2 = phenodata$Y2[1:100], predictors = predictors, covariates_Y1 = covariates, covariates_Y2 = covariates, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) cjamp_loop_res ``` Both `cjamp()` and `cjamp_loop()` return `cjamp` objects as output, so that the `summary.cjamp()` function can be used through the generic `summary()` to provide a reader-friendly formatted output of the results. ```{r, echo=FALSE} summary.cjamp <- function(results = NULL) { if (is.null(results) | !class(results)=="cjamp") { stop("cjamp object has to be supplied.") } # for input from cjamp function: if ("Parameter point estimates" %in% names(results)) { length_res <- length(results$"Parameter p-values") res_out <- data.frame(point_estimates = results$"Parameter point estimates"[3:(length_res+2)], SE_estimates = results$"Parameter standard error estimates"[3:(length_res+2)], pvalues = results$"Parameter p-values") print(paste("C-JAMP estimates of marginal parameters.")) print(res_out) } # for input from cjamp_loop function: if ("Parameter p-values for effects of predictors on Y1" %in% names(results)) { res_out_1 <- data.frame(point_estimates = results$"Parameter point estimates for effects of predictors on Y1", SE_estimates = results$"Parameter standard error estimates for effects on Y1", pvalues = results$"Parameter p-values for effects of predictors on Y1") rownames(res_out_1) <- paste("Y1", rownames(res_out_1), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y1.")) print(res_out_1) res_out_2 <- data.frame(point_estimates = results$"Parameter point estimates for effects of predictors on Y2", SE_estimates = results$"Parameter standard error estimates for effects on Y2", pvalues = results$"Parameter p-values for effects of predictors on Y2") rownames(res_out_2) <- paste("Y2", rownames(res_out_2), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y2.")) print(res_out_2) res_out <- data.frame(rbind(res_out_1, res_out_2)) } invisible(res_out) } ``` ```{r} # Summary of regular cjamp function summary(cjamp_res) # Summary of looped cjamp function summary(cjamp_loop_res) ``` ## References Joe H (1997). Multivariate models and multivariate dependence concepts. London: Chapman & Hall. Konigorski S, Yilmaz YE, Bull SB (2014). Bivariate genetic association analysis of systolic and diastolic blood pressure by copula models. BMC Proc, 8(Suppl 1): S72. Konigorski S, Yilmaz YE, Pischon T (2016). Genetic association analysis based on a joint model of gene expression and blood pressure. BMC Proc, 10(Suppl 7): 289-294. Laird NM, Lange C (2011). The fundamentals of modern statistical genetics. New York: Springer. Nelsen RB (2006). An introduction to copulas. Springer, New York. Sklar A (1959). Fonctions de répartition à n dimensions et leurs marges. Publications de l’Institut de statistique de l’Université de Paris 8: 229–231. Self GS, Liang KY (1987). Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions. J Am Stat Assoc, 82: 605–610. Yilmaz YE, Lawless JF (2011). Likelihood ratio procedures and tests of fit in parametric and semiparametric copula models with censored data. Lifetime Data Anal, 17(3): 386-408.
/scratch/gouwar.j/cran-all/cranData/CJAMP/inst/doc/cjamp.Rmd
--- title: "C-JAMP: Copula-based Joint Analysis of Multiple Phenotypes" author: "Stefan Konigorski" date: "March 20, 2019" output: pdf_document vignette: > %\VignetteIndexEntry{C-JAMP: Copula-based Joint Analysis of Multiple Phenotypes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ## Overview The general goal of C-JAMP (Copula-based Joint Analysis of Multiple Phenotypes) is to jointly model two (or more) traits $Y_1, Y_2$ of a phenotype conditional on covariates using copula functions, in order to estimate and test the association of the covariates with either trait. Copulas are functions used to construct a joint distribution by combining the marginal distributions with a dependence structure (Joe 1997, Nelsen 2006). In contrast to multivariate linear regression models, which model the linear dependence of two random variables coming from a bivariate normal distribution with a certain Pearson’s correlation, more general dependencies can be flexibly investigated using copula functions. This can be helpful when the conditional mean of $Y_i$ given $Y_j$ is not linear in $Y_j$. Additional properties of copula models are that they allow an investigation of the dependence structure between the phenotypes separately from the marginal distributions. Also, the marginal distributions can come from different families and not necessarily from the normal distribution. Copula models can be used to make inference about the marginal parameters and to identify markers associated with one or multiple phenotypes. Through the joint modeling of multiple traits, the power of the association test with a given trait can be increased, also if the markers are only associated with one trait. This is of special interest for genetic association studies, and in particular for the analysis of rare genetic variants, where the low power of association tests is one of the main challenges in empirical studies. The potential of C-JAMP to increase the power of association tests is supported by the results of empirical applications of C-JAMP in real-data analyses (Konigorski, Yilmaz & Bull, 2014; Konigorski, Yilmaz, Pischon, 2016). The functions in this package implement C-JAMP for fitting joint models based on the Clayton and 2-parameter copula, of two normally-distributed traits $Y_1, Y_2$ conditional on multiple predictors, and allow obtaining coefficient and standard error estimates of the copula parameters (modeling the dependence between $Y_1, Y_2$) and marginal parameters (modeling the effect of the predictors on $Y_1$ and on $Y_2$), as well as performing Wald-type hypothesis tests of the marginal parameters. Summary functions provide a user-friendly output. In addition, likelihood-ratio tests for testing nested copula models are available. Furthermore, functions are available to generate genetic data, and phenotypic data from bivariate normal distrutions and bivariate distributions based on copula functions. Finally, for genetic association analyses, functions are available to calculate the amount of phenotypic variance that can be explained by the genetic markers. ## Background on copula functions In more detail, a d-dimensional copula can be defined as a function $C:[0,1]^d \to [0,1]$, which is a joint cumulative distribution function with uniform marginal cumulative distribution functions. Hence, $C$ is the distribution of a multivariate random vector, and can be considered independent of the margins. For $Y_1, \dots, Y_d$ and a covariate vector $x$, the joint distribution $F$ of $Y_1, \dots, Y_d$, conditional on $x$, can be constructed by combining the marginal distributions of $Y_1, \dots, Y_d$, $F_1, \dots, F_d$, conditional on $x$, using a copula function $C_\psi$ with dependence parameter(s) $\psi$: $$ F(Y_1, \dots, Y_d|x)= C_\psi (F_1 (Y_1|x), \dots, F_d(Y_d|x)). $$ For continuous marginal distributions, the copula $C_\psi$ is unique and the multivariate distribution can be constructed from the margins in a uniquely defined way (Sklar, 1959). Popular copula functions include the Clayton family $$ C_\phi (u_1, \dots, u_d, \phi) = \left( \sum_{i=1}^d u_i^{-\phi} - (d-1) \right)^{ -\frac{1}{\phi}} $$ with $\phi>0$, and the Gumbel-Hougaard family $$ C_\theta (u_1, \dots, u_d, \theta) = exp\left( - \left[ \sum_{i=1}^d(-log(u_i))^\theta \right]^{\frac{1}{\theta}} \right) $$ with $\theta>1$. A third family which includes both Clayton and Gumbel-Hougaard copula (for $\theta=1$ and $\phi \to 0$) is the 2-paramater copula family $$ C_\psi (u_1, \dots, u_d, \phi, \theta) = \left( \left[ \sum_{i=1}^d \left( u_i^{-\phi}-1 \right)^\theta \right]^{\frac{1}{\theta}} + 1 \right)^{-\frac{1}{\phi}} $$ with $0 \leq u_1, u_2 \leq 1$, and the copula parameters $\psi=(\phi,\theta), \phi>0, \theta \geq 1$, which allows a flexible modeling of both the lower- and upper-tail dependence. For the 2-parameter copula family, Kendall’s tau can be derived as (Joe, 1997) $$ \tau = 1 - \frac{2}{\theta(\phi+2)}. $$ Additional dependence parameters of interest are the lower and upper tail dependence measures $\lambda_L, \lambda_U$, which explain the amount of dependence between extreme values. For the 2-parameter copula family, these dependence measures become (Joe, 1997) $$ \lambda_L=2^{-\frac{1}{\theta\phi}}, \ \lambda_U= 2-2^{\frac{1}{\theta}}.$$ Data $Y_1, Y_2$ can be sampled from the Clayton copula (with standard normal margins) using the `generate_clayton_copula()` function. This uses the following steps to generate standard normal $Y_1, Y_2$ from the Clayton copula $C_\phi (\Phi(Y_1), \Phi(Y_2)) = C_\phi (U_1, U_2)$, where $\Phi$ is the standard normal cumulative distribution function: 1. Generate uniform random variables $U_1, \tilde{U}_2 \sim Unif(0,1)$. 1. Generate $Y_1$ from the inverse standard normal distribution of $U_1$, $Y_1 := \Phi^{-1}(U_1)$. 1. In order to obtain the second variable $Y_2$, use the conditional distribution of $U_2$ given $U_1$, set $\tilde{U}_2 = \frac{\partial C(U_1, U_2)}{\partial U_1}$ and solve for $U_2$. This yields $U_2 = \left( 1 - U_1^{-\phi} \cdot \left( 1 - \tilde{U}_2^{-\frac{\phi}{1 + \phi}} \right) \right)^{-\frac{1}{\phi}}$. 1. Generate $Y_2$ from the inverse standard normal distribution of $U_2$, $Y_2 := \Phi^{-1}(U_2)$. ```{r, echo=FALSE} generate_clayton_copula <- function(n = NULL, phi = NULL) { U1 <- runif(n, min = 0, max = 1) U2 <- runif(n, min = 0, max = 1) Y1 <- qnorm(U1, mean = 0, sd = 1) Y2.help <- (1 - U1^(-phi) * (1 - U2^(-phi/(1 + phi))))^(-1/phi) tau <- phi/(phi + 2) Y2 <- qnorm(Y2.help, mean = 0, sd = 1) phenodata <- data.frame(Y1 = Y1, Y2 = Y2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) } ``` ```{r} # Generate phenotype data from the Clayton copula: set.seed(10) dat1a <- generate_clayton_copula(n = 1000, phi = 0.5) dat1b <- generate_clayton_copula(n = 1000, phi = 2) dat1c <- generate_clayton_copula(n = 1000, phi = 8) par(mfrow = c(1, 3)) plot(dat1a$Y1, dat1a$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.2"))) plot(dat1b$Y1, dat1b$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.5"))) plot(dat1c$Y1, dat1c$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " with ", tau, "=0.8"))) ``` ## Data generation functions In order to generate sample data for simulation studies and to illustrate C-JAMP, different functions are provided. Firstly, the functions `generate_singleton_data()`, `generate_doubleton_data()` and `generate_genodata()` can be used to generate genetic data in the form of single nucleotide variants (SNVs). `generate_singleton_data()` generates singletons (i.e., SNVs with one observed minor allele); `generate_doubleton_data()` generates doubletons (i.e., SNVs with two observed minor alleles), and the function `generate_genodata()` generates $n$ observations of $k$ SNVs with random minor allele frequencies. The minor allele frequencies can be computed using the function `compute_MAF()`. Next, `generate_phenodata_1_simple()`, `generate_phenodata_1()`, `generate_phenodata_2_bvn()` and `generate_phenodata_2_copula()` can be used to generate phenotype data based on SNV input data, covariates, and a specification of the covariate effect sizes. Here, the functions `generate_phenodata_1_simple()` and `generate_phenodata_1()` generate one normally-distributed or binary phenotype $Y$ conditional on provided SNVs and two generated covariates $X_1$, $X_2$. The functions `generate_phenodata_2_bvn()` and `generate_phenodata_2_copula()` generate two phenotypes $Y_1$, $Y_2$ with dependence Kendall's $\tau$ conditional on the provided SNVs and covariates $X_1$, $X_2$ from the bivariate normal distribution or the Clayton copula function with standard normal marginal distributions. `generate_phenodata_2_copula()` is using the function `generate_clayton_copula()` described above. ```{r, echo=FALSE} generate_singleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, rep(0, n_ind - 1)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ``` ```{r, echo=FALSE} generate_doubleton_data <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) helpvec <- c(1, 1, rep(0, n_ind - 2)) for (i in 1:n_SNV) { genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ``` ```{r, echo=FALSE} generate_genodata <- function(n_SNV = 100, n_ind = 1000) { genodata <- data.frame(matrix(nrow = n_ind, ncol = n_SNV)) for (i in 1:n_SNV) { MAFhelp <- round(runif(1, 0, 0.5), 3) n0 <- round((1 - MAFhelp)^2 * n_ind) n2 <- round(MAFhelp^2 * n_ind) n1 <- n_ind - n0 - n2 helpvec <- c(rep(0, n0), rep(1, n1), rep(2, n2)) genodata[, i] <- sample(helpvec, n_ind, replace = F) names(genodata)[i] <- paste("SNV", i, sep = "") } return(genodata) } ``` ```{r, echo=FALSE} compute_MAF <- function(genodata) { MAF <- NULL if (is.null(dim(genodata))) { dat <- genodata[!is.na(genodata)] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF > 0.5) { warning("MAF is larger than 0.5, maybe recode alleles?") } } if (!is.null(dim(genodata))) { for (i in 1:dim(genodata)[2]) { dat <- genodata[, i][!is.na(genodata[, i])] if (!all(unique(dat) %in% c(0, 1, 2))) { stop("SNP has to be supplied as genotypes 0,1,2.") } if (is.na(table(dat)["1"])) { genocount1 <- 0 } if (!is.na(table(dat)["1"])) { genocount1 <- table(dat)["1"][[1]] } if (is.na(table(dat)["2"])) { genocount2 <- 0 } if (!is.na(table(dat)["2"])) { genocount2 <- table(dat)["2"][[1]] } nobs <- length(dat) MAF[i] <- (genocount1/nobs + 2 * genocount2/nobs)/2 if (MAF[i] > 0.5) { warning(paste("MAF of SNV ",i ," is larger than 0.5, maybe recode alleles?",sep="")) } } } names(MAF) <- names(genodata) return(MAF) } ``` ```{r, echo=FALSE} generate_phenodata_1_simple <- function(genodata = NULL, type = "quantitative", b = 0, a = c(0, 0.5, 0.5)) { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- rnorm(n_ind, mean = 0, sd = 1) X2 <- rbinom(n_ind, size = 1, prob = 0.5) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + genodata %*% b + rnorm(n_ind, 0, 1) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * X1 + a[3] * X2 + b * genodata))) Y <- rbinom(n_ind, 1, P) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } ``` ```{r, echo=FALSE} generate_phenodata_1 <- function(genodata = NULL, type = "quantitative", b = 0.6, a = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied") } genodata <- as.data.frame(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.data.frame(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b)) & (!length(b) == 1)) { stop("Genetic effects b has to be of same length as \n the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b)) & (length(b) == 1)) { b <- rep(b, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b <- b[causal_idx] alpha_g <- b * abs(log10(compute_MAF(geno_causal))) # if direction b or c is specified, change direction of effect for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in%help_idx_2)) + 1) * alpha_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g } epsilon1 <- stats::rnorm(n_ind, mean = 0, sd = sigma1) if (type == "quantitative") { Y <- a[1] + a[2] * X1 + a[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y <- as.numeric(Y) } if (type == "binary") { P <- 1/(1 + exp(-(a[1] + a[2] * scale(X1, center = T, scale = F) + a[3] * scale(X2, center = T, scale = F) + geno_causal %*% alpha_g))) Y <- stats::rbinom(n_ind, 1, P) Y <- as.numeric(Y) } phenodata <- data.frame(Y = Y, X1 = X1, X2 = X2) return(phenodata) } ``` ```{r, echo=FALSE} generate_phenodata_2_bvn <- function(genodata = NULL, tau = NULL, b1 = 0, b2 = 0, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5)) { if (!requireNamespace("MASS", quietly = TRUE)) { stop("MASS package needed for this function to work. Please install it.", call. = FALSE) } if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } # generate the two covariates X1 <- rnorm(n_ind, mean = 0, sd = 1) X2 <- rbinom(n_ind, size = 1, prob = 0.5) # set the weight of the nongenetic covariates set the residual variances sigma1 <- 1 sigma2 <- 1 if (is.null(tau)) { stop("Tau has to be provided.") } rho <- sin(tau * pi/2) mu <- c(0, 0) sigma <- matrix(c(sigma1, rho, rho, sigma2), 2, 2) epsilon <- MASS::mvrnorm(n = n_ind, mu = mu, Sigma = sigma) epsilon1 <- epsilon[, 1] epsilon2 <- epsilon[, 2] Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + genodata %*% b1 + epsilon1 Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + genodata %*% b2 + epsilon2 phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) return(phenodata) } ``` ```{r, echo=FALSE} generate_phenodata_2_copula <- function(genodata = NULL, phi = NULL, tau = 0.5, b1 = 0.6, b2 = 0.6, a1 = c(0, 0.5, 0.5), a2 = c(0, 0.5, 0.5), MAF_cutoff = 1, prop_causal = 0.1, direction = "a") { if (is.null(genodata)) { stop("Genotype data has to be supplied.") } genodata <- as.matrix(genodata) genodata <- genodata[stats::complete.cases(genodata),] genodata <- as.matrix(genodata) n_ind <- dim(genodata)[1] n_SNV <- dim(genodata)[2] if ((!n_SNV == length(b1)) & (!n_SNV == length(b1)) & (!length(b1) == 1)) { stop("Genetic effects b1 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b2)) & (!n_SNV == length(b2)) & (!length(b2) == 1)) { stop("Genetic effects b2 has to be of same length \n as the number of provided SNVs or of length 1.") } if ((!n_SNV == length(b1)) & (length(b1) == 1)) { b1 <- rep(b1, n_SNV) } if ((!n_SNV == length(b2)) & (length(b2) == 1)) { b2 <- rep(b2, n_SNV) } X1 <- stats::rnorm(n_ind, mean = 0, sd = 1) X2 <- stats::rbinom(n_ind, size = 1, prob = 0.5) sigma1 <- 1 sigma2 <- 1 causal_idx <- FALSE help_causal_idx_counter <- 0 while (!any(causal_idx)) { # if no causal variants are selected (MAF <= MAF_cutoff), do it again up to 10 times help_causal_idx_counter <- help_causal_idx_counter + 1 if(help_causal_idx_counter == 10){ stop("MAF cutoff too low, no causal SNVs") } help_idx <- sample(1:dim(genodata)[2], ceiling(prop_causal * dim(genodata)[2])) causal_idx <- ((1:dim(genodata)[2] %in% help_idx) & (compute_MAF(genodata) < MAF_cutoff)) } geno_causal <- as.matrix(genodata[, causal_idx]) b1 <- b1[causal_idx] b2 <- b2[causal_idx] alpha_g <- b1 * abs(log10(compute_MAF(geno_causal))) beta_g <- b2 * abs(log10(compute_MAF(geno_causal))) # if b or c is specified, change effect direction for some variants if (direction == "b") { help_idx_2 <- sample(1:dim(geno_causal)[2], round(0.2 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_2)) + 1) * beta_g } if (direction == "c") { help_idx_3 <- sample(1:dim(geno_causal)[2], round(0.5 * dim(geno_causal)[2])) alpha_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * alpha_g beta_g <- (-1)^(as.numeric(!(1:dim(geno_causal)[2] %in% help_idx_3)) + 1) * beta_g } # compute copula parameter between the two phenotypes from tau if tau is given if (!is.null(tau)) { phi <- (2 * tau)/(1 - tau) } res_copula <- generate_clayton_copula(n = n_ind, phi = phi) epsilon1 <- res_copula$Y1 epsilon2 <- res_copula$Y2 if (is.null(tau)) { tau <- phi/(phi + 2) } Y1 <- a1[1] + a1[2] * X1 + a1[3] * X2 + geno_causal %*% alpha_g + epsilon1 Y1 <- as.numeric(Y1) Y2 <- a2[1] + a2[2] * X1 + a2[3] * X2 + geno_causal %*% beta_g + epsilon2 Y2 <- as.numeric(Y2) phenodata <- data.frame(Y1 = Y1, Y2 = Y2, X1 = X1, X2 = X2) print(paste("Kendall's tau between Y1, Y2 = ", tau, sep="")) return(phenodata) } ``` ```{r} # Generate genetic data: set.seed(10) genodata <- generate_genodata(n_SNV = 20, n_ind = 1000) compute_MAF(genodata) # Generate phenotype data from the bivariate normal distribution given covariates: phenodata_bvn <- generate_phenodata_2_bvn(genodata = genodata, tau = 0.5, b1 = 1, b2 = 2) plot(phenodata_bvn$Y1, phenodata_bvn$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of bivariate normal ", Y[1], ", ", Y[2], " with ", tau, "=0.5"))) # Generate phenotype data from the Clayton copula given covariates: phenodata <- generate_phenodata_2_copula(genodata = genodata$SNV1, MAF_cutoff = 1, prop_causal = 1, tau = 0.5, b1 = 0.3, b2 = 0.3) plot(phenodata$Y1, phenodata$Y2, xlab = "Y1", ylab = "Y2", main = expression(paste("Scatterplot of ", Y[1], ", ", Y[2], " from the Clayton copula with ", tau, "=0.5"))) ``` For the analysis of genetic associations with the phenotypes, the amount of variability in the phenotypes that can be explained by the SNVs might be of interest. This can be computed based on four different approaches using the function `compute_expl_var()` (Laird & Lange, 2011), which is described in more detail in the help pages of the function. ```{r, echo=FALSE} compute_expl_var <- function(genodata = NULL, phenodata = NULL, type = "Rsquared_unadj", causal_idx = NULL, effect_causal = NULL) { ExplVar <- NULL if (is.null(phenodata) | is.null(genodata)) { stop("Genodata and phenodata have to be supplied.") } if (!dim(genodata)[1] == length(phenodata)) { stop("Number of observations in genodata and phenodata has to be the same.") } if (class(genodata) == "data.frame") { if (!all(sapply(genodata, is.numeric))) { genodata <- as.data.frame(data.matrix(genodata)) } } if (is.null(dim(genodata))) { if (!is.numeric(genodata)) { stop("genodata has to be numeric.") } } if (class(phenodata) == "data.frame") { if (!all(sapply(phenodata, is.numeric))) { phenodata <- as.data.frame(data.matrix(phenodata)) warning("phenodata contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(dim(phenodata))) { if (!is.numeric(phenodata)) { stop("phenodata has to be numeric.") } } if (is.null(causal_idx)) { warning("A vector indicating the causal SNVs is not supplied \n so the estimate of explained variance is based on all SNVs.") } if (any(type %in% c("MAF_based", "MAF_based_Y_adjusted")) & is.null(effect_causal)) { stop("A vector indicating the genetic effect sizes of the causal SNVs has \n to be supplied for the MAF_based and MAF_based_Y_adjusted approach.") } if (!is.null(causal_idx)) { genodata <- as.data.frame(genodata[, causal_idx]) } MAF_causal <- compute_MAF(genodata) phenodata <- as.data.frame(phenodata) dat <- as.data.frame(append(phenodata, genodata)) dat <- dat[complete.cases(dat),] names(dat)[1] <- "Y" ExplVar <- list() if ("Rsquared_unadj" %in% type) { ExplVar$Rsquared_unadj <- summary(lm(Y ~ ., data = dat))$r.squared } if ("Rsquared_adj" %in% type) { ExplVar$Rsquared_adj <- summary(lm(Y ~ ., data = dat))$adj.r.squared } if ("MAF_based" %in% type) { ExplVar$MAF_based <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2) } if ("MAF_based_Y_adjusted" %in% type) { ExplVar$MAF_based_Y_adjusted <- sum(2 * MAF_causal * (1 - MAF_causal) * effect_causal^2)/var(dat$Y) } return(ExplVar) } ``` ```{r} compute_expl_var(genodata = genodata, phenodata = phenodata$Y1, type = c("Rsquared_unadj", "Rsquared_adj", "MAF_based", "MAF_based_Y_adjusted"), causal_idx = rep(TRUE,20), effect_causal = c(0.3 * abs(log10(compute_MAF(genodata$SNV1))), rep(0,19))) ``` ## C-JAMP: Copula-based joint analysis of multiple phenotypes C-JAMP is implemented for the joint analysis of two phenotypes $Y_1, Y_2$ conditional on one or multiple predictors $x$ with linear marginal models. Functions are available to fit the joint model $$ F(Y_1, Y_2|x)= C_\psi (F_1 (Y_1|x), F_2 (Y_2|x)) $$ for the Clayton and 2-parameter copula, with marginal models $$Y_1 = \alpha^T X + \epsilon_1, \epsilon_1 \sim N(0,\sigma_1^2 ) $$ $$Y_2 = \beta^T X + \epsilon_2, \epsilon_2 \sim N(0,\sigma_2^2 ). $$ Maximum likelihood estimates for all parameters $(\psi, \alpha, \beta, \sigma_1, \sigma_2)$ can be obtained using the function `get_estimates_naive()`, which is based on the ´lm()´ function. ```{r, echo=FALSE} get_estimates_naive <- function(Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, copula_param = "both") { if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } dataframe_Y1 <- data.frame(Y1 = Y1) dataframe_Y2 <- data.frame(Y2 = Y2) n_ind <- dim(dataframe_Y1)[1] if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y1)) { predictors_Y1 <- data.frame(predictors_Y1) } if (!is.null(predictors_Y2)) { predictors_Y2 <- data.frame(predictors_Y2) } if (!n_ind == dim(dataframe_Y2)[1]) { stop("Variables must have same length.") } if (!is.null(predictors_Y1)) { if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y2)) { if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } } if (!is.null(predictors_Y1)) { dataframe_Y1 <- cbind(dataframe_Y1, predictors_Y1) } if (!is.null(predictors_Y2)) { dataframe_Y2 <- cbind(dataframe_Y2, predictors_Y2) } res_Y1 <- lm(Y1 ~ ., data = dataframe_Y1) res_Y2 <- lm(Y2 ~ ., data = dataframe_Y2) param_Y1_sigma <- log(sd(res_Y1$residuals, na.rm = T)) #param_Y1_sigma <- log(sd(Y1, na.rm = T)) names(param_Y1_sigma) <- "Y1_log_sigma" param_Y2_sigma <- log(sd(res_Y2$residuals, na.rm = T)) #param_Y2_sigma <- log(sd(Y2, na.rm = T)) names(param_Y2_sigma) <- "Y2_log_sigma" tau <- cor(Y1, Y2, use = "complete.obs", method = c("kendall")) if (tau == 0) { tau <- 1e-04 } # to avoid technical breakdown of function log_phi <- log(2 * tau/(1 - tau)) log_theta <- log((1/(1 - tau)) - 1) param_Y1_Y2 <- c(log_phi, log_theta) names(param_Y1_Y2) <- c("log_phi", "log_theta_minus1") if (copula_param == "phi") { param_Y1_Y2 <- param_Y1_Y2[1] } if (copula_param == "theta") { param_Y1_Y2 <- param_Y1_Y2[2] } param_Y1_predictors <- res_Y1$coefficients names(param_Y1_predictors) <- paste("Y1_", names(param_Y1_predictors), sep = "") param_Y2_predictors <- res_Y2$coefficients names(param_Y2_predictors) <- paste("Y2_", names(param_Y2_predictors), sep = "") if (any(is.na(param_Y1_Y2))) { warning("One or both dependence parameters could not be estimated.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { warning("One or both marginal variances could not be estimated.") } if (any(is.na(param_Y1_predictors)) | any(is.na(param_Y2_predictors))) { warning("One or more marginal parameters could not be estimated.") } estimates <- c(param_Y1_Y2, param_Y1_sigma, param_Y2_sigma, param_Y1_predictors, param_Y2_predictors) return(estimates) } ``` ```{r} predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") ``` For these or any other parameter estimates, the log-likelihood (or rather the minus log-likelihood) of the copula model can be computed with the function `minusloglik()` for the Clayton and 2-parameter copula: ```{r, echo=FALSE} minusloglik <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, parameters = NULL) { if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (!is.null(predictors_Y1)) { n_Y1_pred <- dim(predictors_Y1)[2] } else { n_Y1_pred <- 0 } if (!is.null(predictors_Y2)) { n_Y2_pred <- dim(predictors_Y2)[2] } else { n_Y2_pred <- 0 } if (copula == "Clayton") { param_Y1_Y2 <- parameters[1] n_dep <- 1 if (!names(param_Y1_Y2) == "log_phi") { stop("Estimate for phi is not provided.") } } if (copula == "2param") { param_Y1_Y2 <- parameters[1:2] n_dep <- 2 if (!identical(names(param_Y1_Y2), c("log_phi", "log_theta_minus1"))) { stop("Estimates for phi/theta are not provided.") } } param_Y1_sigma <- parameters[n_dep + 1] param_Y2_sigma <- parameters[n_dep + 2] no_p <- length(parameters) param_Y1_predictors <- parameters[(n_dep + 3):(n_dep + 3 + n_Y1_pred)] param_Y2_predictors <- parameters[(no_p - n_Y2_pred):no_p] if (is.null(Y1) | is.null(Y2)) { stop("Both Y1 and Y2 have to be supplied.") } n_ind <- length(Y1) if (!is.null(predictors_Y1)) { predictors_Y1 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y1) } else { predictors_Y1 <- data.frame(One = rep(1, n_ind)) } if (!is.null(predictors_Y2)) { predictors_Y2 <- cbind(data.frame(One = rep(1, n_ind)), predictors_Y2) } else { predictors_Y2 <- data.frame(One = rep(1, n_ind)) } if (!n_ind == length(Y2)) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y1)[1]) { stop("Variables must have same length.") } if (!n_ind == dim(predictors_Y2)[1]) { stop("Variables must have same length.") } if (is.null(param_Y1_Y2) | any(is.na(param_Y1_Y2))) { stop("Estimate(s) of dependence betwee Y1 and Y2 is (are) not provided.") } if (any(is.na(param_Y1_sigma)) | any(is.na(param_Y2_sigma))) { stop("One or both marginal variances are not provided") } if (any(is.na(param_Y1_predictors))) { warning(paste("Effect estimate of ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " on Y1 is missing. Variable ", names(predictors_Y1)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y1 <- predictors_Y1[, !is.na(param_Y1_predictors)] param_Y1_predictors <- param_Y1_predictors[!is.na(param_Y1_predictors)] } if (any(is.na(param_Y2_predictors))) { warning(paste("Effect estimates of ", names(predictors_Y2)[which(is.na(param_Y2_predictors))], " on Y2 is missing. Variable ", names(predictors_Y2)[which(is.na(param_Y1_predictors))], " is excluded from the analysis.", sep = "")) predictors_Y2 <- predictors_Y2[, !is.na(param_Y2_predictors)] param_Y2_predictors <- param_Y2_predictors[!is.na(param_Y2_predictors)] } if (copula == "Clayton") { phi <- exp(param_Y1_Y2[1]) } else if (copula == "2param") { phi <- exp(param_Y1_Y2[1]) theta <- exp(param_Y1_Y2[2]) + 1 } else { stop("copula has to be specified") } minusloglik <- 0 predictors_Y1 <- as.matrix(predictors_Y1) predictors_Y2 <- as.matrix(predictors_Y2) for (i in 1:n_ind) { lik.pt1.1 <- pnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt1.2 <- pnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) lik.pt2 <- dnorm(Y1[i], mean = as.numeric(param_Y1_predictors) %*% predictors_Y1[i, ], sd = exp(as.numeric(param_Y1_sigma))) lik.pt3 <- dnorm(Y2[i], mean = as.numeric(param_Y2_predictors) %*% predictors_Y2[i, ], sd = exp(as.numeric(param_Y2_sigma))) if (copula == "Clayton") { fun <- ((lik.pt1.1)^(-phi) - 1) + ((lik.pt1.2)^(-phi) - 1) joints <- (fun + 1)^(-1/phi) d1.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun + 1)^(-1/phi - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1) * (fun + 1)^(1/phi + 1) lik <- dd.joints * (fun * (1 + phi) * (fun + 1)^(-1)) } if (copula == "2param") { fun <- ((lik.pt1.1)^(-phi) - 1)^theta + ((lik.pt1.2)^(-phi) - 1)^theta joints <- (fun^(1/theta) + 1)^(-1/phi) d1.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.1)^(-phi) - 1)^(theta - 1) * (lik.pt1.1)^(-phi - 1) * (-lik.pt2) d2.joints <- (fun^(1/theta) + 1)^(-1/phi - 1) * fun^(1/theta - 1) * ((lik.pt1.2)^(-phi) - 1)^(theta - 1) * (lik.pt1.2)^(-phi - 1) * (-lik.pt3) dd.joints <- d1.joints * d2.joints * fun^(-1/theta) * (fun^(1/theta) + 1)^(1/phi + 1) lik <- dd.joints * ((theta - 1) * phi + fun^(1/theta) * (1 + phi) * (fun^(1/theta) + 1)^(-1)) } minusloglik <- minusloglik - log(lik) } return(as.numeric(minusloglik)) } ``` ```{r} predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:5]) estimates <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates, copula = "2param") ``` It should be noted that the `minusloglik()` function (and the `cjamp()`, `cjamp_loop()` functions below) assume quantitative predictors and use an additive model. That means that for the analysis of categorical predictors with more than 2 levels, dummy variables have to be created beforehand. Accordingly, if single nucleotide variants (SNVs) are included as predictors, the computation is based on an additive genetic model if SNVs are provided as 0-1-2 genotypes and on a dominant model if SNVs are provided as 0-1 genotypes. The `lrt_copula()` can be used to test the model fit of different nested copula models with the same marginal models. For this, likelihood ratio tests are performed. In more detail, to test the fit of the 1-parameter Clayton copula model fit versus the 2-parameter copula, i.e. $H_0: \phi \to 0$, the likelihood ratio test statistic $$ logLR = 2 \cdot \left(L\left(\hat{\alpha},\hat{\beta},\hat{\psi}\right) - L\left(\hat{\alpha}(\psi_0),\hat{\beta}(\psi_0),\hat{\psi} \right)\right)$$ can be used, where $\hat{\psi}=(\hat{\phi}, \hat{\theta})$, $\hat{\psi_0}=\left(\hat{\phi}(\theta=1), 1\right)$, see Yilmaz & Lawless (2011). Here, $\hat{\alpha}(\psi_0)$ and $\hat{\beta}(\psi_0)$ are the maximum likelihood estimates of $\alpha$ and $\beta$ under the null model $\psi=\psi_0$. P-values are obtained by using that $logLR$ is asymptotically distributed as $0.5 + 0.5\chi_1^2$ under the null hypothesis $\psi=\psi_0$ and under the assumption that other free parameters in $\psi_0$ don’t lie on the boundary of the parameter space (Self & Liang, 1987). ```{r, echo=FALSE} lrt_copula <- function(minlogl_null = NULL, minlogl_altern = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern)) { stop("minlogl_null and minlogl_altern have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - (0.5 + 0.5 * pchisq(chisq, df = 1)) return(list(chisq = chisq, pval = pval)) } ``` ```{r} # Example: Test whether 2-parameter copula model has a better # model fit compared to Clayton copula (no). predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) estimates_c <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "phi") minusloglik_Clayton <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates_c, copula = "Clayton") estimates_2p <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, copula_param = "both") minusloglik_2param <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors, predictors_Y2 = predictors, parameters = estimates_2p, copula = "2param") lrt_copula(minusloglik_Clayton, minusloglik_2param) ``` Log-likelihood ratio tests of marginal parameters within the same copula model can be performed using the `lrt_param()` function: ```{r, echo=FALSE} lrt_param <- function(minlogl_null = NULL, minlogl_altern = NULL, df = NULL) { if (is.null(minlogl_null) | is.null(minlogl_altern) | is.null(df)) { stop("minlogl_null, minlogl_altern and df have to be supplied.") } chisq <- 2 * minlogl_null - 2 * minlogl_altern pval <- 1 - pchisq(chisq, df = df) return(list(chisq = chisq, pval = pval)) } ``` ```{r} # Example: Test marginal parameters (alternative model has better fit). predictors_1 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2) estimates_1 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_1, predictors_Y2 = predictors_1, copula = "phi") minusloglik_1 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_1, predictors_Y2 = predictors_1, parameters = estimates_1, copula = "Clayton") predictors_2 <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, SNV = genodata$SNV1) estimates_2 <- get_estimates_naive(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_2, predictors_Y2 = predictors_2, copula = "phi") minusloglik_2 <- minusloglik(Y1 = phenodata$Y1, Y2 = phenodata$Y2, predictors_Y1 = predictors_2, predictors_Y2 = predictors_2, parameters = estimates_2, copula = "Clayton") lrt_param(minusloglik_1, minusloglik_2, df=2) ``` Finally, to obtain maximum likelihood estimates of the parameters $(\psi, \alpha, \beta, \sigma_1, \sigma_2)$ as well as standard error estimates under the Clayton or 2-parameter copula models, the function `cjamp()` can be used. `cjamp()` uses the `optimx()` function in the optimx package to maximize the log-likelihood function (i.e., minimize `minusloglik()`). For this, the BFGS optimization method is recommended. In order to deal with convergence problems, several checks are built-in, and different starting values for the optimization algorithm are automatically tried. Standard error estimates of the parameter estimates are obtained from the observed inverse information matrix. Finally, p-values are computed for the marginal parameter estimates from hypothesis tests of the absence of effects of each predictor on each phenotype in the marginal models. ```{r, echo=FALSE} cjamp <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors_Y1 = NULL, predictors_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (pval_est & !SE_est) { stop("SE_est has to be TRUE to compute p-values.") } if (!requireNamespace("optimx", quietly = TRUE)) { stop("Package optimx needed for this function to work. Please install it.", call. = FALSE) } if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (cor(Y1, Y2, use = "complete.obs", method = "kendall") < 0) { Y2 <- -Y2 warning("Dependence between Y1, Y2 is negative but copulas require positive dependence. \n Hence Y2 is transformed to -Y2 and point estimates for Y2 are in inverse direction.") } if (copula == "Clayton") { n_dep <- 1 copula_param = "phi" } if (copula == "2param") { n_dep <- 2 copula_param = "both" } if ((!class(predictors_Y1) == "data.frame" & !is.null(predictors_Y1)) | (!class(predictors_Y2) == "data.frame" & !is.null(predictors_Y2))) { stop("predictors_Y1 and predictors_Y2 have to be a dataframe or NULL.") } if (class(predictors_Y1) == "data.frame") { if (!all(sapply(predictors_Y1, is.numeric))) { predictors_Y1 <- as.data.frame(data.matrix(predictors_Y1)) warning("predictors_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(predictors_Y2) == "data.frame") { if (!all(sapply(predictors_Y2, is.numeric))) { predictors_Y2 <- as.data.frame(data.matrix(predictors_Y2)) warning("predictors_Y2 contains non-numeric Variables, which have automatically been transformed.") } } if (is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] n_pred <- 0 } if (!is.null(predictors_Y1) & is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y1)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] } if (is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y2)[2] } if (!is.null(predictors_Y1) & !is.null(predictors_Y2)) { idx <- (!is.na(Y1) & !is.na(Y2) & complete.cases(predictors_Y1) & complete.cases(predictors_Y2)) Y1 <- Y1[idx] Y2 <- Y2[idx] predictors_Y1 <- predictors_Y1[idx, , drop = FALSE] predictors_Y2 <- predictors_Y2[idx, , drop = FALSE] if (qr(predictors_Y1)$rank < dim(predictors_Y1)[2]) { stop("Complete cases matrix of predictors_Y1 doesn't have full rank.") } if (qr(predictors_Y2)$rank < dim(predictors_Y2)[2]) { stop("Complete cases matrix of predictors_Y2 doesn't have full rank.") } n_pred <- dim(predictors_Y1)[2] + dim(predictors_Y2)[2] } if (scale_var) { predictors_Y1 <- data.frame(lapply(predictors_Y1, scale)) predictors_Y2 <- data.frame(lapply(predictors_Y2, scale)) } convcode <- 1 kkt <- c(FALSE, FALSE) n_iter <- 1 helpnum <- 0.4 while (!(convcode == 0 & all(kkt) & !any(is.na(kkt))) & (n_iter <= n_iter_max)) { startvalues <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) - helpnum names_pred <- names(startvalues[(n_dep + 3):length(startvalues)]) if (minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues) == Inf | is.na(minusloglik(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, parameters = startvalues))) { helpnum <- (-1)^rbinom(1, 1, 0.5) * runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 next } res <- optimx::optimx(par = startvalues, fn = minusloglik, Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula = copula, method = optim_method, hessian = TRUE, control = list(trace = trace, kkt2tol = kkt2tol)) convcode <- res$convcode kkt <- c(res$kkt1, res$kkt2) helpnum <- (-1)^rbinom(1, 1, 0.5) * runif(1, min = 0.1, max = 1) n_iter <- n_iter + 1 } names(convcode) <- "convcode" names(kkt) <- c("KKT1", "KKT2") maxloglik <- NULL if (!convcode == 0) { warning("In model with predictors \n", names_pred, ": \n Optimization doesn't seem to be converged.", "\n SE estimates and pvalues are not computed. Please check.") } if (!all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n KKT conditions are not satistified.", " \n SE estimates and pvalues are not computed. Please check.") } if (!convcode == 0 | !all(kkt) | any(is.na(kkt))) { warning("In model with predictors \n", names_pred, ": \n Naive parameter estimates are computed from separate marginal models.") point_estimates <- get_estimates_naive(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, copula_param = copula_param) point_estimates <- as.list(point_estimates) if (copula == "Clayton") { phi <- exp(point_estimates$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(point_estimates$log_phi) theta <- exp(point_estimates$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates[(n_dep + 1):length(point_estimates)], phi, theta, tau, lambda_l, lambda_u) point_estimates[[1]] <- exp(point_estimates[[1]]) point_estimates[[2]] <- exp(point_estimates[[2]]) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (convcode == 0 & all(kkt) & !any(is.na(kkt))) { maxloglik <- res$value names(maxloglik) <- "maxloglik" point_estimates <- res[(n_dep + 1):(n_dep + n_pred + 4)] point_estimates[1:2] <- exp(point_estimates[1:2]) if (copula == "Clayton") { phi <- exp(res$log_phi) tau <- phi/(2 + phi) theta <- lambda_l <- lambda_u <- NA } if (copula == "2param") { phi <- exp(res$log_phi) theta <- exp(res$log_theta_minus1) + 1 tau <- 1 - (2/(theta * (phi + 2))) lambda_l <- 2^(-1/(theta * phi)) lambda_u <- 2 - 2^(1/theta) } point_estimates <- c(point_estimates, phi, theta, tau, lambda_l, lambda_u) names(point_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } SE_estimates <- NULL if (SE_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { SE_estimates <- vector(mode = "numeric", length = (n_pred + 4)) SE_estimates[1] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 1] * (point_estimates$Y1_sigma^2)) SE_estimates[2] <- sqrt(diag(solve(attributes(res)$details[[3]]))[n_dep + 2] * (point_estimates$Y2_sigma^2)) SE_estimates[3:length(SE_estimates)] <- sqrt(diag(solve(attributes(res)$details[[3]]))[(n_dep + 3):(n_dep + n_pred + 4)]) if (copula == "Clayton") { helpvar1 <- 2 * phi/((phi + 2)^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) tau_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (helpvar1^2)) theta_SE <- lambda_l_SE <- lambda_u_SE <- NA } if (copula == "2param") { helpvar3.1 <- 2 * phi/(theta * (phi + 2)^2) helpvar3.2 <- 2 * (theta - 1)/(theta^2 * (phi + 2)) helpvar3.3 <- (2^(-1/(theta * phi))) * (log(2)/(theta * phi)) helpvar3.4 <- (2^(-1/(theta * phi))) * (log(2) * (theta - 1)/(theta^2 * phi)) helpvar3.5 <- (2^(1/theta)) * ((theta - 1) * log(2)/theta^2) phi_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[1] * (phi^2)) theta_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * ((theta - 1)^2)) tau_SE <- sqrt(t(c(helpvar3.1, helpvar3.2)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.1, helpvar3.2)) lambda_l_SE <- sqrt(t(c(helpvar3.3, helpvar3.4)) %*% solve(attributes(res)$details[[3]])[1:2, 1:2] %*% c(helpvar3.3, helpvar3.4)) lambda_u_SE <- sqrt(diag(solve(attributes(res)$details[[3]]))[2] * helpvar3.5^2) } SE_estimates <- c(SE_estimates, phi_SE, theta_SE, tau_SE, lambda_l_SE, lambda_u_SE) names(SE_estimates) <- c("Y1_sigma", "Y2_sigma", names_pred, "phi", "theta", "tau", "lambda_l", "lambda_u") } if (is.null(SE_estimates)){ SE_estimates <- rep(NA, length(point_estimates)) } pval <- NULL point_estimates <- unlist(point_estimates) if (pval_est & convcode == 0 & all(kkt) & !any(is.na(kkt))) { pval <- vector(mode = "numeric", length = (n_pred + 2)) pval <- 2 * pnorm(as.numeric(-abs(point_estimates[3:(n_pred + 4)]/ SE_estimates[3:(n_pred + 4)]))) names(pval) <- names_pred } if (is.null(pval)){ pval <- rep(NA, (n_pred + 2)) } output <- list(point_estimates = point_estimates, SE_estimates = SE_estimates, pval = pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates", "Parameter standard error estimates", "Parameter p-values", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } ``` ```{r} # Restrict example to sample size 100 to decrease running time: predictors <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2, genodata[, 1:3])[1:100,] cjamp_res <- cjamp(copula = "2param", Y1 = phenodata$Y1[1:100], Y2 = phenodata$Y2[1:100], predictors_Y1 = predictors, predictors_Y2 = predictors, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) cjamp_res ``` If the goal is to test a large number of predictors in the same marginal models (such as in genetic association studies), the wrapper function `cjamp_loop()` provides an easy use of the `cjamp()` function and only extracts the coefficient and standard error estimates as well as the p-values for the predictor(s) of interest, and not for all other covariates. ```{r, echo=FALSE} cjamp_loop <- function(copula = "Clayton", Y1 = NULL, Y2 = NULL, predictors = NULL, covariates_Y1 = NULL, covariates_Y2 = NULL, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1e-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) { if (is.null(Y1) | is.null(Y2)) { stop("Y1 and Y2 have to be supplied.") } if (is.null(predictors)) { stop("At least one predictor has to be supplied.") } if (!class(predictors) == "data.frame") { stop("Predictors has to be a dataframe.") } if (!all(sapply(predictors, is.numeric))) { predictors <- as.data.frame(data.matrix(predictors)) warning("predictors contains non-numeric Variables, which have automatically been transformed.") } if ((!class(covariates_Y1) == "data.frame" & !is.null(covariates_Y1)) | (!class(covariates_Y2) == "data.frame" & !is.null(covariates_Y2))) { stop("covariates_Y1 and covariates_Y2 have to be a dataframe or NULL.") } if (class(covariates_Y1) == "data.frame") { if (!all(sapply(covariates_Y1, is.numeric))) { covariates_Y1 <- as.data.frame(data.matrix(covariates_Y1)) warning("covariates_Y1 contains non-numeric Variables, which have automatically been transformed.") } } if (class(covariates_Y2) == "data.frame") { if (!all(sapply(covariates_Y2, is.numeric))) { covariates_Y2 <- as.data.frame(data.matrix(covariates_Y2)) warning("covariates_Y2 contains non-numeric Variables, which have automatically been transformed.") } } N <- dim(predictors)[2] Y1_point_estimates <- Y1_SE_estimates <- Y1_pval <- NULL Y2_point_estimates <- Y2_SE_estimates <- Y2_pval <- NULL convcode <- kkt <- maxloglik <- NULL for (i in 1:N) { names_pred_i <- names(predictors)[i] predictors_Y1 <- predictors_Y2 <- predictors[, i, drop = FALSE] if (!is.null(covariates_Y1)) { predictors_Y1 <- cbind(predictors_Y1, as.data.frame(covariates_Y1)) } if (!is.null(covariates_Y2)) { predictors_Y2 <- cbind(predictors_Y2, as.data.frame(covariates_Y2)) } n_pred_Y1 <- dim(predictors_Y1)[2] n_pred_Y2 <- dim(predictors_Y2)[2] results <- cjamp(Y1 = Y1, Y2 = Y2, predictors_Y1 = predictors_Y1, predictors_Y2 = predictors_Y2, scale_var = scale_var, copula = copula, optim_method = optim_method, trace = trace, kkt2tol = kkt2tol, SE_est = SE_est, pval_est = pval_est, n_iter_max = n_iter_max) Y1_point_estimates[i] <- as.numeric(results[[1]][4]) Y2_point_estimates[i] <- as.numeric(results[[1]][5 + n_pred_Y1]) Y1_SE_estimates[i] <- results[[2]][4] Y2_SE_estimates[i] <- results[[2]][5 + n_pred_Y1] Y1_pval[i] <- results[[3]][2] Y2_pval[i] <- results[[3]][3 + n_pred_Y1] names(Y1_point_estimates)[i] <- names(Y2_point_estimates)[i] <- names_pred_i names(Y1_SE_estimates)[i] <- names(Y2_SE_estimates)[i] <- names_pred_i names(Y1_pval)[i] <- names(Y2_pval)[i] <- names_pred_i convcode[i] <- results[[4]] kkt[i] <- all(results[[5]]) maxloglik[i] <- results[[6]] } output <- list(Y1_point_estimates = Y1_point_estimates, Y2_point_estimates = Y2_point_estimates, Y1_SE_estimates = Y1_SE_estimates, Y2_SE_estimates = Y2_SE_estimates, Y1_pval = Y1_pval, Y2_pval = Y2_pval, convcode = convcode, kkt = kkt, maxloglik = maxloglik) names(output) <- c("Parameter point estimates for effects of predictors on Y1", "Parameter point estimates for effects of predictors on Y2", "Parameter standard error estimates for effects on Y1", "Parameter standard error estimates for effects on Y2", "Parameter p-values for effects of predictors on Y1", "Parameter p-values for effects of predictors on Y2", "Convergence code of optimx function", "Karush-Kuhn-Tucker conditions 1 and 2", "Maximum log-likelihood") class(output) <- "cjamp" return(output) } ``` ```{r} # Restrict example to sample size 100 to decrease running time: covariates <- data.frame(X1 = phenodata$X1, X2 = phenodata$X2)[1:100,] predictors <- genodata[1:100,1:5] cjamp_loop_res <- cjamp_loop(copula = "Clayton", Y1 = phenodata$Y1[1:100], Y2 = phenodata$Y2[1:100], predictors = predictors, covariates_Y1 = covariates, covariates_Y2 = covariates, scale_var = FALSE, optim_method = "BFGS", trace = 0, kkt2tol = 1E-16, SE_est = TRUE, pval_est = TRUE, n_iter_max = 10) cjamp_loop_res ``` Both `cjamp()` and `cjamp_loop()` return `cjamp` objects as output, so that the `summary.cjamp()` function can be used through the generic `summary()` to provide a reader-friendly formatted output of the results. ```{r, echo=FALSE} summary.cjamp <- function(results = NULL) { if (is.null(results) | !class(results)=="cjamp") { stop("cjamp object has to be supplied.") } # for input from cjamp function: if ("Parameter point estimates" %in% names(results)) { length_res <- length(results$"Parameter p-values") res_out <- data.frame(point_estimates = results$"Parameter point estimates"[3:(length_res+2)], SE_estimates = results$"Parameter standard error estimates"[3:(length_res+2)], pvalues = results$"Parameter p-values") print(paste("C-JAMP estimates of marginal parameters.")) print(res_out) } # for input from cjamp_loop function: if ("Parameter p-values for effects of predictors on Y1" %in% names(results)) { res_out_1 <- data.frame(point_estimates = results$"Parameter point estimates for effects of predictors on Y1", SE_estimates = results$"Parameter standard error estimates for effects on Y1", pvalues = results$"Parameter p-values for effects of predictors on Y1") rownames(res_out_1) <- paste("Y1", rownames(res_out_1), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y1.")) print(res_out_1) res_out_2 <- data.frame(point_estimates = results$"Parameter point estimates for effects of predictors on Y2", SE_estimates = results$"Parameter standard error estimates for effects on Y2", pvalues = results$"Parameter p-values for effects of predictors on Y2") rownames(res_out_2) <- paste("Y2", rownames(res_out_2), sep = "_") print(paste("C-JAMP estimates of marginal parameters on Y2.")) print(res_out_2) res_out <- data.frame(rbind(res_out_1, res_out_2)) } invisible(res_out) } ``` ```{r} # Summary of regular cjamp function summary(cjamp_res) # Summary of looped cjamp function summary(cjamp_loop_res) ``` ## References Joe H (1997). Multivariate models and multivariate dependence concepts. London: Chapman & Hall. Konigorski S, Yilmaz YE, Bull SB (2014). Bivariate genetic association analysis of systolic and diastolic blood pressure by copula models. BMC Proc, 8(Suppl 1): S72. Konigorski S, Yilmaz YE, Pischon T (2016). Genetic association analysis based on a joint model of gene expression and blood pressure. BMC Proc, 10(Suppl 7): 289-294. Laird NM, Lange C (2011). The fundamentals of modern statistical genetics. New York: Springer. Nelsen RB (2006). An introduction to copulas. Springer, New York. Sklar A (1959). Fonctions de répartition à n dimensions et leurs marges. Publications de l’Institut de statistique de l’Université de Paris 8: 229–231. Self GS, Liang KY (1987). Asymptotic properties of maximum likelihood estimators and likelihood ratio tests under nonstandard conditions. J Am Stat Assoc, 82: 605–610. Yilmaz YE, Lawless JF (2011). Likelihood ratio procedures and tests of fit in parametric and semiparametric copula models with censored data. Lifetime Data Anal, 17(3): 386-408.
/scratch/gouwar.j/cran-all/cranData/CJAMP/vignettes/cjamp.Rmd
########### Use PC Scores to select joint rank based on cancor ################## #' Permutation Test for Joint Rank in CJIVE #' #' @description Conducts the permutation test for the number of joint components as described in CJIVE manuscript. Briefly, canonical correlations (CC) between principal component #' vectors of the data are obtained (PC). Then for 1:nperms, the rows of one data set are permuted and CCs between PC vectors are calculated, retaining #' the maximum CC. These maximum CCs form a null distribution against which the original CCs are tested. The number of original CCs exceeding the (1-alpha)^th #' percentile is the returned as the joint rank. #' #' @param dat.blocks a list of two matrices with samples along rows and features along columns, which contain data on the same n individuals/sampling units #' @param signal.ranks a vector of length two which contains the rank for the signal within each data block. The rank corresponds to the number of principal #' components (PCs) to be retained within each data block. If NULL, the ranks are determined by the parameter 'perc.var.' Default is NULL #' @param nperms integer value indicating the number of permutations that should be performed #' @param perc.var numeric value of either a scalar or of length 2: an alternative to signal.ranks that allows specification of signal ranks based on the #' desired proportion of total variation to be retained in each data block. #' For perc.var = p (where 0<p<1), rank is determined as the minimum number of eigenvalues whose cumulative sum is at least p*(total sum of eigenvalues). #' Default is 0.95 (i.e. 95\% of total variation preserved for each data block). For p=c(p1,p2) pk is used to determine the rank of block k #' @param alpha nominal type-I error rate #' @param center logical (TRUE/FALSE) indicating whether data should be column-centered prior to testing. Default is TRUE #' @return The Frobenius norm of the matrix X, calculated as the sum of square entries in X #' @export #' perm.jntrank <- function(dat.blocks, signal.ranks = NULL, nperms = 500, perc.var = 0.95, alpha = 0.05, center = TRUE){ n.r.1 = nrow(dat.blocks[[1]]) n.r.2 = nrow(dat.blocks[[2]]) if(n.r.1 != n.r.2){stop("The number of rows in each data matrix must match")} n = n.r.1 K = length(dat.blocks) ##Column center data blocks if(center){ cent.blocks = lapply(dat.blocks, function(D){scale(D, scale = FALSE)}) } else{ cent.blocks = dat.blocks } if(is.null(signal.ranks)){ all.singvals = lapply(cent.blocks, function(x) svd(x)$d) p = ifelse(length(perc.var)==1, rep(perc.var, 2), perc.var) for(k in 1:K){ d = all.singvals[[k]] signal.ranks = c(signal.ranks, which.min(cumsum(d^2) <= p[k]*sum(d^2)) ) } } x.all.svd = list() for(k in 1:K){ x.all.svd[[k]] = svd(cent.blocks[[k]], nu = signal.ranks[k], nv = signal.ranks[k]) } U.all = lapply(x.all.svd, function(x) scale(x$u, scale = FALSE)) U1tU2 = t(U.all[[1]])%*%U.all[[2]] orig.corrs = svd(U1tU2)$d perm.corrs = NULL for (i in 1:nperms){ U1tU2.perm = t(U.all[[1]])%*%U.all[[2]][sample(n),] perm.svd = svd(U1tU2.perm) perm.corrs = rbind(perm.corrs, perm.svd$d) } test.val = stats::quantile(perm.corrs[,1],probs = 1-alpha) r.j = which.min(orig.corrs >= test.val) - 1 ranks = c(r.j, signal.ranks) p.vals = NULL for(i in 1:r.j){ p.vals = c(p.vals, sum(orig.corrs[i] <= perm.corrs[,1])/nperms) } names(ranks) = c("Joint", "Total Signal 1", "Total Signal 2") res = list(ranks, orig.corrs[1:r.j], p.vals) names(res) = c("Ranks", "Canonical Corrs", "P-values") return(res) } ########### CC.JIVE ################## ########### uses permutation test based on PC scores to find joint rank ########### and estimates joint subject scores as scaled average of canonical variables #' Canonical (Correlation) JIVE #' #' @description Performs Canonical JIVE as described in the CJVE manuscript. This method is equivalent to AJIVE for 2 data sets. #' #' @param dat.blocks a list of two matrices with samples along rows and features along columns, which contain data on the same n individuals/sampling units #' @param signal.ranks a vector of length two which contains the rank for the signal within each data block. The rank corresponds to the number of principal #' components (PCs) to be retained within each data block. If NULL, the ranks are determined by the parameter 'perc.var.' Default is NULL #' @param joint.rank The rank of the joint subspace i.e., number of components in the joint subspace #' @param perc.var an alternative to signal.ranks that allows specification of ranks based on the desired proportion of total variation to be retained. F #' For perc.var = p (where 0<p<1), rank is determined as the minimum number of eigenvalues whose cumulative sum is at least p*(total sum of eigenvalues) #' Default is 0.95 (i.e. 95\% of total variation preserved for each data block). #' @param perm.test logical (TRUE/FALSE) of whether permutation test for joint rank should be performed. Overrides 'joint.rank' parameter if TRUE. Default is TRUE #' @param center logical (TRUE/FALSE) indicating whether data should be column-centered prior to testing. Default is TRUE #' @param nperms integer value indicating the number of permutations that should be performed. Default is 1000 #' #' @return A list of two lists: #' 1) 'CanCorRes' contains results from the canonical correlation of PC scores including, the joint rank, joint subject sores, #' canonical correlations (and their respective p-values if perm.test was used), canonical loadings for the joint subspace, and total signal ranks #' 2) 'sJIVE', i.e. Simple JIVE results, correspond to the AJIVE when all ranks are known; includes the joint and individual signal matrices, concatenated PC scores, #' and the projection matrix used to project each data block onto the joint subspace #' @examples #'#Assign sample size and the number of features in each dataset #'n = 200 #sample size #'p1 = 100 #Number of features in data set X1 #'p2 = 100 #Number of features in data set X2 #' #'# Assign values of joint and individual signal ranks #'r.J = 1 #joint rank #'r.I1 = 2 #individual rank for data set X1 #'r.I2 = 2 #individual rank for data set X2 #' #' #'# Simulate data sets #'ToyDat = GenerateToyData(n = 200, p1 = p1, p2 = p2, JntVarEx1 = 0.05, JntVarEx2 = 0.05, #' IndVarEx1 = 0.25, IndVarEx2 = 0.25, jnt_rank = r.J, equal.eig = FALSE, #' ind_rank1 = r.I1, ind_rank2 = r.I2, SVD.plots = TRUE, Error = TRUE, #' print.cor = TRUE) #'# Store simulated data sets in an object called 'blocks' #'blocks <- ToyDat$'Data Blocks' #' #'# Save Subject scores as R objects #'JntScores = ToyDat[['Scores']][['Joint']] #'IndivScore.X = ToyDat[['Scores']][["Indiv_1"]] #'IndivScore.Y = ToyDat[['Scores']][["Indiv_2"]] #' #'# Save joint variable loadings as R objects #'JntLd.X = t(ToyDat$Loadings$Joint_1) #'JntLd.Y = t(ToyDat$Loadings$Joint_2) #' #'# Save individual variable loadings as R objects #'IndivLd.X =t(ToyDat$Loadings$Indiv_1) #'IndivLd.Y = t(ToyDat$Loadings$Indiv_2) #' #'# Save joint, individual, and noise signal matrices as R objects #'JX = ToyDat[[1]]$J1 #'JY = ToyDat[[1]]$J2 #'IX = ToyDat[[1]]$I1 #'IY = ToyDat[[1]]$I2 #'EX = ToyDat[[1]]$E1 #'EY = ToyDat[[1]]$E2 #' #' #'## Check that proportions of variation explained are (approximately) equal to intended values #'JVE.X = MatVar(JX)/MatVar(blocks[[1]]) #'JVE.Y = MatVar(JY)/MatVar(blocks[[2]]) #' #'IVE.X = MatVar(IX)/MatVar(blocks[[1]]) #'IVE.Y = MatVar(IY)/MatVar(blocks[[2]]) #' #'TotVE.X = MatVar((JX + IX))/MatVar(blocks[[1]]) #'TotVE.Y = MatVar((JY + IY))/MatVar(blocks[[2]]) #' #' #' CJIVE.res = cc.jive(blocks, c(r.I1,r.I2)+r.J, r.J, perm.test = FALSE) #'# CJIVE signal matrix estimates #'J.hat = CJIVE.res$sJIVE$joint_matrices #'I.hat = CJIVE.res$sJIVE$indiv_matrices #' #'# CJIVE loading estimates #'WJ = lapply(J.hat, function(x) x[['v']]) #'WI = lapply(I.hat, function(x) x[['v']]) #' #'# Plots of CJIVE estimates against true counterparts and include an estimate of their chordal norm #'layout(matrix(1:6,2, byrow = TRUE)) #'plot(JntScores, CJIVE.res$CanCorRes$Jnt_Scores, xlab = "True Joint Scores", #' ylab = "CJIVE Joint Scores", #' sub = paste0("Chordal Norm = ", #' round(chord.norm.diff(JntScores, CJIVE.res$CanCorRes$Jnt_Scores), 3))) #'plot(JntLd.X, WJ[[1]][,1], xlab = "True Joint Loadings X", ylab = "CJIVE Joint Loadings X", #' sub = paste0("Chordal Norm = ", round(chord.norm.diff(JntLd.X, WJ[[1]][,1]), 3))) #'plot(JntLd.Y, WJ[[2]][,1], xlab = "True Joint Loadings Y", ylab = "CJIVE Joint Loadings Y", #' sub = paste0("Chordal Norm = ", round(chord.norm.diff(JntLd.Y, WJ[[2]][,1]), 3))) # plot(1,lwd=0,axes=F,xlab="",ylab="", "n") #'plot.new(); legend("left", paste("Comp.", 1:2), pch = 1, col = c("orange", "green"),bty = "n" ) #'plot(IndivLd.X, WI[[1]][,1:2], xlab = "True Individual Loadings X", #' ylab = "CJIVE Individual Loadings X", #' col = c(rep("orange",p1), rep("green",p2)), #' sub = paste0("Chordal Norm = ", round(chord.norm.diff(IndivLd.X, WI[[1]][,1:2]), 3))) #'plot(IndivLd.Y, WI[[2]][,1:2], xlab = "True Individual Loadings Y", #' ylab = "CJIVE Individual Loadings Y", #' col = c(rep("orange",p1), rep("green",p2)), #' sub = paste0("Chordal Norm = ", round(chord.norm.diff(IndivLd.Y, WI[[2]][,1:2]), 3))) #'layout(1) #' #' @export cc.jive<-function(dat.blocks, signal.ranks = NULL, joint.rank = 1, perc.var = 0.95, perm.test = TRUE, center = FALSE, nperms = 1000){ n.1 = nrow(dat.blocks[[1]]) n.2 = nrow(dat.blocks[[2]]) if(n.1 != n.2){stop("The number of rows in each data matrix must match")} n = n.1 if(center){ cent.blocks = lapply(dat.blocks, scale) } else { cent.blocks = dat.blocks } if(is.null(signal.ranks)){ d1 = svd(cent.blocks[[1]])$d d2 = svd(cent.blocks[[2]])$d r.1 = which.min(cumsum(d1^2) <= perc.var*sum(d1^2)) r.2 = which.min(cumsum(d2^2) <= perc.var*sum(d2^2)) signal.ranks = c(r.1,r.2) } r.1 = signal.ranks[1] r.2 = signal.ranks[2] r.J = joint.rank if(perm.test){ cca.perm.res = perm.jntrank(cent.blocks, signal.ranks = c(r.1,r.2), nperms = nperms) r.J = cca.perm.res$Ranks[1] } x1.svd = svd(cent.blocks[[1]], nu = signal.ranks[1], nv = signal.ranks[1]) x2.svd = svd(cent.blocks[[2]], nu = signal.ranks[2], nv = signal.ranks[2]) U.1 = x1.svd$u U.2 = x2.svd$u if(r.J > 0){ U1tU2 = t(U.1)%*%U.2 U1tU2.svd = svd(U1tU2, nu = r.J, nv = r.J) orig.corrs = U1tU2.svd$d if(r.J == 1){ jnt.scores = (U.1%*%U1tU2.svd$u +U.2%*%U1tU2.svd$v)*(2*(1 + orig.corrs[r.J]))^-.5 } else { jnt.scores = (U.1%*%U1tU2.svd$u +U.2%*%U1tU2.svd$v)%*%diag((2*(1 + orig.corrs[1:r.J]))^-.5) } } else { jnt.scores = rep(0, nrow(cent.blocks[[1]])) U1tU2 = t(U.1)%*%U.2 U1tU2.svd = svd(U1tU2) orig.corrs = U1tU2.svd$d } sjive.out = sjive(cent.blocks, c(r.1, r.2), r.J, jnt.scores) if(perm.test){ res = list(r.J, jnt.scores, list(orig.corrs,cca.perm.res$'P-values'), list(U1tU2.svd$u, U1tU2.svd$v), signal.ranks) names(res) = c("Jnt_Rank","Jnt_Scores", "Canonical_Correlations", "Loadings", "Signal Ranks") } else { res = list(r.J, jnt.scores, orig.corrs, list(U1tU2.svd$u, U1tU2.svd$v), signal.ranks) names(res) = c("Jnt_Rank","Jnt_Scores", "Canonical_Correlations", "Loadings", "Signal Ranks") } res.out = list(res, sjive.out) names(res.out) = c("CanCorRes","sJIVE") return(res.out) } ######### Compute predicted joint scores for new subjects using current CCJIVE Joint loadings ############# #' CJIVE joint subject score prediction #' #' @description Predicts joint scores for new subjects based on CJIVE joint scores #' #' @param orig.dat.blocks list of the two data matrices on which CJIVE was initially conducted #' @param new.subjs list of two data matrices containing information on new subjects #' @param signal.ranks a vector of length two which contains the rank for the signal within each data block. The rank corresponds to the number of principal #' components (PCs) to be retained within each data block. If NULL, the ranks are determined by the parameter 'perc.var.' Default is NULL #' @param cc.jive.loadings canonical loadings for the joint subspace #' @param can.cors canonical correlations from the PCs of the data on which CJIVE was initially conducted - notated as rho_j in CJIVE manuscript #' #' @return matrix of joint subject score for new subjects #' #' @examples #'n = 200 #sample size #'p1 = 100 #Number of features in data set X1 #'p2 = 100 #Number of features in data set X2 #'# Assign values of joint and individual signal ranks #'r.J = 1 #joint rank #'r.I1 = 2 #individual rank for data set X1 #'r.I2 = 2 #individual rank for data set X2 #'true_signal_ranks = r.J + c(r.I1,r.I2) #'# Simulate data sets #'ToyDat = GenerateToyData(n = n, p1 = p1, p2 = p2, JntVarEx1 = 0.05, JntVarEx2 = 0.05, #' IndVarEx1 = 0.25, IndVarEx2 = 0.25, jnt_rank = r.J, equal.eig = FALSE, #' ind_rank1 = r.I1, ind_rank2 = r.I2, SVD.plots = TRUE, Error = TRUE, #' print.cor = TRUE) #'# Store simulated data sets in an object called 'blocks' #'blocks <- ToyDat$'Data Blocks' #'# Split data randomly into two subsamples #'rnd.smp = sample(n, n/2) #'blocks.sub1 = lapply(blocks, function(x){x[rnd.smp,]}) #'blocks.sub2 = lapply(blocks, function(x){x[-rnd.smp,]}) #'# Joint scores for the two sub samples #'JntScores.1 = ToyDat[['Scores']][['Joint']][rnd.smp] #'JntScores.2 = ToyDat[['Scores']][['Joint']][-rnd.smp] #'# Conduct CJIVE analysis on the first sub-sample and store the canonical loadings and canonical #'# correlations #'cc.jive.res_sub1 = cc.jive(blocks.sub1, signal.ranks = r.J+c(r.I1,r.I2), center = FALSE, #' perm.test = FALSE, joint.rank = r.J) #'cc.ldgs1 = cc.jive.res_sub1$CanCorRes$Loadings #'can.cors = cc.jive.res_sub1$CanCorRes$Canonical_Correlations[1:r.J] #'# Conduct CJIVE analysis on the second sub-sample. We will predict these joint scores using the #'# results above #'cc.jive.res_sub2 = cc.jive(blocks.sub2, signal.ranks = true_signal_ranks, center = FALSE, #' perm.test = FALSE, joint.rank = r.J) #'cc.jnt.scores.sub2 = cc.jive.res_sub2$CanCorRes$Jnt_Scores #'cc.pred.jnt.scores.sub2 = cc.jive.pred(blocks.sub1, new.subjs = blocks.sub2, #' signal.ranks = true_signal_ranks, #' cc.jive.loadings = cc.ldgs1, can.cors = can.cors) #'# Calculate the Pearson correlation coefficient between predicted and calculated joint scores #'# for sub-sample 2 #'cc.pred.cor = diag(cor(cc.pred.jnt.scores.sub2, cc.jnt.scores.sub2)) #'print(cc.pred.cor) #'# Plots of CJIVE estimates against true counterparts and include an estimate of their chordal #'# norm #'layout(matrix(1:2, ncol = 2)) #'plot(JntScores.2, cc.pred.jnt.scores.sub2, ylab = "Predicted Joint Scores", #' xlab = "True Joint Scores", #' col = rep(1:r.J, each = n/2), #' main = paste("Chordal Norm = ", #' round(chord.norm.diff(JntScores.2, cc.pred.jnt.scores.sub2),2))) #'legend("topleft", legend = paste("Component", 1:r.J), col = 1:r.J, pch = 1) #'plot(cc.jnt.scores.sub2, cc.pred.jnt.scores.sub2, ylab = "Predicted Joint Scores", #' xlab = "Estimated Joint Scores", #' col = rep(1:r.J, each = n/2), #' main = paste("Chordal Norm = ", #' round(chord.norm.diff(cc.jnt.scores.sub2, cc.pred.jnt.scores.sub2),2))) #'layout(1) #' #' @export cc.jive.pred<-function(orig.dat.blocks, new.subjs, signal.ranks, cc.jive.loadings, can.cors){ r1 = signal.ranks[1] r2 = signal.ranks[2] X1.svd = svd(orig.dat.blocks[[1]], nu = r1, nv = r1) X2.svd = svd(orig.dat.blocks[[2]], nu = r2, nv = r2) U1.Ldngs = cc.jive.loadings[[1]] U2.Ldngs = cc.jive.loadings[[2]] Pred.CanVar.1 = new.subjs[[1]]%*%X1.svd$v%*%diag(X1.svd$d[1:r1]^-1)%*%U1.Ldngs Pred.CanVar.2 = new.subjs[[2]]%*%X2.svd$v%*%diag(X2.svd$d[1:r2]^-1)%*%U2.Ldngs pred.jnt.scores = sqrt(1/2*(1+can.cors))*(Pred.CanVar.1 + Pred.CanVar.2) return(pred.jnt.scores) } ########### sJIVE ################## #' Simple JIVE #' #' @description Conducts AJIVE estimation under the assumption that all ranks are known and no components are discarded #' #' @param blocks list of data blocks, i.e. matrices, all having the same number of rows, which correspond to the same sampling units (i.e. study participants, patients, etc.) #' @param signal_ranks numerical vector of the same length as 'blocks' with each entry corresponding to the rank of the respective matrix in 'blocks' #' @param joint.rank integer value corresponding to the rank of the joint signal subspace, i.e. number of components in the signal subspace #' @param joint_scores numerical matrix containing joint subject scores if they were calculated by some other method, e.g. Canonical Correlation of PC scores. #' Must have the same number of rows as each matrix in 'blocks' and number of columns equal to 'joint_rank'. If NULL, joint scores are calculated and #' returned. Default is NULL. #' #' @return list of 4 or 5 items: 1) joint signal matrices, their SVDs, and the proportion of total variation in each matrix that is attributable to the joint signal #' 2) individual signal matrices, their SVDs, and the proportion of total variation in each matrix that is attributable to the individual signal #' 3) concatenated PC scores, used to determine joint subspace #' 4) projection matrix for joint subspace #' 5) joint subject scores (only returned if not provided initially) #' @export sjive<-function (blocks, signal_ranks, joint.rank, joint_scores = NULL) { j=joint.rank K <- length(blocks) if (K < 2) { stop("ajive expects at least two data matrices.") } if (sum(sapply(blocks, function(X) any(is.na(X)))) > 0) { stop("Some of the blocks has missing data -- ajive expects full data matrices.") } block_svd <- list() scaled.centered <- list() total.var <- list() for (k in 1:K) { #Scale and center each block temp<-blocks[[k]] for (i in 1:dim(blocks[[k]])[2]) { temp[,i]<-blocks[[k]][,i]-mean(blocks[[k]][,i]) ##subtract the mean from each column } scaled.centered[[k]] <- temp block_svd[[k]] <- svd(scaled.centered[[k]],nu=signal_ranks[k]) ##Take SVD of each data block total.var[[k]] = sum(block_svd[[k]]$d^2) if (k==1) { stacked_mat<-block_svd[[k]]$u[,1:signal_ranks[k]] ##initialize matrix that results from stacking SVD matrices: contains first k vectors of U } else if (k>1){ stacked_mat <- cbind(stacked_mat,block_svd[[k]]$u[,1:signal_ranks[k]]) ##stack the rest of the U matrices together with the first } } if(is.null(joint_scores)){ if(j>0){ joint_scores<-svd(stacked_mat,nu=j)$u ##take SVD of stacked matrix: nu=j indicates that the joint structure has rank=j joint_proj<-(joint_scores)%*%t(joint_scores) ##orthogonal projection matrix onto joint space based on stacked bases } else { joint_scores = rep(0, nrow(scaled.centered[[1]])) joint_proj<-(joint_scores)%*%t(joint_scores) } } else { joint_proj<-(joint_scores)%*%t(joint_scores) } indiv_structure <- list() joint_structure <- list() for (k in 1:K) { joint_structure[[k]] = list() joint_structure[[k]][['full']]<-joint_proj%*%as.matrix(scaled.centered[[k]]) temp.svd = svd(joint_structure[[k]][['full']], nu = joint.rank, nv = joint.rank) if (j>0){ joint_structure[[k]][['u']]<-temp.svd[['u']] joint_structure[[k]][['v']]<-temp.svd[['v']] joint_structure[[k]][['d']]<-temp.svd[['d']][1:joint.rank] } else { joint_structure[[k]][['u']]<-matrix(rep(0, nrow(scaled.centered[[1]])), ncol = 1) joint_structure[[k]][['v']]<-matrix(rep(0, ncol(scaled.centered[[k]])), ncol = 1) joint_structure[[k]][['d']]<-0 } joint_structure[[k]][['full']] = joint_structure[[k]][['u']]%*% diag(joint_structure[[k]][['d']], nrow = max(joint.rank, 1), ncol = max(joint.rank, 1))%*% t(joint_structure[[k]][['v']]) joint_structure[[k]][['VarEx']] = sum(joint_structure[[k]][['d']]^2)/total.var[[k]] dat_proj<-block_svd[[k]]$u%*%t(block_svd[[k]]$u) # indiv_structure[[k]]<-(dat_proj-joint_proj)%*%as.matrix(scaled.centered[[k]]) temp = (diag(nrow(scaled.centered[[k]]))-joint_proj)%*%as.matrix(scaled.centered[[k]]) indiv.rank = signal_ranks[k]-joint.rank temp.svd = svd(temp) indiv_structure[[k]] = list() indiv_structure[[k]][['u']] = temp.svd[['u']][,1:indiv.rank, drop = FALSE] indiv_structure[[k]][['v']] = temp.svd[['v']][,1:indiv.rank, drop = FALSE] indiv_structure[[k]][['d']] = temp.svd[['d']][1:indiv.rank] indiv_structure[[k]][['full']] = indiv_structure[[k]][['u']]%*% diag(indiv_structure[[k]][['d']], nrow = indiv.rank, ncol = indiv.rank)%*% t(indiv_structure[[k]][['v']]) indiv_structure[[k]][['VarEx']] = sum(indiv_structure[[k]][['d']]^2)/total.var[[k]] } out = list(joint_structure,indiv_structure,stacked_mat,joint_proj) names(out) = c("joint_matrices", "indiv_matrices", "stacked_mat", "joint_projection") if(is.null(joint_scores)){out[[5]] = joint_scores; names(out)[5] = "joint_scores"} return(out) }
/scratch/gouwar.j/cran-all/cranData/CJIVE/R/CJIVE_Functions.R
#' Generate 'Toy' Data #' #' @description Generates two Simulated Datasets that follow JIVE Model using binary subject scores #' #' @param n integer for sample size, i.e. number of subjects #' @param p1 integer for number of features/variables in first data set #' @param p2 integer for number of features/variables in second data set #' @param JntVarEx1 numeric between (0,1) which describes proportion of variance in the first data set which is attributable to the joint signal #' @param JntVarEx2 numeric between (0,1) which describes proportion of variance in the second data set which is attributable to the joint signal #' @param IndVarEx1 numeric between (0,1) which describes proportion of variance in the first data set which is attributable to the individual signal #' @param IndVarEx2 numeric between (0,1) which describes proportion of variance in the second data set which is attributable to the individual signal #' @param jnt_rank integer for rank of the joint signal, i.e., number of joint components #' @param equal.eig logical (TRUE/FALSE) for whether components should contribute equal variance to signal matrices - default is FALSE #' @param ind_rank1 integer for rank of the individual signal in first data set, i.e., number of joint components #' @param ind_rank2 integer for rank of the individual signal in second data set, i.e., number of joint components #' @param SVD.plots logical (TRUE/FALSE) for whether plots of singular values from signal should be produced - used to confirm number of components #' @param Error logical (TRUE/FALSE) final data sets should be noise contaminated - default is FALSE; use TRUE to obtain pure signal datasets #' @param print.cor logical (TRUE/FALSE) for whether to print matrix of correlations between subject scores) #' #' @return A 'list' object which contains 1) list of signal matrices which additively comprise the simulated data sets, i.e. joint, individual, #' and error matrices for each data set; 2) list of simulated data sets (each equal to the sum of the matrices in part 1); #' 3) list of joint subject scores and individual subject scores for each data set, and 4) lsit of joint and individual loadings for each data set #' @examples #' ToyDat = GenerateToyData(n = 200, p1 = 2000, p2 = 1000, JntVarEx1 = 0.05, JntVarEx2 = 0.05, #' IndVarEx1 = 0.25, IndVarEx2 = 0.25, jnt_rank = 1, equal.eig = FALSE, #' ind_rank1 = 2, ind_rank2 = 3, SVD.plots = TRUE, Error = TRUE, #' print.cor = TRUE) #' @export #' #' GenerateToyData <- function(n, p1, p2, JntVarEx1, JntVarEx2, IndVarEx1, IndVarEx2, jnt_rank = 1, equal.eig = FALSE, ind_rank1 = 2, ind_rank2 = 2, SVD.plots = TRUE, Error = TRUE, print.cor = TRUE){ #Write out both joint and indiv subject scores for both data sets first r.J = jnt_rank JntScores = matrix(stats::rbinom(n*r.J, size=1, prob=0.2), nrow = n, ncol = r.J) colnames(JntScores) = paste("Jnt Score", 1:r.J) r.I1 = ind_rank1 r.I2 = ind_rank2 b = stats::rbinom(n*(r.I1 + r.I2), size=1, prob=0.4) b = 1 - 2*b IndivScores = matrix(b, nrow = n, ncol = (r.I1 + r.I2)) colnames(IndivScores) = c(paste("Ind X Score", 1:r.I1), paste("Ind Y Score", 1:r.I2)) if(print.cor){ message("The strongest absolute correlation between subject scores is ", round(max(abs(stats::cor(cbind(JntScores, IndivScores)) - diag(r.J+r.I1+r.I2))),4)) } ##############################Define X Dataset############################## ##Then write each of the 3 variable loading vectors for the first dataset ##Note that the joint signal has rank=1 AdjJntLoad.X = matrix(stats::rnorm(r.J*p1), nrow = r.J, ncol = p1) #change relavent scaling of joint components D.J = ifelse(diag(rep(equal.eig, r.J)), diag(rep(1,r.J)), diag(r.J:1)) if(equal.eig){D.J = diag(rep(1,r.J))} else{ D.J = diag(r.J:1) } JX = JntScores%*%sqrt(D.J)%*%AdjJntLoad.X if(SVD.plots){ plot(svd(JX)$d, ylab = "Singular Values") graphics::title("SVD of Joint Signal from X") } ##Note that the individual signal has rank = 2 as well IndScores.X = IndivScores[,1:r.I1] IndLoad.X = matrix(stats::rnorm(n = p1*r.I1), nrow = r.I1, ncol = p1) if(equal.eig){D.IX = diag(rep(1,r.I1))} else{ D.IX = diag(r.I1:1) } IX = IndScores.X%*%sqrt(D.IX)%*%IndLoad.X if(SVD.plots){ plot(svd(IX)$d, ylab = "Singular Values") graphics::title("SVD of Individual Signal from X") } AX = JX + IX ##############################Define Y Dataset############################## AdjJntLoad.Y = matrix(stats::rnorm(r.J*p2), nrow = r.J, ncol = p2) ##Note that the joint signal has rank = 3 JY = JntScores%*%sqrt(D.J)%*%AdjJntLoad.Y if(SVD.plots){ plot(svd(JY)$d, ylab = "Singular Values") graphics::title("SVD of Joint Signal from Y") } IndScores.Y = IndivScores[,(r.I1 + 1:r.I2)] IndLoad.Y = matrix(stats::rnorm(r.I2*p2), nrow = r.I2, ncol = p2) if(equal.eig){D.IY = diag(rep(1,r.I2))} else{ D.IY = diag(r.I2:1) } ##Note that the individual signal has rank=2 IY = IndScores.Y%*%sqrt(D.IY)%*%IndLoad.Y if(SVD.plots){ plot(svd(IY)$d, ylab = "Singular Values") graphics::title("SVD of Individual Signal from Y") } ##Error matrix EX = matrix(stats::rnorm(n*p1), nrow=n, ncol=p1)*Error ##Error matrix EY = matrix(stats::rnorm(n*p2), nrow=n, ncol=p2)*Error Dat.X = AdjSigVarExp(JX, IX, EX, JntVarEx1, IndVarEx1) JX = Dat.X$J IX = Dat.X$I Dat.Y = AdjSigVarExp(JY, IY, EY, JntVarEx2, IndVarEx2) JY = Dat.Y$J IY = Dat.Y$I Blocks = list(Dat.X[["Data"]], Dat.Y[["Data"]]) Dat.Comps = list(JX, JY, IX, IY, EX, EY) names(Dat.Comps) = c("J1", "J2", "I1", "I2", "E1", "E2" ) Scores = list(JntScores, IndScores.X, IndScores.Y) names(Scores) = c("Joint", "Indiv_1", "Indiv_2") Loadings = list(AdjJntLoad.X, IndLoad.X, AdjJntLoad.Y, IndLoad.Y) names(Loadings) = c("Joint_1", "Indiv_1", "Joint_2", "Indiv_2") out = list(Dat.Comps, Blocks, Scores, Loadings) names(out) = c("Data Components", "Data Blocks", "Scores", "Loadings") out } ########### Adjust Dataset Components to get Desired R^2 Values ################# #' Adjust Signal Variation Explained #' #' @description Adjusts the proportion of total variation attributable to each signal component to predetermined values #' #' @param J joint signal matrix of size n-by-p #' @param I individual signal matrix of size n-by-p #' @param N noise/error matrix of size n-by-p #' @param JntVarEx desired proportion of total variation explained by the joint signal #' @param IndVarEx desired proportion of total variation explained by the individual signal #' #' @return a list of 3 items: 1) adjusted joint signal matrix; 2) adjusted individual signal matrix; 3) data matrix additively comprised of the adjusted signal matrices #' #' @export AdjSigVarExp <-function(J, I, N, JntVarEx, IndVarEx){ simul.quads = function(x, parms){ JJ = parms[1] II = parms[2] NN = parms[3] JN = parms[4] IN = parms[5] R_J = parms[6] R_I = parms[7] y1 = x[1]^2*II*(1 - R_I) - 2*x[1]*IN*R_I - R_I*(x[2]^2*JJ + 2*x[2]*JN + NN) y2 = x[2]^2*JJ*(1 - R_J) - 2*x[2]*JN*R_J - R_J*(x[1]^2*II + 2*x[1]*IN + NN) y = c(y1,y2) return(y) } JJ = MatVar2(J) II = MatVar2(I) NN = MatVar2(N) JN = sum(diag(J%*%t(N))) IN = sum(diag(I%*%t(N))) R_J = JntVarEx R_I = IndVarEx parms = c(JJ, II, NN, JN, IN, R_J, R_I) A = J + I AA = MatVar2(A) NN = MatVar2(N) AN = sum(diag(A%*%t(N))) ##Desired Total Variance Explained d0 = IndVarEx + JntVarEx a = AA*(1 - d0) b = -2*AN c = -d0*NN d.A = (-b+sqrt(b^2 - 4*a*c))/(2*a) start = c(0.5, 0.5)*d.A roots = rootSolve::multiroot(simul.quads, start, parms = parms) c = roots$root[1] d = roots$root[2] J.d = d*J; I.c = c*I; Dat = J.d + I.c + N res = list(J.d, I.c, Dat) names(res) = c("J", "I", "Data") return(res) } ############## Retrieve simulation results stored in a directory ################## #' Retrieve simulation results #' #' @description Retrives and compiles results from simulation study which are stored in a directory. A directory should contain separate .csv files (one per replicate), #' each of which will include all evaluation metrics and most experimental settings for that particular replicate. For the CJIVE manuscript, a directory houses results of all #' 100 replicates for each combination of experimental factors. #' #' @param sim.dir (character string) file path for the directory from which results will be retrieved #' @param p1 number of features in data set 1 #' @param p2 number of features in data set 2 #' @param Preds (logical) do the replicate results contain correlations between predicted and true joint subject scores. Default is FALSE #' #' @return upper triangular p-by-p matrix #' @export GetSimResults_Dir = function(sim.dir, p1, p2, Preds=FALSE){ files = list.files(sim.dir, pattern = ".csv") num_sims = length(files) JVEs = as.numeric(paste("0",strsplit(sim.dir, "[.]0")[[1]][-1], sep = ".")) JntVarEx1 = JVEs[1] JntVarEx2 = JVEs[2] results = NULL for (nm in files){ temp = utils::read.csv(file = file.path(sim.dir, nm), header = TRUE) varnames = temp[,1]; values = temp[,2] to.keep = !grepl("Pred",varnames) if(Preds==F & length(to.keep)>0){ values = values[to.keep] varnames = varnames[to.keep] } results = rbind(results,c(values, p1, p2)) } colnames(results) = c(varnames, "p1", "p2") results = data.frame(cbind(results, JntVarEx1, JntVarEx2)) } ##################### Convert Simulation Results to a form that will allow ggplot ####################### #' Convert simulation study results #' #' @description Convert results from simulation study into a form for graphing with ggplot #' #' @param AllSims matrix with each row representing results from a replicate in the simulation study described in CJIVE manuscript #' #' @return list of 2 items: 1) joint ranks determined by each method employed in the simulations study #' 2) chordal norms between true and estimated joint/individual loadings/scores for each method employed in the simulation study #' @export ConvSims_gg<-function(AllSims){ sim.names = colnames(AllSims) #CompEvals.names = c(sim.names[grep("Scores", sim.names)], sim.names[grep("Loads", sim.names)]) num.sims = dim(AllSims)[1] p1 = unique(AllSims$p1) p2 = unique(AllSims$p2) JVE_1 = c(as.matrix(AllSims[,grep("JntVarEx1",sim.names)])) JVE1.labs = c(bquote("R"[J1]^2*"=0.05, p"[1]*"="*.(p1)), bquote("R"[J1]^2*"=0.5, p"[1]*"="*.(p1))) JVE_1 = factor(JVE_1, labels = JVE1.labs, levels = c(0.05, 0.5)) JVE_2 = c(as.matrix(AllSims[,grep("JntVarEx2",sim.names)])) JVE2.labs = c(bquote("R"[J2]^2*"=0.05, p"[2]*"="*.(p2)), bquote("R"[J2]^2*"=0.5, p"[2]*"="*.(p2)) ) JVE_2 = factor(JVE_2, labels = JVE2.labs, levels = c(0.05, 0.5)) IVE_1 = c(as.matrix(AllSims[,grep("Indiv.Var.Exp.X", sim.names)])) IVE_1 = round(as.numeric(IVE_1), 2) IVE_2 = c(as.matrix(AllSims[,grep("Indiv.Var.Exp.Y", sim.names)])) IVE_2 = round(as.numeric(IVE_2), 2) if("True.Joint.Rank" %in% sim.names){ sim.names.2 = sim.names[-grep("True.Joint.Rank", sim.names)] AllSims.2 = AllSims[,which(sim.names %in% sim.names.2)] Method = sim.names.2[grep("Joint.Rank", sim.names.2)] temp = colnames(AllSims.2) Rank = factor(c(as.matrix(AllSims.2[,temp[grep("Joint.Rank", temp)]]))) } else { Method = sim.names[grep("Joint.Rank", sim.names)] Rank = factor(c(as.matrix(AllSims[,grep("Joint.Rank", sim.names)]))) } Method = sub(".Joint.Rank", "", Method, fixed = TRUE); Method = sub("aJI", "AJI", Method, fixed = TRUE) Method = sub("Correct", "", Method, fixed = TRUE); Method = sub(".Wrong", "-Over", Method, fixed = TRUE) Method = sub(".oracle", "-r_k", Method, fixed = TRUE); Method = sub(".over", "-Over", Method, fixed = TRUE) Method = sub("Elbow", "r_k", Method, fixed = TRUE); Method = sub(".95.", "-Over", Method, fixed = TRUE) Method = sub("iJI", "R.JI", Method, fixed = TRUE); Method = sub("AJIVE.", "AJIVE-", Method, fixed = TRUE) Method = sub("CC", "CJIVE", Method, fixed = TRUE); Method = sub("cJIVE", "CJIVE", Method, fixed = TRUE) Method[which(Method == "CJIVE.Oracle")] = "CJIVE-r_k" Method[which(Method == "CJIVE.r_k")] = "CJIVE-r_k" Method[which(Method == "AJIVE-Oracle")] = "AJIVE-r_k" Method[which(Method == "R.JIVE.Free")] = "R.JIVE-Free" Method[which(Method %in% c("CJIVE.Over", "cJIVE.Over"))] = "CJIVE-Over" Method = factor(Method, levels = c("CJIVE-r_k","CJIVE-Over","AJIVE-r_k","AJIVE-Over","R.JIVE-Free"), labels = c("CJIVE-r_k","CJIVE-Over","AJIVE-r_k","AJIVE-Over","R.JIVE-Free")) sim.ranks.gg = data.frame(Rank = Rank, Method = rep(Method, each = num.sims), JVE_1 = rep(JVE_1, each = length(levels(Method))), JVE_2 = rep(JVE_2, each = length(levels(Method))), IVE_1 = rep(IVE_1, each = length(levels(Method))), IVE_2 = rep(IVE_2, each = length(levels(Method)))) if("True.Joint.Rank" %in% sim.names){ True_Rank = c(as.numeric(as.matrix(AllSims[,grep("True.Joint.Rank", sim.names)]))) True_Rank = factor(True_Rank) sim.ranks.gg$True_Rank = rep(True_Rank, each = length(levels(Method))) } Norm = c(as.numeric(as.matrix(AllSims[,grep("Scores", sim.names)]))) Method = rep(substr(sim.names[grep("Scores",sim.names)], 1,12), each = num.sims) Method = sub(".Joint.", "", Method, fixed = TRUE); Method = sub(".Indiv.", "", Method, fixed = TRUE); Method = sub("aJI", "AJI", Method, fixed = TRUE); Method = sub("iJI", "R.JI", Method, fixed = TRUE); Method = sub("r.J", "r", Method, fixed = TRUE); Method = sub("r.I", "r", Method, fixed = TRUE) Method[which(Method == "AJIVE")] = "AJIVE-r_k"; Method = sub(".w", "-Over", Method, fixed = TRUE); Method[which(Method == "CC.Oracle")] = "CJIVE-r_k"; Method[which(Method == "CC-Over")] = "CJIVE-Over" Method[which(Method == "R.JIVE.Free")] = "R.JIVE-Free" Method = sub("JIVE.", "JIVE-", Method, fixed = TRUE); Method = sub("[[:punct:]]$", "", Method, fixed = TRUE) Method[which(Method == "AJIVE-Oracle")] = "AJIVE-r_k"; Method[which(Method == "CJIVE-Oracle")] = "CJIVE-r_k" Method = sub("R.JIVE-Oracl", "R.JIVE-Oracle", Method); Method = sub("R.JIVE-Free.", "R.JIVE-Free", Method) Method = factor(Method, levels = c("CJIVE-r_k","CJIVE-Over","AJIVE-r_k","AJIVE-Over","R.JIVE-Free","R.JIVE-Oracle"), labels = c("CJIVE-r_k","CJIVE-Over","AJIVE-r_k","AJIVE-Over","R.JIVE-Free","R.JIVE-Oracle")) Type = rep(substring(sim.names[grep("Scores", sim.names)], 7), each = num.sims) Type = sub("w.", "", Type); Type = gsub("[.]", " ", Type) Type = gsub("X", "X[1]", Type); Type = gsub("Y", "X[2]", Type) Type = gsub("cle ", "", Type); Type = gsub("Over ", "", Type) Type = gsub("Ora", "", Type); Type = gsub("Free ", "", Type) Type = gsub(" Joint", "Joint", Type); Type = gsub(" Indiv", "Indiv", Type) Type = gsub(" Subj", "", Type); Type = gsub(" Variable", "", Type) Type = as.factor(Type) n.levs = nlevels(Type)*nlevels(Method) sim.score.norms.gg = data.frame(Norm = Norm, Method = Method, Type = Type, JVE_1 = rep(JVE_1, each = n.levs), JVE_2 = rep(JVE_2, each = n.levs), IVE_1 = rep(IVE_1, each = n.levs), IVE_2 = rep(IVE_2, each = n.levs)) if("True.Joint.Rank" %in% sim.names){ True_Rank = c(as.numeric(as.matrix(AllSims[,grep("True.Joint.Rank", sim.names)]))) True_Rank = factor(True_Rank) sim.score.norms.gg$True_Rank = rep(True_Rank, each = length(levels(Method))) } Norm = c(as.numeric(as.matrix(AllSims[,grep("Loads", sim.names)]))) Method = rep(substr(sim.names[grep("Loads",sim.names)], 1,12), each = num.sims) Method = sub(".Joint.", "", Method, fixed = TRUE); Method = sub(".Indiv.", "", Method, fixed = TRUE); Method = sub("aJI", "AJI", Method, fixed = TRUE); Method = sub("iJI", "R.JI", Method, fixed = TRUE); Method = sub("r.J", "r", Method, fixed = TRUE); Method = sub("r.I", "r", Method, fixed = TRUE) Method[which(Method == "AJIVE")] = "AJIVE-r_k"; Method = sub(".w", "-Over", Method, fixed = TRUE); Method[which(Method == "CC.Oracle")] = "CJIVE-r_k"; Method[which(Method == "CC-Over")] = "CJIVE-Over" Method = sub("JIVE.", "JIVE-", Method, fixed = TRUE); Method = sub("[[:punct:]]$", "", Method, fixed = TRUE) Method = sub("JIVE.", "JIVE-", Method, fixed = TRUE); Method = sub("[[:punct:]]$", "", Method, fixed = TRUE) Method[which(Method == "AJIVE-Oracle")] = "AJIVE-r_k"; Method[which(Method == "CJIVE-Oracle")] = "CJIVE-r_k" Method = sub("R.JIVE-Oracl", "R.JIVE-Oracle", Method); Method = sub("R.JIVE-Free.", "R.JIVE-Free", Method) Method = factor(Method, levels = c("CJIVE-r_k","CJIVE-Over","AJIVE-r_k","AJIVE-Over","R.JIVE-Free","R.JIVE-Oracle"), labels = c("CJIVE-r_k","CJIVE-Over","AJIVE-r_k","AJIVE-Over","R.JIVE-Free","R.JIVE-Oracle")) Type = factor(rep(substring(sim.names[grep("Loads", sim.names)], 7), each = num.sims)) Type = sub("w.", "", Type); Type = gsub("[.]", " ", Type) Type = gsub("X", "X[1]", Type); Type = gsub("Y", "X[2]", Type) Type = gsub("cle ", "", Type); Type = gsub("Over ", "", Type) Type = gsub("Ora", "", Type); Type = gsub("Free ", "", Type) Type = gsub(" Joint", "Joint", Type); Type = gsub(" Indiv", "Indiv", Type) Type = gsub(" Subj", "", Type); Type = gsub(" Variable", "", Type) Type = as.factor(Type) n.levs = nlevels(Type)*nlevels(Method) sim.load.norms.gg = data.frame(Norm = Norm, Method = Method, Type = Type, JVE_1 = rep(JVE_1, each = n.levs), JVE_2 = rep(JVE_2, each = n.levs), IVE_1 = rep(IVE_1, each = n.levs), IVE_2 = rep(IVE_2, each = n.levs)) if("True.Joint.Rank" %in% sim.names){ True_Rank = c(as.numeric(as.matrix(AllSims[,grep("True.Joint.Rank", sim.names)]))) True_Rank = factor(True_Rank) sim.load.norms.gg$True_Rank = rep(True_Rank, each = length(levels(Method))) } sim.all.norms.gg = rbind(sim.score.norms.gg, sim.load.norms.gg) out = list(sim.ranks.gg, sim.all.norms.gg) names(out) = c("Ranks", "Subj and Ldg Norms") out } ##################### Plot chordal norms from Simulation Study ####################### #' Function for plotting chordal norms between estimated and true subspaces within the simulation study described in CJIVE manuscript #' #' @description Graphically displays the center and spread of chordal norms for joint/individual score/loading subspaces #' #' @param norm.dat data frame with at least the 5 following variables: #' Norm - the value of the norm for a particular subspace; #' Type - the subspace for which the norm is given (i.e., joint/individual score/loading for dataset X1 or X2 (except for joint scores)) #' Method - the method by which the subspace was estimated, e.g. CJIVE, AJIVE, R.JIVE #' JVE_1 and JVE_2 - labels describing the proportion of joint variation explained in each dataset (and typically the number of variables in dataset X2) #' @param cols a vector of colors, must have length equal to the number of methods used in the simulation #' @param show.legend logical (TRUE/FALSE) for whether a legend should be included in the plot. Default is FALSE #' @param text.size numeric value for the font size #' @param lty linetype (see ggplot2). Default = 1 #' @param y.max maximum value for the horizontal axis of the plot #' @param x.lab.angle angle at which x-axis labels are tilted #' #' @return graphical display (via ggplot2) #' @export gg.norm.plot<-function(norm.dat, cols, show.legend = FALSE, text.size, lty = 1, y.max = 1, x.lab.angle = 70){ labs = levels(norm.dat$Type)[c(3,6,7,1,2,4,5)] labs.ex = c(expression("Joint Subj Scores"), expression("Joint Loadings"*"X"[1]), expression("Joint Loadings"*"X"[2]), expression("Indiv Subj Scores"*"X"[1]), expression("Indiv Subj Scores"*"X"[2]), expression("Indiv Loadings"*"X"[1]), expression("Indiv Loadings"*"X"[2])) labs.rows = levels(norm.dat$JVE_2) labs.cols = levels(norm.dat$JVE_1) ggplot2::ggplot(data = norm.dat, ggplot2::aes(x = norm.dat$Type, y = norm.dat$Norm)) + ggplot2::geom_boxplot(ggplot2::aes(fill = norm.dat$Method), position = "dodge", outlier.alpha = 0, show.legend = show.legend, linetype = lty, fatten = 0.5) + ggplot2::labs(y = "Chordal Norm", x = "Type") + ggplot2::facet_grid(JVE_2 ~ JVE_1, labeller = ggplot2::label_parsed) + ggplot2::scale_x_discrete(limits = levels(norm.dat$Type)[c(3,6,7,1,2,4,5)], labels = labs.ex) + ggplot2::scale_fill_manual(values=cols, name = "Method") + ggplot2::scale_colour_manual(values=cols) + ggplot2::theme_bw() + ggplot2::coord_cartesian(ylim = c(0, y.max)) + ggplot2::theme(axis.title.x = ggplot2::element_blank(), axis.text.x = ggplot2::element_text(face = "bold", hjust = 01, angle = x.lab.angle, size = text.size-3), text = ggplot2::element_text(size = text.size)) } ##################### Plot chordal norms from Simulation Study ####################### #' Function for plotting chordal norms between estimated and true subject score subspaces within the simulation study described in CJIVE manuscript #' #' @description Graphically displays the center and spread of chordal norms for joint/individual subject score subspaces #' #' @param norm.dat data frame with at least the 5 following variables: #' Norm - the value of the norm for a particular subspace; #' Type - the subspace for which the norm is given (i.e., joint and individual subject scores for dataset X1 or X2 (except joint scores, which are for both datasets)) #' Method - the method by which the subspace was estimated, e.g. CJIVE, AJIVE, R.JIVE #' JVE_1 and JVE_2 - labels describing the proportion of joint variation explained in each dataset (and typically the number of variables in dataset X2) #' @param cols a vector of colors, must have length equal to the number of methods used in the simulation #' @param show.legend logical (TRUE/FALSE) for whether a legend should be included in the plot. Default is FALSE #' @param text.size numeric value for the font size #' @param lty linetype (see ggplot2). Default = 1 #' @param y.max maximum value for the horizontal axis of the plot #' @param x.lab.angle angle at which x-axis labels are tilted #' #' @return graphical display (via ggplot2) #' @export gg.score.norm.plot<-function(norm.dat, cols, show.legend = FALSE, text.size, lty = 1, y.max = 1, x.lab.angle = 70){ norm.dat = norm.dat[grep("Score",norm.dat$Type),] labs = levels(norm.dat$Type)[grep("Score",levels(norm.dat$Type))][c(3,1,2)] labs.ex = c("Joint Scores", expression("Indiv Scores"*" X"[1]), expression("Indiv Scores"*" X"[2])) ggplot2::ggplot(data = norm.dat, ggplot2::aes(x = norm.dat$Type, y = norm.dat$Norm)) + ggplot2::geom_boxplot(ggplot2::aes(fill = norm.dat$Method), position = "dodge", outlier.alpha = 0, show.legend = show.legend, linetype = lty, fatten = 0.5) + ggplot2::labs(y = "Chordal Norm", x = "Type") + ggplot2::facet_grid(norm.dat$JVE_2 ~ norm.dat$JVE_1, labeller = ggplot2::label_parsed) + ggplot2::scale_x_discrete(limits = labs, labels = labs.ex) + ggplot2::scale_fill_manual(values=cols, name = "Method") + ggplot2::scale_colour_manual(values=cols) + ggplot2::theme_bw() + ggplot2::coord_cartesian(ylim = c(0, y.max)) + ggplot2::theme(axis.title.x = ggplot2::element_blank(), axis.text.x = ggplot2::element_text(face = "bold", hjust = 01, angle = x.lab.angle, size = text.size-3), text = ggplot2::element_text(size = text.size)) } ##################### Plot chordal norms from Simulation Study ####################### #' Function for plotting chordal norms between estimated and true variable loading subspaces within the simulation study described in CJIVE manuscript #' #' @description Graphically displays the center and spread of chordal norms for joint/individual variable loading subspaces #' #' @param norm.dat data frame with at least the 5 following variables: #' Norm - the value of the norm for a particular subspace; #' Type - the subspace for which the norm is given (i.e., joint/individual variable loadings for dataset X1 or X2) #' Method - the method by which the subspace was estimated, e.g. CJIVE, AJIVE, R.JIVE #' JVE_1 and JVE_2 - labels describing the proportion of joint variation explained in each dataset (and typically the number of variables in dataset X2) #' @param cols a vector of colors, must have length equal to the number of methods used in the simulation #' @param show.legend logical (TRUE/FALSE) for whether a legend should be included in the plot. Default is FALSE #' @param text.size numeric value for the font size #' @param lty linetype (see ggplot2). Default = 1 #' @param y.max maximum value for the horizontal axis of the plot #' @param x.lab.angle angle at which x-axis labels are tilted #' #' @return graphical display (via ggplot2) #' @export gg.load.norm.plot<-function(norm.dat, cols, show.legend = FALSE, text.size, lty = 1, y.max = 1, x.lab.angle = 70){ norm.dat = norm.dat[grep("Load",norm.dat$Type),] labs = levels(norm.dat$Type)[grep("Load",levels(norm.dat$Type))][c(3,4,1,2)] labs.ex = c(expression("Joint Loadings"*" X"[1]),expression("Joint Loadings"*" X"[2]), expression("Indiv Loadings"*" X"[1]), expression("Indiv Loadings"*" X"[2])) ggplot2::ggplot(data = norm.dat, ggplot2::aes(x = norm.dat$Type, y = norm.dat$Norm)) + ggplot2::geom_boxplot(ggplot2::aes(fill = norm.dat$Method), position = "dodge", outlier.alpha = 0, show.legend = show.legend, linetype = lty, fatten = 0.5) + ggplot2::labs(y = "Chordal Norm", x = "Type") + ggplot2::facet_grid(norm.dat$JVE_2 ~ norm.dat$JVE_1, labeller = ggplot2::label_parsed) + ggplot2::scale_x_discrete(limits = labs, labels = labs.ex) + ggplot2::scale_fill_manual(values=cols, name = "Method") + ggplot2::scale_colour_manual(values=cols) + ggplot2::theme_bw() + ggplot2::coord_cartesian(ylim = c(0, y.max)) + ggplot2::theme(axis.title.x = ggplot2::element_blank(), axis.text.x = ggplot2::element_text(face = "bold", hjust = 01, angle = x.lab.angle, size = text.size-3), text = ggplot2::element_text(size = text.size)) } ##################### Plot Pearson correlations from Simulation Study ####################### #' Function for plotting Pearson correlations between predicted and true subject scores within the simulation study described in CJIVE manuscript #' #' @description Graphically displays the center and spread of chordal norms for joint/individual subject score subspaces #' #' @param cor.dat data frame with at least the 5 following variables: #' Norm - the value of the norm for a particular subspace; #' Type - the subspace for which the norm is given (i.e., joint/individual score/loading for dataset X1 or X2 (except for joint scores)) #' Method - the method by which the subspace was estimated, e.g. CJIVE, AJIVE, R.JIVE #' JVE_1 and JVE_2 - labels describing the proportion of joint variation explained in each dataset (and typically the number of variables in dataset X2) #' @param cols a vector of colors, must have length equal to the number of methods used in the simulation #' @param show.legend logical (TRUE/FALSE) for whether a legend should be included in the plot. Default is FALSE #' @param text.size numeric value for the font size #' #' @return graphical display (via ggplot2) #' @export gg.corr.plot<-function(cor.dat, cols, show.legend = FALSE, text.size){ ggplot2::ggplot(data = cor.dat, ggplot2::aes(x = cor.dat$Component, y = cor.dat$Prediction_Correlation)) + ggplot2::geom_boxplot(ggplot2::aes(fill = cor.dat$Type), position = "dodge", outlier.alpha = 0, show.legend = show.legend, fatten = 0.5) + ggplot2::labs(y = "Absolute Pearson Correlation", x = "Component") + ggplot2::facet_grid(cor.dat$JVE_2 ~ cor.dat$JVE_1, labeller = ggplot2::label_parsed) + ggplot2::scale_fill_manual(values=cols, name = "Method") + ggplot2::scale_colour_manual(values=cols) + ggplot2::theme_bw() + ggplot2::theme(text = ggplot2::element_text(size = text.size)) } ##################### Plot Ranks CJIVE from Simulation Study ####################### #' Function for plotting selected joint ranks #' #' @description Graphically displays the count of joint ranks selected by each method employed in the simulation study described in the CJIVE manuscript #' #' @param rank.dat data frame expected to be built with the functions dplyr::count and tidyr::complete, which should include the following variables #' Rank - numeric values of the rank selected by each method in each replicate simulation #' n - the number of times this value was selected as the rank #' Type - the subspace for which the norm is given (i.e., joint/individual score/loading for dataset X1 or X2 (except for joint scores)) #' Method - the method by which the subspace was estimated, e.g. CJIVE, AJIVE, R.JIVE #' JVE_1 and JVE_2 - labels describing the proportion of joint variation explained in each dataset (and typically the number of variables in dataset X2) #' @param cols a vector of colors, must have length equal to the number of methods used in the simulation #' @param show.legend logical (TRUE/FALSE) for whether a legend should be included in the plot. Default is FALSE #' @param text.size numeric value for the font size #' @param num.sims numeric value for the number of replicates evaluated in each full combination of experimental settings #' #' @return graphical display (via ggplot2) #' @export gg.rank.plot<-function(rank.dat, cols, show.legend = FALSE, text.size, num.sims){ ggplot2::ggplot(data = rank.dat, ggplot2::aes(x = rank.dat$Rank, y = rank.dat$n/num.sims, fill=rank.dat$Method)) + ggplot2::geom_bar(position = ggplot2::position_dodge(), stat = "identity", width = 0.6, show.legend = show.legend) + ggplot2::labs(y = "Proportion", x = "Selected Rank") + ggplot2::facet_grid(rank.dat$JVE_2 ~ rank.dat$JVE_1, labeller = ggplot2::label_parsed) + ggplot2::scale_fill_manual(values=cols, name = "Method") + ggplot2::theme_bw() + ggplot2::theme(text = ggplot2::element_text(size = text.size)) } ##################### 'Melts' correlations from prediction portion of simulation study to prepare for plotting ####################### #' Converts correlations of predicted to true joint subject scores to a format conducive to ggplot2 #' #' @description Converts correlations of predicted to true joint subject scores into a format conducive to ggplot2 #' #' @param sim.dat matrix with each row representing results from a replicate in the simulation study described in CJIVE manuscript #' @param r.J (Numeric/integer) the joint rank, i.e. number of components in the joint subspace #' @param p1 number of variables/features in data set X1 #' @param p2 number of variables/features in data set X2 #' #' @return data frame with seven columns: one each for the joint variance explained in each data set, #' one column containing the method by which predictions were obtained, #' one column containing the component number (1,...,r.J), #' #' @export ############## Prepare data from prediction portion of simulation study for graphical display ################ Melt.Sim.Cors<-function(sim.dat,r.J,p1,p2){ JVE1.labs = c(bquote("R"[J1]^2*"=0.05, p"[1]*"="*.(p1)), bquote("R"[J1]^2*"=0.5, p"[1]*"="*.(p1))) JVE2.labs = c(bquote("R"[J2]^2*"=0.05, p"[2]*"="*.(p2)), bquote("R"[J2]^2*"=0.5, p"[1]*"="*.(p2))) CC.PredCors.melt = reshape2::melt(sim.dat, id.vars = c("JntVarEx1", "JntVarEx2"), measure.vars = paste("CC_Pred_Corr", 1:r.J, sep = ""), variable_name = "Component", value.name = "Prediction_Correlation") colnames(CC.PredCors.melt)[which(colnames(CC.PredCors.melt)=="variable")]="Component" colnames(CC.PredCors.melt)[which(colnames(CC.PredCors.melt)=="value")]="Prediction_Correlation" levels(CC.PredCors.melt$Component) = paste("No.", 1:r.J) CC.PredCors.melt$Type = factor(1, levels = 1:3, labels = c("CJIVE-Prediction", "G-inverse Prediction", "R.JIVE-Prediction")) A.PredCors.melt = reshape2::melt(sim.dat, id.vars = c("JntVarEx1", "JntVarEx2"), measure.vars = paste("AJIVE_Pred_Corr", 1:r.J, sep = ""), variable_name = "Component") colnames(A.PredCors.melt)[which(colnames(A.PredCors.melt)=="variable")]="Component" colnames(A.PredCors.melt)[which(colnames(A.PredCors.melt)=="value")]="Prediction_Correlation" levels(A.PredCors.melt$Component) = paste("No.", 1:r.J) A.PredCors.melt$Type = factor(2, levels = 1:3, labels = c("CJIVE-Prediction", "G-inverse Prediction", "R.JIVE-Prediction")) R.JIVE.PredCors.melt = reshape2::melt(sim.dat, id.vars = c("JntVarEx1", "JntVarEx2"), measure.vars = paste("R.JIVE_Pred_Corr", 1:r.J, sep = ""), variable_name = "Component", value.name = "Prediction_Correlation") colnames(R.JIVE.PredCors.melt)[which(colnames(R.JIVE.PredCors.melt)=="variable")]="Component" colnames(R.JIVE.PredCors.melt)[which(colnames(R.JIVE.PredCors.melt)=="value")]="Prediction_Correlation" levels(R.JIVE.PredCors.melt$Component) = paste("No.", 1:r.J) R.JIVE.PredCors.melt$Type = factor(3, levels = 1:3, labels = c("CJIVE-Prediction", "G-inverse Prediction", "R.JIVE-Prediction")) Pred.Cors.melt = rbind(A.PredCors.melt, CC.PredCors.melt, R.JIVE.PredCors.melt) Pred.Cors.melt$Prediction_Correlation = abs(Pred.Cors.melt$Prediction_Correlation) Pred.Cors.melt$JVE_1 = factor(Pred.Cors.melt$JntVarEx1, labels = JVE1.labs) Pred.Cors.melt$JVE_2 = factor(Pred.Cors.melt$JntVarEx2, labels = JVE2.labs) Pred.Cors.melt }
/scratch/gouwar.j/cran-all/cranData/CJIVE/R/SimulationStudyFunctions.R
########### Frobenius Norm of Data Matrix Values ################# #' Matrix variation (i.e. Frobenius norm) #' #' @description Calculates the Frobenius norm of a matrix, which can be used as a measure of total variation #' #' @param X a matrix of any size #' #' @return The Frobenius norm of the matrix X, calculated as the square root of the sum of squared entries in X #' #' @examples #' X = matrix(rnorm(10), 5,2) #' MatVar(X) #' @export MatVar = function(X){ sum(X^2) } ########### Frobenius Norm of Data Matrix Values ################# #' Alternative calculation - Matrix variation (i.e. Frobenius norm) #' #' @description Calculates the Frobenius norm of a matrix, which can be used as a measure of total variation #' #' @param X a matrix of any size #' #' @return The Frobenius norm of the matrix X, calculated as the square root of the trace of t(X)%*%X #' #' @examples #' X = matrix(rnorm(10), 5,2) #' MatVar2(X) #' @export MatVar2 = function(X){ sum(diag(t(X)%*%X)) } ########### Chordal norm for matrices with diff ranks ################## #' Chordal norm between column-subspaces of two matrices #' #' @description Calculates the chordal norm between the column subspaces of two matrices. Matrices must have the same number of rows. Let U_x and U_y represent the singular #' vectors of matrices X and Y, respectively. The chordal norm can be calculated as the square root of the sum of the singular values of t(U_x)%*%U_y #' #' @param X a matrix with the same number of rows as Y and any number of columns #' @param Y a matrix with the same number of rows as X and any number of columns #' @param tol threshold under which singular values of inner product are zeroed out #' #' @return (Numeric) Chordal norm between column-subspaces of X and Y, scaled to the interval [0,1] #' #' @export chord.norm.diff = function(X,Y, tol = 1E-8){ svd.X = svd(X) svd.Y = svd(Y) if(svd.Y$d[1]>0){ Uy = svd.Y$u } else { Uy = matrix(0, dim(svd.Y$u)) } if(svd.X$d[1]>0){ Ux = svd.X$u } else { Ux = matrix(0, dim(svd.X$u)) } k = max(min(sum(svd.X$d > tol), sum(svd.Y$d > tol)),1) inner.prod = t(Ux)%*%Uy sig = round(svd(inner.prod)$d[1:k], 8) sqrt(sum((1 - sig^2))/k) } ############ Convert Vector to Network ############### #' Convert vector to network #' #' @description Converts a vector of size p choose 2 into a p-by-p upper triangular matrix #' #' @param invector numeric vector of size p choose 2 #' #' @return upper triangular p-by-p matrix #' @export vec2net.u = function(invector) { #invector: p x 1, where p is the number of edges nNode = (1 + sqrt(1+8*length(invector)))/2 outNet = matrix(0,nNode,nNode) outNet[upper.tri(outNet,diag = FALSE)] = invector dim(outNet) = c(nNode,nNode) outNet = outNet + t(outNet) # diag(outNet) = 1 outNet } #' Convert vector to network #' #' @description Converts a vector of size p choose 2 into a p-by-p lower triangular matrix #' #' @param invector numeric vector of size p choose 2 #' #' @return lower triangular p-by-p matrix #' @export vec2net.l = function(invector) { #invector: p x 1, where p is the number of edges nNode = (1 + sqrt(1+8*length(invector)))/2 outNet = matrix(0,nNode,nNode) outNet[lower.tri(outNet,diag = FALSE)] = invector outNet = t(outNet) dim(outNet) = c(nNode,nNode) outNet = outNet + t(outNet) # diag(outNet) = 1 outNet } ############ Visually display heatmap of matrix: adapted from Erick Lock's show.image function employed in r.jive package ################### #' Display a heatmap of a matrix (adapted from Erick Lock's show.image function in the r.jive package) #' #' @description Visual display of a matrix as a heatmap with colors determined by entry values, and including a colorbar to aid interpretation of the heatmap #' #' @param Image matrix to display #' @param ylab lab for y-axis of heatmap #' @param xlab lab for x-axis of heatmap #' @param net logical (TRUE/FALUSE) of whether entries correspond to edges between regions of interest in the Power-264 brain atlas. Default is FALSE #' @param main main title for heatmap #' @param sub subtitle for heatmap #' @param colorbar logical (TRUE/FALUSE) of whether colorabar shouldl be included to aid interpretation. Default is TRUE #' #' @return graphical display of matrix as a heatmap #' @export show.image.2<-function (Image, ylab = "", xlab="", net=FALSE, main="", sub="", colorbar = TRUE) { #if(net){Image=Image-diag(Image)} #Image = Image*upper.tri(Image) lower = mean(Image) - 5 * stats::sd(Image) upper = mean(Image) + 5 * stats::sd(Image) Image[Image < lower] = lower Image[Image > upper] = upper if(colorbar){ fields::image.plot(x = 1:dim(Image)[2], y = 1:dim(Image)[1], z = t(Image), zlim = c(lower, upper), axes = FALSE, col = gplots::bluered(100), xlab = xlab, ylab = ylab) graphics::title(main=main, sub = sub) } else if(!colorbar){ graphics::image(x = 1:dim(Image)[2], y = 1:dim(Image)[1], z = t(Image), zlim = c(lower, upper), axes = FALSE, col = gplots::bluered(100), xlab = xlab, ylab = ylab) graphics::title(main=main, sub = sub) } if(net){ mod = utils::read.table("C:/Users/Raphiel\'s PC/Dropbox/JIVE-PNC/PNC-Data/roi_id.txt") mod = mod[,1] Count.m = table(sort(mod)) k = 0 Grid.m = vector() for(i in 1:(length(Count.m)-1)) { k = k + Count.m[i] Grid.m[i] = k } graphics::abline(v=c(0,Grid.m[-1]-32,232)+.5, h=c(0,232-Grid.m[-1]+32,232)+.5) } } ##################### Convert square matrix/network for plotting ####################### #' Function for plotting networks with ggplot #' #' @description Convert matrix representation of a network for graphical display via ggplot #' #' @param gmatrix square matrix of size p-by-p in which entries represent the strength of (un-directed) edges between the p nodes #' @param sort_indices vector of length p by which nodes are sorted. If NULL, then nodes are not sorted. Default is NULL. #' #' @return a data frame of three variables: X1, which represents the row from which the edge comes; X2, which represents the column from which the edge comes; #' 3) value, matrix entry representing the strength of the edge between the nodes represented by X1 and X2 #' @export create.graph.long = function(gmatrix,sort_indices=NULL) { nnode = nrow(gmatrix) X1 = c(1:nnode)%x%rep(1,nnode) X2 = rep(1,nnode)%x%c(1:nnode) X1 = factor(X1, ) if (!is.null(sort_indices)) { gmatrix = gmatrix[sort_indices,sort_indices] } value = as.vector(as.matrix(gmatrix)) data.frame(X1,X2,value) } ############## Function to sign-correct and scale variable loadings ################ #' Scale and sign-correct variable loadings to assist interpretation #' @description Scale loadings for a joint or individual component by its largest absolute value resulting in loadings between -1 and 1. #' Loadings are also sign-corrected to result in positive skewness #' #' @param loading.comp numeric vector of variable loadings from a JIVE analysis #' #' @return numeric vector of loadings which have been scaled and sign-corrected #' @export scale_loadings = function(loading.comp){ x = loading.comp x1 = x/max(abs(x), dna.rm = TRUE) pos = sign(psych::skew(x1, na.rm = TRUE)) ((-1)^(pos))*x1 }
/scratch/gouwar.j/cran-all/cranData/CJIVE/R/Utilities.R
#' Composite kernel association test for SNP-set analysis in pharmacogenetics (PGx) studies. #' @param G - genotype matrix. #' @param Tr - treatment vector, 0 indicates placebo, 1 indicates treatment. #' @param X - non-genetic covariates data matrix. #' @param y - response vector. Currently continuous and binary responses are supported. Survival response will be added soon. #' @param trait - response indicator. trait = "continuous" or "binary". #' @param ker - kernel. ker = "linear", "IBS", "Inter" (interaction kernel) and "RBF" (radial basis function kernel). #' @param grids - grids of the candidate weights. #' @param n_a - the number of intervals for manual integration (when integrate function fails). Default n_a = 1000. #' @param method - method for getting density of A (see details in the reference). Default method is Liu's method. #' @param subdiv - parameter of Davies' method. Default value is 1E6. #' @return pvals - p-values of each individual association test. #' @return finalp - final p-value of the CKAT test. #' @examples #' nsamples = 500; nsnps = 10 #' X = rnorm(nsamples,0,1) #' Tr = sample(0:1,nsamples,replace=TRUE) #' G = matrix(rbinom(nsamples*nsnps, 1, 0.05), nrow = nsamples, ncol = nsnps) #' GxT = G*Tr #' Y0 = 0.5*X + Tr + rnorm(nsamples) #' CKAT(G, Tr, X, Y0, grids=c(0,0.5,1)) #' @export #' @importFrom stats dbeta lm glm integrate qchisq dchisq pchisq resid sigma #' @importFrom CompQuadForm davies liu farebrother CKAT<- function(G, Tr, X, y, trait="continuous", ker="linear", grids=c(0,0.5,1),n_a=1000,method="liu", subdiv=10^6){ #order original data by treatment dat = data.frame(y=y,X=X,Tr=Tr,G=G) dat = dat[order(-dat$Tr),] y = dat[, grepl("^y", names(dat))] X = dat[, grepl("^X", names(dat))] Tr = dat[, grepl("^Tr", names(dat))] G = as.matrix(dat[, grepl("^G", names(dat))]) n1 = sum(Tr) n = length(Tr) maf <- apply(G,2,mean, na.rm=T)/2 weights = dbeta(maf, 1,25) if(ker=="IBS"){ K_G = IBSKern(G, weight = weights^2); K_GxTr = matrix(0,n,n); K_GxTr[1:n1,1:n1] = K_G[1:n1,1:n1] }else if(ker=="linear"){ G.w <- t(t(G) * (weights)) K_G = G.w %*% t(G.w) K_GxTr = matrix(0,n,n); K_GxTr[1:n1,1:n1] = K_G[1:n1,1:n1] }else if(ker=="Inter"){ G.w <- t(t(G) * (weights)) K_G = InterKern(G.w) K_GxTr = matrix(0,n,n); K_GxTr[1:n1,1:n1] = K_G[1:n1,1:n1] } # else if(ker=="RBF"){ # G.w <- t(t(G) * (weights)) # K_G = kernelMatrix(rbfdot(sigma=rbfpara), G.w) # K_GxTr = matrix(0,n,n); K_GxTr[1:n1,1:n1] = K_G[1:n1,1:n1] # } K_G = K_G/n K_GxTr = K_GxTr/n Ks = list() wgrid = 0 for (w in grids){ wgrid = wgrid + 1 K = (1-w)*K_G +w*K_GxTr Ks[[wgrid]] = K } nullCovar = as.matrix(data.frame(Tr,X)) results = Get_CKAT_P(y=y,Ks=Ks,grids=grids,X=nullCovar,ytype=trait,n_a = n_a, method=method, subdiv=subdiv) return(list(pvals=results$pvals, finalp=results$finalp)) }
/scratch/gouwar.j/cran-all/cranData/CKAT/R/CKAT.R
#' @importFrom stats dbeta lm glm integrate qchisq dchisq pchisq #' @importFrom CompQuadForm davies liu farebrother #' Get_CKAT_P <- function(y, Ks, grids, X = NULL, ytype="continuous", n_a = 1000,method="liu", subdiv=10^4){ n = length(y) if(ytype=="continuous"){ if (is.null(X)) { p = 1 X1 = matrix(1, nrow=n) mod = glm(y~1, family = "gaussian") } else { p = ncol(X) X1 = cbind(1, X) mod = glm(y~X, family = "gaussian") } s2 = sigma(mod)^2 D0 = diag(n) M = resid(mod)/sqrt(s2) P0= (D0 - X1%*%solve(t(X1)%*%X1)%*%t(X1)) S = sapply(Ks, getIndivP, M, P0, s2=1) pvals = unlist(S[7,]) w = min(pvals) }else if(ytype=="binary"){ if (is.null(X)) { p = 1 X1 = matrix(1, nrow=n) mod = glm(y~1, family = "binomial") } else { p = ncol(X) X1 = cbind(1, X) mod = glm(y~X, family = "binomial") } mu = mod$fitted.values D = diag(mu*(1-mu)) D.5 = 1/sqrt((mu*(1-mu))) res = y - mu DX1 = mu * (1-mu) * X1 gg = X1 %*% solve(t(X1) %*% (DX1)) %*% t(DX1) P0 = D - diag(D)*gg S = sapply(Ks, getIndivP_hm, res, mu, D.5, P0) pvals = unlist(S[1,]) w = min(pvals) } if(w==0){ finalp = tempint = 0 }else{ nlist = length(Ks) K_G = Ks[[1]] n1 = sum(X[,1]) K1 = K_G[1:n1,1:n1]; K2 = K_G[(n1+1):n,(n1+1):n]; K12 = K_G[1:n1,(n1+1):n]; eig1val = Get_Lambda(K1) eig2val = Get_Lambda(K2) eigval_Ks = sapply(Ks, Get_Lambda) q_Ks = sapply(eigval_Ks,function(x)Get_Q_quantile(w, x, method="liu")) grids[grids==1] = 1-1e-16 get_c = Vectorize(function(x)min((q_Ks-x)/(1-grids))) eig12val = svd(K12)$d eig12val = eig12val[eig12val>1e-10] mu_B = sum(eig2val) v_B = 2*sum(eig2val^2) v_C = sum(eig12val^2) if(method=="davies"){ if(w>1e-2){ F_B = Vectorize(function(x)davies(sqrt(v_B)/(sqrt(v_B+4*v_C))*(get_c(x) - mu_B) + mu_B,eig2val, acc = 1e-4)$Qq) }else{ F_B = Vectorize(function(x)davies(sqrt(v_B)/(sqrt(v_B+4*v_C))*(get_c(x) - mu_B) + mu_B,eig2val, acc = 1e-7)$Qq) } }else if(method=="farebrother"){ F_B = Vectorize(function(x)farebrother(sqrt(v_B)/(sqrt(v_B+4*v_C))*(get_c(x) - mu_B) + mu_B,eig2val)$Qq) }else if(method=="liu"){ F_B = Vectorize(function(x)liu(sqrt(v_B)/(sqrt(v_B+4*v_C))*(get_c(x) - mu_B) + mu_B,eig2val)) } upper1 = Get_Q_quantile(1e-10, eig1val) lower1 = 0# intgr1 = try(integrate(function(x)Get_Q_density(x, eig1val,method="liu")*F_B(x), lower1, upper1,subdivisions = subdiv)$value,silent=TRUE) tempint = intgr1 if(w<1e-2){ intgr1 = intgr1/(F_B(upper1)-F_B(lower1)) + abs(1-try(integrate(function(x)Get_Q_density(x, eig1val,method="liu"), lower1, upper1,subdivisions = subdiv)$value,silent=TRUE)) } intgr = intgr1 if(class(intgr)=="try-error"){ a = seq(lower1,upper1,length.out=n_a) delta_a = a[2] - a[1] f_A = Get_Q_density(a, eig1val,method="liu") dnsty = sum(f_A)*delta_a intgr1 = sum(f_A*F_B(a))*delta_a intgr = abs(1-dnsty) + intgr1 } finalp = intgr } return(list(pvals=pvals,pval_original=tempint,finalp=finalp)) } #Get_Liu_Params_Mod_Lambda function is adapted from R SKAT package https://github.com/cran/SKAT/ Get_Upper <- function(p, lambda){ param = Get_Liu_Params_Mod_Lambda(lambda) muQ <- param$muQ muX <- param$muX varQ<- param$sigmaQ^2 varX<- param$sigmaX^2 delta = 0*param$d df<-param$l upper = 5*((qchisq(1-1e-10,df=df) - df)/sqrt(2*df) *sqrt(varQ) + muQ) lower = 0 q = mean(c(upper,lower)) val = dchisq((q-muQ)/sqrt(varQ)*sqrt(varX)+muX, df, delta) * sqrt(varX)/sqrt(varQ) flag = 1 while(abs(val-p)/p>1e-2&flag<100){ if(val<p){ upper = q q = mean(c(upper,lower)) val = dchisq((q-muQ)/sqrt(varQ)*sqrt(varX)+muX, df, delta) * sqrt(varX)/sqrt(varQ) }else{ lower = q q = mean(c(upper,lower)) val = dchisq((q-muQ)/sqrt(varQ)*sqrt(varX)+muX, df, delta) * sqrt(varX)/sqrt(varQ) } flag = flag + 1 } return(q) } Get_Q_density <- function(q, lambda, method="liu"){ if(method=="liu"){ param = Get_Liu_Params_Mod_Lambda(lambda) muQ <- param$muQ muX <- param$muX varQ<- param$sigmaQ^2 varX<- param$sigmaX^2 delta = 0*param$d df<-param$l dchisq((q-muQ)/sqrt(varQ)*sqrt(varX)+muX, df, delta) * sqrt(varX)/sqrt(varQ) }else if(method=="farebrother"){ sapply(q, function(x) farebrother(x, lambda)$dnsty) }else if(method=="mixed"){ param = Get_Liu_Params_Mod_Lambda(lambda) muQ <- param$muQ muX <- param$muX varQ<- param$sigmaQ^2 varX<- param$sigmaX^2 delta = 0*param$d df<-param$l id1 = which(q>muQ) id2 = which(q<=muQ) dnsty1 = dchisq((q-muQ)/sqrt(varQ)*sqrt(varX)+muX, df, delta) * sqrt(varX)/sqrt(varQ) dnsty2 = sapply(q, function(x) farebrother(x, lambda)$dnsty) pmax(dnsty1,dnsty2) } } Get_Q_quantile<-function(p, lambda,method="davies"){ # p is the p-value, i.e. right-tail probability param = Get_Liu_Params_Mod_Lambda(lambda) muQ <-param$muQ varQ<-param$sigmaQ^2 df<-param$l q.org<-qchisq(1-p,df=df) q.liu = (q.org - df)/sqrt(2*df) *sqrt(varQ) + muQ if(method=="liu"){ return(q.liu) }else if(method=="davies"){ lower = 0.2*q.liu upper = 5*q.liu p.davies = davies(mean(c(lower,upper)), lambda, acc = 1e-8)$Qq flag = 1 while(abs(p-p.davies)/p>1e-8&flag<100){ if(p.davies>p){ lower = mean(c(lower,upper)) }else{ upper = mean(c(lower,upper)) } p.davies = davies(mean(c(lower,upper)), lambda, acc = 1e-8)$Qq flag = flag + 1 } return(mean(c(lower,upper))) } } ######################### #MiRKAT Helper Functions# ######################### # Adapt from R MiRKAT package https://github.com/cran/MiRKAT Get_Var_Elements =function(m4,u1,u2){ temp1 = u1^2 * u2^2 a1 = sum(m4 * temp1) a2 = sum(u1^2) * sum(u2^2) - sum(temp1) a3 = sum(u1*u2)^2 - sum(temp1) return(a1+a2+2*a3) } getIndivP_hm = function(K, res, mu, D0, P0){ Q = t(res)%*% K %*% res # K1 = 1/D0 * P01 %*% K %*% t(1/D0 * P01 ) K1 = P0 %*% (D0*t(D0*K)) %*% P0 eK = eigen(K1, symmetric = T) # Instead of matching the first two moments, match to the fourth moment # Code adapted from SKAT package lambda = eK$values[eK$values > 1e-10] U = as.matrix(eK$vectors[,eK$values > 1e-10]) p.m = length(lambda) m4 = (3*mu^2-3*mu +1)/(mu*(1-mu)) zeta =rep(0,p.m) var_i=rep(0,p.m) varQ = 0 for(i in 1:p.m){ # The diagonals temp.M1 = sum(U[,i]^2)^2 - sum(U[,i]^4) zeta[i] = sum(m4 * U[,i]^4) + 3* temp.M1 # because ( \sum .)^4, not ^2 var_i[i]= zeta[i] - 1 } if(p.m == 1){ Cov_Mat = matrix(zeta* lambda^2, ncol=1,nrow=1) } else if(p.m > 1){ Cov_Mat = diag(zeta* lambda^2) for(i in 1:(p.m-1)){ for(j in (i+1):p.m){ Cov_Mat[i,j] = Get_Var_Elements(m4,U[,i],U[,j]) Cov_Mat[i,j] = Cov_Mat[i,j]* lambda[i]* lambda[j] } } } Cov_Mat = Cov_Mat + t(Cov_Mat) diag(Cov_Mat) = diag(Cov_Mat)/2 varQ = sum(Cov_Mat) - sum(lambda)^2 muQ = sum(lambda) lambda.new = lambda * sqrt(var_i)/sqrt(2) df = sum(lambda.new^2)^2/sum(lambda.new^4) Q_corrected= (Q - muQ)*sqrt(2*df)/sqrt(varQ) + df p_corrected= 1 - pchisq(Q_corrected ,df = df) p_corrected = ifelse(p_corrected <0, 0, p_corrected) return(list(p_hm= p_corrected, Q = Q, muQ = muQ, varQ = varQ, df = df)) } getIndivP <- function(K, res, P0, s2) { ## gets all of the parameters necessary for each kernel S = t(res)%*%K%*%res/s2 #S = t(res)%*%K%*%res W = P0%*%K%*%P0 scale = sum(diag(W)) ee = eigen(W, symmetric = T) w = which(ee$values>1e-10) pvals = davies(S,ee$values[w], acc = 1e-4)$Qq if(pvals<1e-3){ pvals = davies(S,ee$values[w], acc = 1e-7)$Qq } return(list(S=S, W = W,scale = scale, m = length(w), evals = ee$values[w], evecs = ee$vectors[,w], pvals = pvals)) } ####################### #SKAT Helper Functions# ####################### # Adapt from R SKAT package https://github.com/cran/SKAT/ Get_Liu_Params_Mod_Lambda<-function(lambda){ ## Helper function for getting the parameters for the null approximation c1<-rep(0,4) for(i in 1:4){ c1[i]<-sum(lambda^i) } muQ<-c1[1] sigmaQ<-sqrt(2 *c1[2]) s1 = c1[3] / c1[2]^(3/2) s2 = c1[4] / c1[2]^2 beta1<-sqrt(8)*s1 beta2<-12*s2 type1<-0 #print(c(s1^2,s2)) if(s1^2 > s2){ a = 1/(s1 - sqrt(s1^2 - s2)) d = s1 *a^3 - a^2 l = a^2 - 2*d } else { type1<-1 l = 1/s2 a = sqrt(l) d = 0 } muX <-l+d sigmaX<-sqrt(2) *a re<-list(l=l,d=d,muQ=muQ,muX=muX,sigmaQ=sigmaQ,sigmaX=sigmaX) return(re) } Get_Lambda <- function(K){ out.s<-eigen(K,symmetric=TRUE, only.values = TRUE) lambda1<-out.s$values IDX1<-which(lambda1 >= 1e-10) # eigenvalue bigger than sum(eigenvalues)/1000 IDX2<-which(lambda1 > sum(lambda1[IDX1])/1000) if(length(IDX2) == 0){ stop("No Eigenvalue is bigger than 0!!") } lambda<-lambda1[IDX2] return(lambda) } ################## #Kernel Functions# ################## # IBS Kernel # Adapt from https://msu.edu/~qlu/doc/function.r IBSKern=function(geno, weight = 1){ g=geno p=dim(g)[2] #number of SNPs n=dim(g)[1] #number of subjects wt = weight k_g=matrix(NA,ncol=n,nrow=n) gtemp1 = gtemp2 = geno; gtemp1[geno==2] = 1;gtemp2[geno==1] = 0;gtemp2[geno==2] = 1; gtemp = cbind(gtemp1,gtemp2); Inner = gtemp%*%diag(wt,nrow=2*p,ncol=2*p)%*%t(gtemp); X2 = matrix(diag(Inner),nrow=n,ncol=n); Y2 = matrix(diag(Inner),nrow=n,ncol=n,byrow=T); Bound = sum(matrix(wt,nrow=1,ncol=p)*2); Dis = (X2+Y2-2*Inner); k_g = (Bound-Dis); return(k_g) } # Interactive Kernal InterKern=function(x){ x=as.matrix(x) x=t(x) Kernel=((1+crossprod(x))^2-crossprod(x^2))/2-0.5 return(Kernel) }
/scratch/gouwar.j/cran-all/cranData/CKAT/R/functions.R
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' Eigen_C #' @param As A sysmetric matrix #' @keywords internal Eigen_C <- function(As) { .Call('_CKLRT_Eigen_C', PACKAGE = 'CKLRT', As) } #' Eigen_C_value #' @param As A sysmetric matrix #' @keywords internal Eigen_C_value <- function(As) { .Call('_CKLRT_Eigen_C_value', PACKAGE = 'CKLRT', As) } #' MatMult_C #' @param A first matrix #' @param B second matrix #' @keywords internal MatMult_C <- function(A, B) { .Call('_CKLRT_MatMult_C', PACKAGE = 'CKLRT', A, B) } #' Sum_C #' @param AA Vector #' @keywords internal Sum_C <- function(AA) { .Call('_CKLRT_Sum_C', PACKAGE = 'CKLRT', AA) } #' ColSum_C #' @param AA Matrix #' @keywords internal ColSum_C <- function(AA) { .Call('_CKLRT_ColSum_C', PACKAGE = 'CKLRT', AA) } #' MatrixRowMax_C #' @param AA Matrix #' @keywords internal MatrixRowMax_C <- function(AA) { .Call('_CKLRT_MatrixRowMax_C', PACKAGE = 'CKLRT', AA) } #' Elementwisesquare_C #' @param AA Matrix #' @keywords internal Elementwisesquare_C <- function(AA) { .Call('_CKLRT_Elementwisesquare_C', PACKAGE = 'CKLRT', AA) } #' VecMultMat_C #' @param A Vector #' @param B Matrix #' @keywords internal VecMultMat_C <- function(A, B) { .Call('_CKLRT_VecMultMat_C', PACKAGE = 'CKLRT', A, B) } #' Vecplus_C #' @param A Vector #' @param B Vector #' @keywords internal Vecplus_C <- function(A, B) { .Call('_CKLRT_Vecplus_C', PACKAGE = 'CKLRT', A, B) } #' ColSumtwomatrix_C #' @param AA Matrix #' @param BB Matrix #' @keywords internal ColSumtwomatrix_C <- function(AA, BB) { .Call('_CKLRT_ColSumtwomatrix_C', PACKAGE = 'CKLRT', AA, BB) } #' ifelsetest_C #' @param x Vector #' @keywords internal ifelsetest_C <- function(x) { .Call('_CKLRT_ifelsetest_C', PACKAGE = 'CKLRT', x) } #' MatrixPlus_C #' @param A First Matrix #' @param B Second Matrix #' @keywords internal MatrixPlus_C <- function(A, B) { .Call('_CKLRT_MatrixPlus_C', PACKAGE = 'CKLRT', A, B) } #' NumxMatrix_C #' @param A Number #' @param B Matrix #' @keywords internal NumxMatrix_C <- function(A, B) { .Call('_CKLRT_NumxMatrix_C', PACKAGE = 'CKLRT', A, B) } #' LR0_fixRho_C #' @param LamdasR Lamda Number #' @param muR mu vector #' @param w1R w1 vector #' @param w2R w2 vector #' @param nminuspx n-px #' @keywords internal LR0_fixRho_C <- function(LamdasR, muR, w1R, w2R, nminuspx) { .Call('_CKLRT_LR0_fixRho_C', PACKAGE = 'CKLRT', LamdasR, muR, w1R, w2R, nminuspx) } #' doubleloop #' @param K1R K1 matrix #' @param K2R K2 matrix #' @param P0R P0 matrix #' @param AR A matrix #' @param U1R U1 vector #' @param wR w matrix #' @param LamdasR Lamdas vector #' @param nminuspx n-px #' @param all_rho the rho vector #' @param LR0_allRhoR the matrix of likelihood ratio #' @keywords internal doubleloop <- function(K1R, K2R, P0R, AR, U1R, wR, LamdasR, nminuspx, all_rho, LR0_allRhoR) { .Call('_CKLRT_doubleloop', PACKAGE = 'CKLRT', K1R, K2R, P0R, AR, U1R, wR, LamdasR, nminuspx, all_rho, LR0_allRhoR) } #' LR0_fixRho_LRT_C #' @param LamdasR Lamda Number #' @param muR mu vector #' @param w1R w1 vector #' @param w2R w2 vector #' @param nminuspx n-px #' @param xiR Vector #' @keywords internal LR0_fixRho_LRT_C <- function(LamdasR, muR, w1R, w2R, nminuspx, xiR) { .Call('_CKLRT_LR0_fixRho_LRT_C', PACKAGE = 'CKLRT', LamdasR, muR, w1R, w2R, nminuspx, xiR) } #' doubleloop_LRT #' @param K1R K1 matrix #' @param K2R K2 matrix #' @param P0R P0 matrix #' @param AR A matrix #' @param U1R U1 vector #' @param wR w matrix #' @param LamdasR Lamdas vector #' @param nminuspx n-px #' @param all_rho rho vector #' @param LR0_allRhoR LR0_allRhomatrix #' @keywords internal doubleloop_LRT <- function(K1R, K2R, P0R, AR, U1R, wR, LamdasR, nminuspx, all_rho, LR0_allRhoR) { .Call('_CKLRT_doubleloop_LRT', PACKAGE = 'CKLRT', K1R, K2R, P0R, AR, U1R, wR, LamdasR, nminuspx, all_rho, LR0_allRhoR) }
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/RcppExports.R
#' Title #' #' @param null a vector of likelihood ratio under the null hypothesis. Generated from simulation #' @param LR the likelihood of the data #' @param qmax quantile of likelihood ratio vector. Most time put as 1, all the likelihood ratio vector under the null hypothesis will be used #' @keywords internal getp_Qreg_logP = function(null, LR, qmax = 1){ # minimize lse between log theoratical p and empirical p # qmax =1, all LR0 are used. prop = mean(null == 0) # probability of being zero null2= null[null > 0] null2= null2[null2 >= stats::quantile(null2, 1-qmax)] f = function(x){ # objective function wrt scale, dof scl = x[1]; dof = x[2] the_p = 1 - stats::pchisq(null2/scl, df = dof) emp_p = 1 - (rank(null2)-0.5)/length(null2) # bigger null2, smaller p rr = sum(log(the_p) -log(emp_p))^2 return(rr) } test= stats::optim(c(0.5, 0.1) , f) scl = test$par[1] dof = test$par[2] final_p =(1-prop)*stats::pchisq(scl*LR, df = dof, lower.tail = F) return(list(p= final_p, prob_0 = prop, a = scl, d = dof)) } #' Title #' #' @param null a vector of likelihood ratio under the null hypothesis. Generated from simulation #' @param LR the likelihood of the data #' @param qmax quantile of likelihood ratio vector. Most time put as 1, all the likelihood ratio vector under the null hypothesis will be used #' @keywords internal getp_Qreg_P = function(null, LR, qmax = 1){ # minimize lse between theoratical p and empirical p # qmax =1, all LR0 are used. prop = mean(null == 0) # probability of being zero null2= null[null > 0] null2= null2[null2 >= stats::quantile(null2, 1-qmax)] f = function(x){ # objective function wrt scale, dof scl = x[1]; dof = x[2] the_p = 1 - stats::pchisq(null2/scl, df = dof) emp_p = 1 - (rank(null2)-0.5)/length(null2) # bigger null2, smaller p rr = sum(the_p -emp_p)^2 return(rr) } test= stats::optim(c(0.5, 0.1) , f) scl = test$par[1] dof = test$par[2] final_p =(1-prop)*stats::pchisq(scl*LR, df = dof, lower.tail = F) return(list(p= final_p, prob_0 = prop, a = scl, d = dof)) } #' Title #' #' @param null a vector of likelihood ratio under the null hypothesis. Generated from simulation #' @param LR the likelihood of the data #' @param qmax quantile of likelihood ratio vector. Most time put as 1, all the likelihood ratio vector under the null hypothesis will be used #' @keywords internal getp_Qreg_dir = function(null, LR, qmax = 1){ # minimize lse between LR0 and theoratical quantile of aChi_d prop = mean(null == 0) # probability of being zero null2= null[null > 0] null2= null2[null2 >= stats::quantile(null2, 1-qmax)] f = function(x){ # objective function wrt scale, dof scl = x[1]; dof = x[2] emp_p = (rank(null2)-0.5)/length(null2) the_q = scl *stats::qchisq(p = emp_p , df = dof) rr = sum(the_q -null2)^2 return(rr) } test= stats::optim(c(0.5, 0.1) , f) scl = test$par[1] dof = test$par[2] final_p =(1-prop)*stats::pchisq(scl*LR, df = dof, lower.tail = F) return(list(p= final_p, prob_0 = prop, a = scl, d = dof)) }
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/getp_Qreg_logP.R
#' Title #' #' @param null a vector of likelihood ratio under the null hypothesis. Generated from simulation #' @param LR the likelihood of the data #' @keywords internal getp_au1 = function(null, LR){ t1 = mean(null) t2 = mean(null^2) B = max(0,1-3*t1^2/t2) # avoid negative probabiltiy A = t1/(1 - B) p =(1-B)*pchisq(A*LR, df = 1, lower.tail = F) return(list(p= p, prob_0 = B, a = A)) }
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/getp_au1.R
#' Title #' #' @param null a vector of likelihood ratio under the null hypothesis. Generated from simulation #' @param LR the likelihood of the data #' @keywords internal getp_aud_estimate_pi_first = function(null, LR){ prop = mean(null == 0) # probability of being zero null2 = null[null > 0] # Match two moments t1 = mean(null2) t2 = mean(null2^2) d = 2*t1^2/(t2-t1^2) a = t1/d p =(1-prop)*pchisq(a*LR, df = d, lower.tail = F) return(list(p= p, prob_0 = prop, a = a, d = d )) }
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/getp_aud_estimate_pi_first.R
#' Composite kernel machine regression based likelihood ratio test. #' #' Composite kernel machine regression based likelihood ratio test. The approximate method for likelihood ratio test tend to be too conservative for small alpha values. We recommend not using it in GWAS #' @param y : y is the vecgtor of the continous outcomes. #' @param X : X denotes the additional covariates. #' @param K1 : K1 is the first kernel corresponding to the genetic main effect. #' @param K2 : K2 is the second kernel corresponding to the genetic and environment interaction effect. #' @param N : N is th total number of randomly generated normal variables used to generate the emprical null distribution of LRT. Default value is 10,000. #' @param length.lambda : the length of lambda. Dafult value is 200. The values of lambda are all more than 0. #' @param length.rho : the length of rho. Default value is 21. The values of rho are between 0 and 1. #' #' @return the result is a list containing three elements. 1. p.dir is the p-value of likelihood ratio test based on emprical distrition. 2. p.aud is the p-value by approximating the null distribution as a mixture of a point mass at zero with probability b and weighted chi square distribution with d degrees of freedom with probality of 1-b. 3. LR is the likelihood ratio test statistics. #' @export #' #' @examples #' set.seed(6) #' n = 50 # the number of observations #' X = rnorm(n) # the other covariates #' p = 2 # two snp in a gene will be simulated #' G = runif(n*p)< 0.5 #' G = G + runif(n*p) < 0.5 #' G = matrix(G, n,p) #genetic matrix #' E = (runif(n) < 0.5)^2 #enviroment effect #' y = rnorm(n) + G[,1] * 0.3 #observations #' omniLRT_fast(y, X = cbind(X, E),K1 = G %*% t(G),K2 = (G*E) %*% t(G * E)) #' @importFrom MASS ginv #' @import nlme #' @import Rcpp #' @import mgcv #' @import compiler #' @import stats omniLRT_fast = function(y, X,K1, K2, N = 10000,length.lambda = 200, length.rho = 21){ method = "ML" Lambdas = exp(seq(from = -12, to = 12, length.out = length.lambda)) all_rho = seq(from = 0,to = 1, length.out = length.rho) n = length(y) if (is.null(X)){ X1 = matrix(1, nrow=n) px = 1 }else{ X1 = cbind(1,X) px = ncol(X1) } XX = MatMult_C(t(X1),X1) P0 = diag(n)- MatMult_C(MatMult_C(X1,ginv(XX)),t(X1)) eP = Eigen_C(P0) A = eP$vector[,eP$values > 1e-10] # invP = ginv(P0) # A2 = eP$vectors %*% diag(eP$values) eK1 = Eigen_C(K1) wK1 = which(eK1$values > 1e-10) # phi1 = t(t(eK1$vectors[,wK1])*sqrt(eK1$values[wK1])) if (length(wK1) == 1){ phi1 = eK1$vectors[,wK1] * sqrt(eK1$values[wK1]) }else{ phi1 = t(t(eK1$vectors[,wK1])*sqrt(eK1$values[wK1])) } eK2 = Eigen_C(K2) wK2 = which(eK2$values > 1e-10) if (length(wK2) == 1){ phi2 = eK2$vectors[,wK2] * sqrt(eK2$values[wK2]) }else{ phi2 = t(t(eK2$vectors[,wK2])*sqrt(eK2$values[wK2])) } group= rep(1,n) if(is.null(X)){ fit1 = lme(y~1, random = list(group=pdIdent(~-1+phi1), group = pdIdent(~-1+phi2)), method = "ML") # Default = REML fit0 = stats::lm(y~1) LR = max(0, 2*(stats::logLik(fit1, REML = F) -stats::logLik(fit0, REML = F))) }else{ fit1 = lme(y~X, random = list(group=pdIdent(~-1+phi1), group = pdIdent(~-1+phi2)), method = "ML") # Default = REML fit0 = stats::lm(y~X) LR = max(0, 2*(stats::logLik(fit1, REML = F) -stats::logLik(fit0, REML = F))) } if (LR <= 0){ p.dir = 1; p.au1=1; p.aud = 1 }else{ #For the first kernel LR0_allRho = matrix(NA, N, length.rho) #set.seed(123) w = matrix(stats::rnorm(N*(n-px)), n-px,N) LR0_fixRho = matrix(NA, N, length.lambda) # The baseline W1 rho = 0 # K = rho*K1 + (1-rho)*K2 = K2 K = K2 k = length(wK2) xi = eK2$values[wK2] mu = Eigen_C_value(t(phi2) %*% P0%*% phi2) # mu = eigen(P0 %*% K2)$values mu = mu/max(mu, xi) xi = xi/max(mu,xi) AKA = MatMult_C(MatMult_C(t(A),K),A) eV = Eigen_C(AKA) U_1 = eV$vectors w.double = w^2 w1 = (w.double)[1:k,] w2 = ColSum_C((w.double)[-(1:k),]) if (length(mu) < k){mu = c(mu,rep(0, k - length(mu)))} if (length(xi) < k){xi = c(xi,rep(0, k - length(xi)))} LR0_fixRho <- LR0_fixRho_LRT_C(Lambdas, mu, w1, w2, n-px, xi) LR0_allRho[,1] = MatrixRowMax_C(LR0_fixRho) LR0_allRho <- doubleloop_LRT(K1, K2, P0, A, U_1, w, Lambdas, n-px, all_rho, LR0_allRho) LR0 = MatrixRowMax_C(LR0_allRho) LR0 = ifelse(LR0 > 0, LR0, 0) p.dir = mean(LR < LR0) p.aud= getp_aud_estimate_pi_first(null = LR0, LR = LR)$p } out = list(p.dir = p.dir,p.aud = p.aud, LR = LR) return(out) }
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/omniLRT_fast.R
#' Composite kernel machine regression based restricted likelihood ratio test #' #' @param y vector of the continous outcomes. #' @param X the additional covariates. #' @param K1 the first kernel corresponding to the genetic main effect. #' @param K2 the second kernel corresponding to the genetic and environment interaction effect. #' @param N total number of randomly generated normal variables used to generate the emprical null distribution of LRT. Default value is 10,000. #' @param length.lambda the length of lambda. Dafult value is 200. The values of lambda are all more than 0. #' @param length.rho the length of rho. Default value is 21. The values of rho are between 0 and 1. #' #' @return the result is a list containing three elements. 1. p.dir is the p-value of restricted likelihood ratio test based on emprical distrition. 2. p.aud is the p-value by approximating the null distribution as a mixture of a point mass at zero with probability b and weighted chi square distribution with d degrees of freedom with probality of 1-b. 3. LR is the likelihood ratio test statistics. #' @export #' #' @examples #' set.seed(6) #' n = 50 # the number of observations #' X = rnorm(n) # the other covariates #' p = 2 # two snp in a gene will be simulated #' G = runif(n*p)< 0.5 #' G = G + runif(n*p) < 0.5 #' G = matrix(G, n,p) #genetic matrix #' E = (runif(n) < 0.5)^2 #enviroment effect #' y = rnorm(n) + G[,1] * 0.3 #observations #' omniRLRT_fast(y, X = cbind(X, E),K1 = G %*% t(G),K2 = (G*E) %*% t(G * E)) #' @importFrom MASS ginv #' @import nlme #' @import Rcpp #' @import mgcv #' @import compiler omniRLRT_fast = function(y, X,K1, K2, N = 10000, length.rho = 200, length.lambda = 21){ method = "REML" Lambdas = exp(seq(from = -12, to = 12, length.out = length.lambda)) all_rho = seq(from = 0,to = 1, length.out = length.rho) n = length(y) if (is.null(X)){ X1 = matrix(1, nrow=n) px = 1 }else{ X1 = cbind(1,X) px = ncol(X1) } XX = MatMult_C(t(X1),X1) P0 = diag(n)- MatMult_C(MatMult_C(X1,ginv(XX)),t(X1)) eP = Eigen_C(P0) A = eP$vector[,eP$values > 1e-10] # invP = ginv(P0) # A2 = eP$vectors %*% diag(eP$values) eK1 = Eigen_C(K1) wK1 = which(eK1$values > 1e-10) # phi1 = t(t(eK1$vectors[,wK1])*sqrt(eK1$values[wK1])) if (length(wK1) == 1){ phi1 = eK1$vectors[,wK1] * sqrt(eK1$values[wK1]) }else{ phi1 = t(t(eK1$vectors[,wK1])*sqrt(eK1$values[wK1])) # this actually works for all of them } eK2 = Eigen_C(K2) wK2 = which(eK2$values > 1e-10) if (length(wK2) == 1){ phi2 = eK2$vectors[,wK2] * sqrt(eK2$values[wK2]) }else{ phi2 = t(t(eK2$vectors[,wK2])*sqrt(eK2$values[wK2])) } # if wK1 and wK2 are 1, what would this happen to others? group= rep(1,n) fit1 = lme(y~X, random = list(group=pdIdent(~-1+phi1), group = pdIdent(~-1+phi2))) # Default = REML fit0 = lm(y~X) LR = max(0, 2*(logLik(fit1, REML = T) -logLik(fit0, REML = T))) if (LR <= 0){ p.dir =p.au1= p.aud = 1 }else{ #For the first kernel LR0_allRho = matrix(NA, N, length.rho) #set.seed(123) w = matrix(rnorm(N*(n-px)), n-px,N) LR0_fixRho = matrix(NA, N, length.lambda) rho = 0 K = K2 k = length(wK2) xi = eK2$values[wK2] AKA = MatMult_C(MatMult_C(t(A),K),A) eV = Eigen_C(AKA) #eV = Eigen_C(AKA) U_1 = eV$vectors mu = eV$values[eV$values > 1e-10] mu = mu/max(mu, xi) xi = xi/max(mu,xi) # original U_1 in this case W1 = MatMult_C(A,U_1) w.double <- w^2 w1 = w.double[1:k,] w2 = ColSum_C((w.double)[-(1:k),]) if (length(mu) < k){mu = c(mu,rep(0, k - length(mu)))} if (length(xi) < k){xi = c(xi,rep(0, k - length(xi)))} LR0_fixRho <- LR0_fixRho_C(Lambdas, mu, w1, w2, n-px) # for (i in 1:length.lambda){ # lam = Lambdas[i] # Dn = (1/(1 + lam*mu))%*%w1+ w2 # Nn = (lam*mu/(1 + lam*mu))%*%w1 # temp = (n-px)*log(1 + Nn/Dn) - Sum_C(log(1 + lam*mu)) # LR0_fixRho[,i] = ifelse(temp < 0, 0, temp) # } LR0_allRho[,1] = MatrixRowMax_C(LR0_fixRho) LR0_allRho <- doubleloop(K1, K2, P0, A, U_1, w, Lambdas, n-px, all_rho, LR0_allRho) LR0 = MatrixRowMax_C(LR0_allRho) LR0 = ifelse(LR0 > 0, LR0, 0) p.dir = mean(LR < LR0) p.au1 = getp_au1(null = LR0, LR = LR)$p p.aud= getp_aud_estimate_pi_first(null = LR0, LR = LR)$p } out = list(p.dir = p.dir,p.aud = p.aud, LR = LR) return(out) }
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/omniRLRT_fast.R
#' @useDynLib CKLRT #' @importFrom Rcpp evalCpp NULL
/scratch/gouwar.j/cran-all/cranData/CKLRT/R/support.R
--- output: pdf_document: citation_package: natbib keep_tex: true fig_caption: true latex_engine: pdflatex template: /Users/zhangh24/GoogleDrive/project/Ni/Utility/inst/svm.tex title: "Composite Kernel Machine Regression based on Likelihood Ratio Test with Application for Combined Genetic and Gene-environment Interaction Effect " #thanks: "Replication files are available on the author's Github account..." author: - name: Ni Zhao affiliation: Department of Biostatistics, Johns Hopkins University, Baltimore, MD, USA - name: Haoyu Zhang affiliation: Department of Biostatistics, Johns Hopkins University, Baltimore, MD, USA - name: Jennifer J. Clark affiliation: Food and Drug Administration, Baltimore, MD, USA - name: Arnab Maity affiliation: Department of Statistics, North Carolina State University, Raleigh, NC,USA - name: Michael C. Wu affiliation: Public Health Sciences Division, Fred Hutchinson Cancer Research Center, Seattle, WA, USA abstract: "Most common human diseases are a result from the combined effect of genes, the environmental factors and their interactions such that including gene-environment (GE) interactions can improve power in gene mapping studies. The standard strategy is to test the SNPs, one-by-one, using a regression model that includes both the SNP effect and the GE interaction. However, the SNP-by-SNP approach has serious limitations, such as the inability to model epistatic SNP effects, biased estimation and reduced power. Thus, in this paper, we develop a kernel machine regression framework to model the overall genetic effect of a SNP-set, considering the possible GE interaction. Specifically, we use a composite kernel to specify the overall genetic effect via a nonparametric function and we model additional covariates parametrically within the regression framework. The composite kernel is constructed as a weighted average of two kernels, one corresponding to the genetic main effect and one corresponding to the GE interaction effect. We propose a likelihood ratio test (LRT) and a restricted likelihood ratio test (RLRT) for statistical significance. We derive a Monte Carlo approach for the finite sample distributions of LRT and RLRT statistics. Extensive simulations and real data analysis show that our proposed method has correct type I error and can have higher power than score-based approaches under many situations." keywords: "gene-environment interactions, kernel machine testing, likelihood ratio test, multiple variance compo- nents, spectral decomposition, unidentifiable conditions" date: "`r format(Sys.time(), '%B %d, %Y')`" geometry: margin=1in fontfamily: mathpazo fontsize: 11pt # spacing: double #bibliography: ~/Dropbox/master.bib #biblio-style: apsr --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` # Overview This vegnette provides an introduction to the 'CKLRT' package. To load the package, users need to install package from CRAN and CKLRT from github. The package can be loaded with the following command: ```{r, include=T} #install.packages("devtools") library(devtools) #install_github("andrewhaoyu/CKLRT") library(CKLRT) ``` # Example In this vegnette, we will decomstrate the methods with a simple example. 1. X present other covariates we want to adjust. 2. E represents the environment variable. 3. G is is the genotype matrix with two SNPs inside 4. y is the simulated outcomes. ```{r, include=T,echo=T,cache=T} library(mgcv); library(MASS); library(nlme); library(compiler);library(Rcpp);library(RcppEigen) library(CKLRT) set.seed(6) n = 200 # the number of observations X = rnorm(n) # the other covariates p = 2 # two snp in a gene will be simulated G = runif(n*p)< 0.5 G = G + runif(n*p) < 0.5 G = matrix(G, n,p) #genetic matrix E = (runif(n) < 0.5)^2 #enviroment effect y = rnorm(n) + G[,1] * 0.3 #observations #apply the likelihood ratio test omniLRT_fast(y, X = cbind(X, E),K1 = G %*% t(G),K2 = (G*E) %*% t(G * E)) #apply the restricted likelihood ratio test omniRLRT_fast(y, X = cbind(X, E),K1 = G %*% t(G),K2 = (G*E) %*% t(G * E)) ``` The results of the function contain three elements: 1. p.dir is the p-value of likelihood ratio test based on emprical distrition. 2. p.aud is the p-value by approximating the null distribution as a mixture of a point mass at zero with probability b and weighted chi square distribution with d degrees of freedom with probality of 1-b. 3. LR is the likelihood ratio test statistics. # References 1. N. Zhao, H. Zhang, J. Clark, A. Maity, M. Wu. Composite Kernel Machine Regression based on Likelihood Ratio Test with Application for Combined Genetic and Gene-environment Interaction Effect (Submitted)
/scratch/gouwar.j/cran-all/cranData/CKLRT/inst/CKLRT_package.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' Exponentiation function for integer arguments #' #' Solaris' compiler freaked hard on the pow function---couldn't figure #' out whether it should return an int or a float or something, when #' I used it to get very small powers of two. So I #' am going to write a silly, simple function (that only gets used a couple #' of times in an entire execution, and only with very #' small arguments, so the fact that it is not super efficient #' should not be a big problem). #' @param x the integer to raise 2 to. #' @name int_pow2 #' @keywords internal NULL #' Depth first search down the pedigree to N generations. #' #' When you call this #' from within search_up(), c should be set at 0, #' and the algorithm will run down for, n generations from there. #' Unlike in R, this is 0-based. So, n = 0 is self, n = 1 is kids, #' n = 2 is grandkids, and so forth. #' @param i the index of the node to call this on #' @param c the current generation level. 0 = the first (i.e. the starting individual). #' @param n the number of generations back to down. 1 means go no further than the offspring. #' 2 means go no further than the grandkids. #' @param P the pedigree structure #' @param C a reference to a character vector to which sampled individuals' IDs will get #' pushed on. At the end, we can unique them. #' @name search_down #' @keywords internal NULL #' Depth first search up the pedigree to N generations. #' #' Call this #' with c = 0 for the original individual, and it will go back, n generations. #' Unlike in R, this is 0-based. So, n = 1 is parents, n = 2 is grandparents #' and so on. #' @param i the index of the node to call this on #' @param c the current generation level. 0 = the first (i.e. the sampled individual) #' @param n the number of generations back to go. 1 means go no further than the parents. #' 2 means go no further than the grandparents. #' @param P the pedigree structure #' @param C a reference to a character vector to which sampled individuals' IDs will get #' pushed on. At the end, we can unique them. #' @name search_up #' @keywords internal NULL #' Function to make a vector of all the ancestors of an individual out to n generations. #' #' This is a replacement for the R implementation of #' `ancestor_vectors()` which was too slow. This will get called #' from with a C function in which the pedigree has been assembled. #' @param sv vector of sample indexes #' @param nv vector of names of all samples #' @param Ped pedigree struct #' @param n the number of generations. 0 = self, 1 = parent, 2 = grandparent, etc. #' @name ancestor_vectors_cpp #' @keywords internal NULL #' function to test and use DFS stuff #' @param L list of inputs #' @param n the number of generations back to go when computing the ancestor vectors #' and finding relatives. #' @keywords internal #' @export rcpp_ancestors_and_relatives <- function(L, n) { .Call('_CKMRpop_rcpp_ancestors_and_relatives', PACKAGE = 'CKMRpop', L, n) } #' Return a list of the indices of the primary shared ancestors #' #' This operates on an ancestry match matrix and uses a simple, divide-by_two #' relationship between an ancestor and its descendants in the ordering #' of an ancestry vector to determine which of the matching ancestors are secondary, #' and then return the ones that are primary. #' @param M an ancestry match matrix (it is a logical matrix) #' @return A list of pairs. Each pair is the 1-based index of ancestor of ind_1, then #' ind_2 of the primary shared ancestors. #' @keywords internal #' @export #' @examples #' # find primary ancestor pairs of example AMMs #' lapply(example_amms, primary_ancestor_pairs) primary_ancestor_pairs <- function(M) { .Call('_CKMRpop_primary_ancestor_pairs', PACKAGE = 'CKMRpop', M) } recursive_push_back <- function(Boing, i) { invisible(.Call('_CKMRpop_recursive_push_back', PACKAGE = 'CKMRpop', Boing, i)) } rcpp_test <- function(v1) { .Call('_CKMRpop_rcpp_test', PACKAGE = 'CKMRpop', v1) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/RcppExports.R
#' convert an ancestry-matching matrix to a ggplot-able tibble #' #' This merely converts a matrix to a tibble that can be plotted #' easily using ggplot. #' @param M an ancestry-match matrix #' @return `amm2tibble()` returns a tibble with three columns: #' * `x`: the 1-based index of the row of input matrix, #' * `y`: the 1-based index of the column of the input matrix, #' * `amm`: the logical value (TRUE/FALSE) of the (x,y)-th cell of the input matrix. #' @export #' @examples #' # convert one of the simple example AMMs to a tibble #' amm2tibble(example_amms$Father_Offspring_2gen) amm2tibble <- function(M) { tibble( x = rep(1:nrow(M), ncol(M)), y = rep(1:ncol(M), each = nrow(M)), amm = as.vector(M) ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/amm2tibble.R
#' Return ancestry-matrix-zone masks for different relationship types #' #' This returns a list of two logical matrices. The first catches the #' zone that is above the diagonal (when plotted with ind_1 on the x-axis #' and ind_2 on the y-axis). These correspond to ind_2 being the "older" #' member of the pair than ind_1. The second catches the zone on the #' lower diagonal. If the zone spans the diagonal, then each matrix #' returned in the list is the same. #' @param num_generations the number of generations to go back. 0 = self; #' 1 = to the parents; 2 = to the grandparents; 3 = to the great grandparents, #' etc. #' @param R the relationship whose zones you want to mask with TRUEs in the #' output matrices. See below for the possible choices. #' @details The relationships whose zones we are equipped to deal with go out to n=4 generation, #' and are named (and ordered) as follows, which is the order in which they #' appear in the package data vector `relationship_zone_names`: #' - `Se`: self. This is as far as it goes with num_generations = 0 #' - `PO`: parent-offspring #' - `Si`: sibling. This is as far as it goes with num_generations = 1. #' - `GP`: grandparental #' - `A` : avuncular (aunt-niece) #' - `FC`: first cousin. This is as far as it goes with num_generations = 2. #' - `GGP`: great-grandparental #' - `GA`: great-avuncular (great-aunt/great-niece, etc). #' - `FCr1`: first-cousin once removed #' - `SC`: second cousin. This is as far as it goes with num_generations = 3 #' - `GGGP`: great-great-grandparental #' - `GGA`: great-great-avuncular #' - `FCr2`: first cousin twice removed #' - `SCr1`: second cousin once removed #' - `TC`: third cousin #' At this point the additional zones for num_generations = 3 have not been #' implemented. #' @return This function returns a list of two matrices. Each one has FALSEs everywhere #' except in the zones corresponding to the relationship, where it has TRUEs. As mentioned #' above, the first matrix captures the zones where ind_2 is the "older" one and the #' second matrix captures the zones where ind_1 is the "older" one. For the symmetrical #' relationships (Se, Si, FC, etc.) the two matrices in the list are identical. #' @keywords internal #' @export anc_match_masks <- function( num_generations, R ) { # catch errors stopifnot(R %in% relationship_zone_names) Ridx = which(R == relationship_zone_names) # here is the highest possible index for each number of generations, counting from # zero (so we have to bump it up when we test it) maxis <- c(1, 3, 6, 10, 15) if(Ridx > maxis[num_generations + 1]) { stop( paste( "Requested relationship, ", R, ", is too distant for num_generations = ", num_generations, collapse = "", sep = "" ) ) } L <- 2 ^ (num_generations + 1) - 1 # number of rows and columns in matrix M1 <- matrix(FALSE, nrow = L, ncol = L ) M2 <- matrix(FALSE, nrow = L, ncol = L ) switch( R, Se = { M1[1, 1] <- TRUE list(M1, M1) }, PO = { M1[1, 2:3] <- TRUE M2[2:3, 1] <- TRUE list(M1, M2) }, Si = { M1[2:3, 2:3] <- TRUE list(M1, M1) }, GP = { M1[1, 4:7] <- TRUE M2[4:7, 1] <- TRUE list(M1, M2) }, A = { M1[2:3, 4:7] <- TRUE M2[4:7, 2:3] <- TRUE list(M1, M2) }, FC = { M1[4:7, 4:7] <- TRUE list(M1, M1) }, GGP = { M1[1, 8:15] <- TRUE M2[8:15, 1] <- TRUE list(M1, M2) }, GA = { M1[2:3, 8:15] <- TRUE M2[8:15, 2:3] <- TRUE list(M1, M2) }, FCr1 = { M1[4:7, 8:15] <- TRUE M2[8:15, 4:7] <- TRUE list(M1, M2) }, SC = { M1[8:15, 8:15] <- TRUE list(M1, M1) }, GGGP = { M1[1, 16:31] <- TRUE M2[16:31, 1] <- TRUE list(M1, M2) }, GGA = { M1[2:3, 16:31] <- TRUE M2[16:31, 2:3] <- TRUE list(M1, M2) }, FCr2 = { M1[4:7, 16:31] <- TRUE M2[16:31, 4:7] <- TRUE list(M1, M2) }, SCr1 = { M1[8:15, 16:31] <- TRUE M2[16:31, 8:15] <- TRUE list(M1, M2) }, TC = { M1[16:31, 16:31] <- TRUE list(M1, M1) } ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/anc_match_masks.R
#' Return a string of ancestor abbreviations in the order of the ancestor vectors #' #' Use this to put axis labels on plots, etc. #' @param L desired length of the output #' @keywords internal #' @export #' @examples #' ancestor_abbrvs(15) ancestor_abbrvs <- function(L) { if(L <= 3) { return(c("s", "p", "m")[1:L]) } # determine how many generations to go (and go a bit over, possibly) g <- ceiling(log(L + 1, base = 2)) alist <- list( "s", c("p", "m") ) for(i in 3:g) { alist[[i]] <- paste0(rep(alist[[i-1]], each = 2), c("p", "m") ) } unlist(alist)[1:L] }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/ancestor_abbrvs.R
#' Categorize the dominant relationship from an ancestry match matrix #' #' This function takes an ancestry match matrix (AMM) and it returns what the #' "dominant" relationship is. It doesn't try to capture all the nuances #' that might be present in the AMM. For example, it does not note inbreeding #' and other such things. However this is useful for categorizing what type #' of relationship is the "closest" relationship type amongst all the ways a #' pair is related. #' Currently for num_generations == 2, the function goes through in this order, #' to identify relationships: #' - `Se`: self. This is as far as it goes with num_generations = 0 #' - `PO`: parent-offspring #' - `Si`: sibling. This is as far as it goes with num_generations = 1 #' - `GP`: grandparental #' - `A` : avuncular (aunt-niece) #' - `FC`: first cousin. #' #' And so forth. This has been implemented out to 3 generations #' using the relationship zones in package data object #' `relationship_zone_names`. #' @param AMM The ancestry match matrix to categorize #' @return This returns a list with two components: #' - `type`: a string saying what type of relationship (i.e., "Si", or "A"). #' - `hits`: a two vector of the number of TRUEs in each "relationship zone" on the #' upper or the lower diagonal of the AMM. #' @export #' @keywords internal #' @examples #' cat_dom_relat(half_first_cousin_amm) cat_dom_relat <- function(AMM) { # Determine the number of generations from the dimensions of the matrix and # throw an error if it's not an integer L <- nrow(AMM) Ng <- log(L + 1, base = 2) - 1 stopifnot(Ng %% 1 == 0) # cycle over the relationships in order until we get one that is non-zero Relats <- relationship_zone_names for(r in Relats) { masks <- anc_match_masks(num_generations = Ng, R = r) sums <- unlist(lapply(masks, function(x) sum(x & AMM))) if(any(sums > 0)) { return(list(type = r, hits = sums))} } # if we got to here, then there was no relationship, and we just return "U", c(0, 0). # Note that we typically should never get here if we are only dealing with pairs that # are related to some degree at n generations... return(list(type = "U", hits = c(0, 0))) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/cat_dom_relat.R
#' compile pairwise relationships from the samples #' #' Run this on some of the output from `slurp_spip()`. #' @param S a tibble. In the context of this package this tibble is #' typically going to often be the #' `samples` component of the output slurped up from spip with `slurp_spip()`. #' More generally, it is a tibble that must have the columns: #' - `ID`: the id of the sample #' - `ancestors`: a list column of the ancestor vectors of each individual #' - `relatives`: a list column of the vectors of individual samples (including self) #' that each individual is related to. #' @return a tibble with columns `id_1` and `id_2` for each pair. Any additional #' columns outside of `relatives` will be joined with `_1` and #' `_2` suffixes. In a typical run slurped up from spip this leads to the following #' columns: #' - `id_1`: the id of the first sample of the pair, #' - `id_2`: the id of the 2nd sample of the pair, #' - `conn_comp`: the index of the connected component to which the pair belongs, #' - `dom_relat`: the dominant relationship that the pair shares, #' - `max_hit`: the number of shared ancestors at the level of the dominant relationship #' - `dr_hits`: a list column of two-vectors---the number of shared ancestors at the level #' of the dominant relationship in the upper and lower quadrants, respectively of the #' ancestry match matrix. If the relationship is symmetrical, the two values are the same. #' - `upper_member`: for non-symmetrical relationships, a 1 or a 2 indicating which member of the #' pair is the one that is typically older (i.e. the uncle in an uncle-nephew relationship), or #' NA if the relationship is symmetrical. #' - `times_encountered`: the number of times this pair was encountered when processing the #' output of the depth first search algorithm that found these pairs. Not typically used for #' downstream analyses. #' - `primary_shared_ancestors`: a list columns of two-vectors. The first element of each is the #' the position in the ancestry vector of id_1's primary shared ancestor. The second element is #' the same for id_2. #' - `psa_tibs`: like `primary_shared_ancestor` but a list column of tibbles. #' - `pop_pre_1`, `pop_post_1`, `pop_dur_1`: the population from which the id_1 individual #' was sampled during the prekill, postkill, or during-reproduction sampling episodes, #' respectively. NA for episodes in which the individual was not sampled #' - `pop_pre_2`, `pop_post_2`, `pop_dur_2`: same as above for the id_2 individual. #' - `sex_1`: sex of the id_1 individual, #' - `sex_2`: sex of the id_2 individual, #' - `born_year_1`: birth year of the id_1 individual, #' - `born_year_2`: birth year of the id_2 individual, #' - `samp_years_list_pre_1`: list column of years during which the id_1 individual was sampled #' during the prekill episode. #' - `samp_years_list_dur_1`: list column of years during which the id_1 individual was sampled #' during reproduction. #' - `samp_years_list_post_1`: list column of years during which the id_1 individual was sampled #' during the postkill episode. #' - `samp_years_list_1`: by default this column is identical to `samp_years_list_post_1` and is the #' column used in downstream plotting by some functions. If you want to use a different column, #' for example `samp_years_list_pre_1` for the downstream plotting, then set the value of #' `samp_years_list_1` to the same values, #' - `samp_years_list_pre_2`, `samp_years_list_dur_2`, `samp_years_list_post_2`, `samp_years_list_2`: same #' as above but for individual with id_2, #' - `born_pop_1`: index of population in which id_1 was born, #' - `ancestors_1`: ancestry vector of id_1, #' - `born_pop_2`: index of population in which id_2 was born, #' - `ancestors_2`: ancestry vector of id_2, #' - `anc_match_matrix`: the ancestry match matrix (a logical matrix) for the pair. #' @export #' @examples #' C <- compile_related_pairs(three_pops_with_mig_slurped_results$samples) compile_related_pairs <- function(S) { # toss the sampled indivs with no relatives S2 <- S %>% filter(map_int(relatives, length) > 1) # keep just the columns that we will join in later S2_joiner <- S2 %>% select(-relatives) # find all pairs, in a lexicographically sorted order pairs_mat <- lapply(S2$relatives, function(x) { t(combn(sort(x), 2)) }) %>% do.call(rbind, .) colnames(pairs_mat) <- c("id_1", "id_2") pairs_tib_1 <- as_tibble(pairs_mat) # count how many times each pair occurs. I think that all those that # occur only once will not end up being relatives. They just happen to both # be related someone else, but they are not closely enough related to count. # So, I will just record that now and verify. Ultimately, we can probably toss them S2_1 <- S2_joiner names(S2_1) <- paste0(names(S2_1), "_1") S2_2 <- S2_joiner names(S2_2) <- paste0(names(S2_2), "_2") # join those together and compute the ancestor-matching matrix (the anc_match_matrix). # and, at the end, determine the "primary shared ancestors" (see the paper for an explanation). pairs_tib_2 <- pairs_tib_1 %>% count(id_1, id_2) %>% filter(n > 1) %>% # toss out the ones only seen once because they are not true relationships left_join(S2_1, by = c("id_1" = "ID_1")) %>% left_join(S2_2, by = c("id_2" = "ID_2")) %>% mutate( anc_match_matrix = map2( .x = ancestors_1, .y = ancestors_2, .f = function(x, y) outer(x, y, "==") ) ) %>% mutate(no_relat = map_lgl(.x = anc_match_matrix, .f = function(x) all(x == FALSE))) %>% filter(no_relat == FALSE) %>% select(-no_relat) %>% mutate( primary_shared_ancestors = map(.x = anc_match_matrix, .f = primary_ancestor_pairs) ) %>% mutate(psa_tibs = map( # also save those primary ancestors in tibble form .x = primary_shared_ancestors, .f = function(m) { tibble( prim_anc_1 = map_int(m, 1), prim_anc_2 = map_int(m, 2) ) } )) # now, we want categorize the "dominant relationship" of each pair. This is done by # cycling over (within a function) relationships from Self to PO to Sib to Aunt, etc # and returning the first one that qualifies. We also return how many hits are within # each of those relationships zones. Then we pull the list elements type and hits into # their own columns pairs_tib_3 <- pairs_tib_2 %>% mutate( dr = map( .x = anc_match_matrix, .f = function(x) {cat_dom_relat(x)} ), dom_relat = map_chr(dr, function(x) x$type), dr_hits = map(dr, function(x) x$hits) ) %>% select(-dr) %>% mutate( upper_member = map2_int( .x = dom_relat, .y = dr_hits, .f = function(x, y) { if(x %in% c("Se", "Si", "FC")) return(NA_integer_) else if(y[1] == y[2]) return(0L) else if(y[1] > y[2]) return(1L) else if(y[1] < y[2]) return(2L) else return(-999L) # flags that things got through here and should not have } ), max_hit = map_int( .x = dr_hits, .f = function(x) max(x) ) ) # we will return that for now, after adding conn_comps to it pairs_tib_3 %>% rename(times_encountered = n) %>% select( id_1, id_2, dom_relat, max_hit, dr_hits, upper_member, times_encountered, primary_shared_ancestors, psa_tibs, starts_with("pop_"), starts_with("sex_"), starts_with("born_year_"), starts_with("samp_years_list"), everything() ) %>% relpair_conn_comps() }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/compile_related_pairs.R
#' here is a function to plot a basic ancestry match matrix #' #' It is primarily for internal use #' @param ATP a tibble that has ind_1, ind_2, and an ID column #' @keywords internal basic_amm_plot <- function(ATP, add_imps = FALSE, perimeter_width = 0.5) { g <- ggplot() + geom_tile( data = ATP, mapping = aes(x = ind_1, y = ind_2, fill = amm), colour = "black" ) # put this down to establish a discrete scale g <- gg_add_generation_bands( g = g, L = max(ATP$x), add_impossibles = add_imps, alpha = 0.3 ) + scale_fill_manual(values = c(`FALSE` = NA, Impossible = "white", `TRUE` = "black")) + geom_tile( data = ATP, mapping = aes(x = ind_1, y = ind_2, fill = amm), colour = "black" ) + # put it down again to have it on top theme_bw() + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.x = element_text(angle = 90, hjust = 1.0, vjust = 0.5) ) + guides(fill = guide_legend(title = "Ancestry Match\nMatrix Element")) # finally, add the zone perimeters g <- gg_add_zone_perimeters( g = g, L = max(ATP$x), perisize = perimeter_width ) g } #' Count up the number of different kinds of related pairs and make a plot #' #' This counts up all the different types of pairwise relationships and #' makes a plot (or multiple pages of them). For an example, see #' the Vignette: `vignette("species_1_simulation", package = "CKMRpop")`. #' @param Pairs a tibble like that returned by `compile_related_pairs()`. #' @param nrow the number of rows to plot per page #' @param ncol the number of columns to plot per page #' @param white_ball_size the size of the white dot plotted on top of the #' primary shared ancestors' cells. #' @export #' @return Returns a list with the following components: #' - `highly_summarised`: a tibble reporting counts of different types of relationships with #' the columns: #' * `dom_relat`: The name of the dominant relationship (e.g. Si, PO, A, etc). #' * `max_hit`: The number of primary shared ancestors. #' * `n`: The number of occurrences of this type of relationship. #' - `dr_counts`: A tibble with the counts of all the different, unique ancestry match matrices #' observed, with the following columns: #' * `dom_relat`: The dominant relationship type #' * `dr_hits`: list column with the number of primary shared ancestors in the upper and lower quadrants #' of the ancestry match matrix (values are repeated for symmetrical relationships). #' * `max_hit`: the number of primary shared ancestors. #' * `anc_match_matrix`: a list column of ancestry match matrices. #' * `n`: The number of pairs with this type of ancestry match matrix #' * `tot_dom`: The total number of pairs within the given dominant relationship category. #' * `ID`: A unique, properly sorting name for this category for placing a title on #' facets of plots of these ancestry match matrices. #' - `dr_plots`: a list named by the dominant relationship. Each component is a ggplot #' object which is a plot of the ancestry match matrices, faceted by their `ID`'s as #' given in `dr_counts`. #' - `anc_mat_counts`: A tibble summarizing the counts of different ancestry match matrices #' without regard to dominant relationship type, etc. Rows are arranged in descending order #' of number of pairs observed with each ancestry match matrix. It has the columns: #' * `anc_match_matrix`: a list column of ancestry match matrices. #' * `n`: the number of such matrices observed. #' - `anc_mat_plots`: a list of ggplot pages. These are plots faceted by ancestry match #' matrix of all ancestry match matrices observed, ordered by number of occurrences (as #' given in `anc_mat_counts`). count_and_plot_ancestry_matrices <- function( Pairs, nrow = 6, ncol = 5, white_ball_size = 1 ) { #### First, we treat each distinct relationship type #### # count the number of different unique relationships anc_mat_counts <- Pairs %>% count(anc_match_matrix) %>% arrange(desc(n)) # record how many relationship types there are n_relat <- nrow(anc_mat_counts) amc_to_plot <- anc_mat_counts %>% mutate(ID = str_c(sprintf("%03d", 1:n()), " (", n, ")" )) %>% mutate(amm_as_tib = map(anc_match_matrix, amm2tibble)) %>% unnest(amm_as_tib) %>% mutate( ind_1 = factor(ancestor_abbrvs(max(x))[x], levels = ancestor_abbrvs(max(x))), ind_2 = factor(ancestor_abbrvs(max(y))[y], levels = ancestor_abbrvs(max(y))) ) %>% mutate(amm = as.character(amm)) # now, also get a tibble to store the primary shared ancestors PSA_TIBS <- Pairs %>% count(anc_match_matrix, psa_tibs) %>% select(-n) tmp2 <- amc_to_plot %>% count(anc_match_matrix, ID) %>% select(-n) primaries <- left_join(PSA_TIBS, tmp2, by = "anc_match_matrix") %>% select(ID, anc_match_matrix, everything()) %>% unnest(cols = c(psa_tibs)) # now we can lapply over the different pages num_pages <- ceiling(n_relat / (nrow * ncol)) plots <- lapply(1:num_pages, function(i) { g <- basic_amm_plot(amc_to_plot) + geom_point( data = primaries, mapping = aes( x = prim_anc_1, y = prim_anc_2 ), colour = "white", size = white_ball_size ) + ggforce::facet_wrap_paginate(~ ID, ncol = ncol, nrow = nrow, page = i) g }) #### Now, we will also compile according to the dominant relationships #### # first tally up according to dominant relationship, dr_hits, and ancestry matrix together # and count up the total of each dom category while at it. And also make an ID for each # of those ancestry match matrices that includes the dominant relationship, the dr_hits, and # how many were seen dr_counts <- Pairs %>% count(dom_relat, dr_hits, max_hit, anc_match_matrix) %>% group_by(dom_relat) %>% mutate(tot_dom = sum(n)) %>% ungroup() %>% arrange(desc(tot_dom), desc(n)) %>% group_by(dom_relat) %>% mutate( ID = sprintf( "%03d-%s[%d,%d] - %d", 1:n(), dom_relat, map_int(dr_hits, function(x) x[1]), map_int(dr_hits, function(x) x[2]), n ) ) %>% ungroup() # now, figure out which dominant relationship has the most: max_panels <- dr_counts %>% count(dom_relat) %>% pull(n) %>% max() # now, choose a layout for that in which there might be one or a couple more rows than colums. drows <- ceiling(sqrt(max_panels)) dcols <- ceiling(max_panels / drows) # now, set those IDs and dom_relats as factors so that # things plot out in the correct order, and then expand the # AMMs into rows in a tibble, then split all that # it into a list of tibbles on the dominant relationships dr_list <- dr_counts %>% group_by(anc_match_matrix) %>% mutate( ID = factor(ID, levels = unique(ID)), dom_relat = factor(dom_relat, levels = unique(dom_relat)) ) %>% mutate(amm_as_tib = map(anc_match_matrix, amm2tibble)) %>% unnest(amm_as_tib) %>% mutate( ind_1 = factor(ancestor_abbrvs(max(x))[x], levels = ancestor_abbrvs(max(x))), ind_2 = factor(ancestor_abbrvs(max(y))[y], levels = ancestor_abbrvs(max(y))) ) %>% mutate(amm = as.character(amm)) %>% split(., .$dom_relat) # now we need to make another parallel list that has the primary ancestor # information in it. psa_list <- lapply(dr_list, function(x) { tmp <- x %>% ungroup() %>% count(anc_match_matrix, ID) %>% select(-n) %>% left_join(PSA_TIBS, by = "anc_match_matrix") %>% unnest(cols = c(psa_tibs)) }) # now we lapply over those and make a faceted ggplot for each dr_plots <- lapply(names(dr_list), function(n) { g <- basic_amm_plot(dr_list[[n]]) + geom_point( data = psa_list[[n]], mapping = aes( x = prim_anc_1, y = prim_anc_2 ), colour = "white", size = white_ball_size ) + ggtitle(paste0("Dominant relationship: ", n)) + ggforce::facet_wrap_paginate(~ ID, ncol = dcols, nrow = drows, page = 1) }) names(dr_plots) <- names(dr_list) #### Finally, highly summarize the dr_counts into the dominant category and the dr_hit #### highly_summarised <- dr_counts %>% group_by(dom_relat, max_hit) %>% summarise(n = sum(n)) %>% arrange(desc(n)) %>% ungroup() #### now return a list #### list( highly_summarised = highly_summarised, dr_counts = dr_counts, dr_plots = dr_plots, anc_mat_counts = anc_mat_counts, anc_mat_plots = plots ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/count_and_plot_ancestry_matrices.R
#' Count and plot the number of mates each individuals has produced offspring with #' #' This just tallies up the information from the pedigree. It will plot things #' faceted by pop (over rows) and sexes (over columns). #' @param P the pedigree from the simulation, like that returned in the `pedigree` component #' of the list returned by `slurp_spip()`. #' @export #' @return A list with two components with names: #' - `mate_counts`: A tibble with information about the number of mates with which #' a parent produced offspring each year. It has the columns: #' * `sex`: the sex of this parent #' * `year`: the year during which the mating occurred #' * `pop`: the population this parent was in #' * `parent`: the ID of the parent #' * `num_offs`: the number of offspring this parent had in total #' * `num_mates`: the number of mates this parent had #' - `plot_mate_counts`: a ggplot object, faceted on a grid by population in columns #' and sex in rows. The x-axis is the number of offspring (in a season), the y-axis is the #' number of mates in a season, and the fill color of the grid gives the number of parents #' with that number of offspring and mates. #' @examples #' result <- count_and_plot_mate_distribution(three_pops_no_mig_slurped_results$pedigree) #' #' # have a look at the results: #' result$mate_counts #' #' result$plot_mate_counts #' count_and_plot_mate_distribution <- function(P) { P2 <- P %>% filter(ma != "0" & pa != "0") fem_counts <- P2 %>% group_by(year, pop, ma) %>% summarise( num_offs = n(), num_mates = n_distinct(pa) ) %>% ungroup() %>% rename(parent = ma) male_counts <- P2 %>% group_by(year, pop, pa) %>% summarise( num_offs = n(), num_mates = n_distinct(ma) ) %>% ungroup() %>% rename(parent = pa) mate_counts <- bind_rows( list( female = fem_counts, male = male_counts ), .id = "sex" ) # Now, plot this. Because the values are discrete, we # will do it as tiles. for_tiles <- mate_counts %>% count(pop, sex, num_offs, num_mates) gft <- ggplot( for_tiles, aes( x = num_offs, y = num_mates, fill = n ) ) + geom_tile() + facet_grid(sex ~ pop) + scale_fill_viridis_c(trans = "log10") + xlab("Number of offspring (in a season)") + ylab("Number of mates (in a season)") # return list( mate_counts = mate_counts, plot_mate_counts = gft ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/count_and_plot_mate_distribution.R
#' a list of life-history / life-table data for a hypothetical species #' #' species_1 for examples. #' @source Just values that might be typical of a fish. #' @docType data #' @name species_1_life_history #' @usage species_1_life_history NULL #' a list of life-history / life-table data for another hypothetical species #' #' species_2 for examples. Note that I just set the male and female #' rates and parameters similar. #' @source This is something used for simulation testing #' @docType data #' @name species_2_life_history #' @usage species_2_life_history NULL #' a list of examples of ancestry-match matrices #' #' This is a list of matrices with names that describe what they #' represent. The names are Relationship_Number-of-Generations, like: #' "Unrelated_2gen", "Self_2gen", "Unrelated_3gen", "Unrelated_4gen", #' "Unrelated_1gen", "Father_Offspring_2gen", "FullSibling_2gen", "PatHalfSibling_2gen", #' "FullCousin_2gen", "HalfAuntNiece_2gen". #' @source I just made these for some illustrative figures in the manuscript about this #' R package. #' @docType data #' @name example_amms #' @usage example_amms NULL #' relationship zone names #' #' A simple character vector of 15 relationship zones in the order they #' are encountered when traversing an ancestry match matrix out to four #' generations #' @source I simply defined these #' @docType data #' @name relationship_zone_names NULL #' The result of running spip in the species_1_simulation vignette. #' #' This is stored as package data so that the vignette can be written #' even if spip is not installed on the system. #' #' @source Simulation results #' @docType data #' @name species_1_slurped_results #' @usage species_1_slurped_results NULL #' The result of running spip in the species_1_simulation vignette and slurping out with num_generations = 1. #' #' This is stored as package data so that the vignette can be written #' even if spip is not installed on the system. #' #' @source Simulation results #' @docType data #' @name species_1_slurped_results_1gen #' @usage species_1_slurped_results_1gen NULL #' The result of running spip in the species_1_simulation vignette with 100 loci. #' #' This is stored as package data so that the vignette can be written #' even if spip is not installed on the system. This particular version #' stores the results of running `run_spip()` calling for 100 loci segregating #' in the population, then slurping the results up with `slurp_spip()`. #' @source Simulation results #' @docType data #' @name species_1_slurped_results_100_loci #' @usage species_1_slurped_results_100_loci NULL #' The result of running spip and slurping the output in the three population case with no migration #' #' This is stored as package data so that the vignette can be written #' even if spip is not installed on the system. #' #' @source Simulation results #' @docType data #' @name three_pops_no_mig_slurped_results #' @usage three_pops_no_mig_slurped_results NULL #' The result of running spip and slurping the output in the three population case with migration #' #' This is stored as package data so that the vignette can be written #' even if spip is not installed on the system. #' #' @source Simulation results #' @docType data #' @name three_pops_with_mig_slurped_results #' @usage three_pops_with_mig_slurped_results NULL #' A half-first cousin ancestry match matrix #' #' Just a simple AMM to use in some examples #' #' @source Simply wrote this down. #' @docType data #' @name half_first_cousin_amm #' @usage half_first_cousin_amm NULL
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/data.R
#' downsample the number of individuals sampled #' #' This discards individuals from the sample, randomly, until #' the desired number of samples is achieved, then it #' returns only those pairs in which both members are part of #' the retained samples. #' @param S the tibble of samples with columns at least of `ID` and `samp_years_list`. Typically #' this will be what is returned in the `samples` component from `slurp_spip()`. #' @param P the tibble of pairs. Typically this will be what has been returned from #' `compile_related_pairs()`. #' @param n The desired number of individuals (or instances, really, see below) to #' retain in the sample. #' @return This returns a list with two components as follows: #' - `ds_samples`: A tibble like `S` except having randomly removed individuals #' so as to only have n left. #' - `ds_pairs`: A tibble like `P` except having removed any pairs that #' include individuals that were not retained in the sample. #' @export #' @examples #' # prepare some input #' S <- three_pops_with_mig_slurped_results$samples #' P <- compile_related_pairs(three_pops_with_mig_slurped_results$samples) #' result <- downsample_pairs(S, P, n = 500) #' #' # print the result #' result downsample_pairs <- function(S, P, n) { # here is how we do it when assuming that we want to downsample # sample episodes, rather than individuals (I think this should be # the default). # first, we need to unnest the samp_years of each individual S2 <- S %>% select(ID, samp_years_list) %>% unnest(samp_years_list) if(nrow(S2) < n) { stop(paste0("Sorry, you only have ", nrow(S2), " sampling instances. Not enough to downsample them to n = ", n)) } # now we need to downsample them S3 <- S2 %>% sample_n(n) # make a sample list to return Sret <- S3 %>% group_by(ID) %>% summarise(samp_years_list = map(samp_years_list, function(x) x)) %>% ungroup() %>% left_join(S %>% select(-samp_years_list), by = "ID") # now, only retain the pairs that have sampling instances that they should P2 <- P %>% unnest(samp_years_list_1) %>% unnest(samp_years_list_2) %>% filter( id_1 %in% S3$ID, samp_years_list_1 %in% S3$samp_years_list, id_2 %in% S3$ID, samp_years_list_2 %in% S3$samp_years_list ) # finally, nest up the samp_years_lists on those again P3 <- P2 %>% nest(tmp_1 = c(samp_years_list_1)) %>% nest(tmp_2 = c(samp_years_list_2)) %>% mutate( samp_years_list_1 = map(tmp_1, function(x) x$samp_years_list_1), samp_years_list_2 = map(tmp_2, function(x) x$samp_years_list_2) ) # now, get the columns in the same order P4 <- P3[, names(P)] # finally, reset the connected components P5 <- P4 %>% select(-conn_comp) %>% relpair_conn_comps() # and return that list( ds_samples = Sret, ds_pairs = P5 ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/downsample_pairs.R
#' Find ancestors and relative of each sampled member of a pedigree #' #' This is a fairly general function that can be applied to pedigree output #' from any simulation program. It calls a function written in C++ to #' do all the recursive pedigree searching. #' @param P a tibble that gives the pedigree. It must have the columns `kid`, `pa`, `ma`. #' These columns must be character vectors of the unique IDs for each individual in #' the pedigree. #' Every individual in the pedigree must appear exactly once in the `kid` column. When founders #' appear in the pedigree, their `pa` and `ma` entries must be "0" (i.e. character zero). #' @param S a vector of the IDs of the sampled individuals. Obviously, all members of S must appear #' in P. #' @param n number of generations back from the sampled individuals to return in each #' individual's ancestor vector. 0 = self, 1 = back to and including the parents, #' 2 = back to and including the grandparents, and so on. #' @return A tibble with three columns: #' - `sample_id`: the ID names of the sampled individuals #' - `ancestors`: a list column. Each element is a vector of the ids of the ancestors of the #' sampled individual in the 2^(n+1) - 1 positions. The first is the sampled individual, the second #' is pa, third is ma, fourth is pa's pa, fifth is pa's ma, sixth is ma's pa, and so forth. #' - `relatives`: a list column. Each element is a vector of the ids of the individuals that are _sampled_ relatives #' within the n generations. The first element is the sampled individual itself, and the remaining #' ones are all the relatives of that individual whom were also sampled. #' @keywords internal #' @export #' @examples #' # get some input variables #' P <- three_pops_with_mig_slurped_results$pedigree #' S <- three_pops_with_mig_slurped_results$samples$ID #' n <- 2 #' result <- find_ancestors_and_relatives_of_samples(P, S, n) #' result find_ancestors_and_relatives_of_samples <- function(P, S, n) { DFS_input <- prepare_for_dfs(P, S) ra <- rcpp_ancestors_and_relatives(DFS_input, n) # get the sample names as the first element in each of the AV vectors: sample_ids = lapply(ra$AV, function(x) x[1]) %>% unlist() tibble( sample_id = sample_ids, ancestors = ra$AV, relatives = ra$REL ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/find_ancestors_and_relatives_of_samples.R
#' Add bands of transparent colors to denote generations on plots of ancestor-match matrices #' #' Pass it the original ggplot, and this will return it, with the bands added #' @param g the original ggplot #' @param L the number of rows (or columns) in the ancestor-match matrices #' @param alpha the transparency to use for these color-bands #' @param colors the colors in order of self, parent, grandparent, etc. By default it #' is just rainbow order starting from red. #' @param add_impossibles pass TRUE if you want to blot out the cells that are not possible #' because they conflict with the sex of the individuals. You set the fill of the #' impossibles with a `scale_fill_manual()` in the main ggplot call. i.e., #' ``` #' scale_fill_manual(values = c(`FALSE` = NA, Impossible = "white", `TRUE` = "black")) #' ``` #' @keywords internal gg_add_generation_bands <- function( g, L, alpha = 0.2, colors = c("red", "orange", "yellow", "green", "blue"), add_impossibles = FALSE ) { # determine number of generations Gen <- ceiling(log(L + 1, base = 2)) # lay down a series of rectangles for each generation level for(i in 1:Gen) { g <- g + annotate( "rect", xmin = 2^(i-1) - 0.5, xmax = 2^i - 1 + 0.5, #ymin = 2^(i-1) - 0.5, #ymax = L + 0.5, ymin = 0.5, ymax = 2^Gen - 1 + 0.5, fill = colors[i], colour = NA, alpha = alpha ) + annotate( "rect", #xmin = 2^(i-1) - 0.5, #xmax = L + 0.5, xmin = 0.5, xmax = 2^Gen - 1 + 0.5, ymin = 2^(i-1) - 0.5, ymax = 2^i - 1 + 0.5, fill = colors[i], colour = NA, alpha = alpha ) } if(add_impossibles == TRUE) { # make the tibble for it imp_tib <- tibble( x = rep(1:L, L), y = rep(1:L, each = L), val = NA_character_ ) %>% mutate( val = case_when( x == 1 | y == 1 ~ "FALSE", (x %% 2) == (y %% 2) ~ "Impossible", TRUE ~ "FALSE" ) ) g <- g + geom_tile( data = imp_tib, mapping = aes(x = x, y = y, fill = val), colour = "black" ) } g }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/gg_add_generation_bands.R
#' Add perimeters around the relationship zones #' #' Pass it the original ggplot, and this will return it, with the perimeters added. #' @param g the original ggplot #' @param L the number of rows (or columns) in the ancestor-match matrices #' @param perisize the size of the line to color in the perimeters #' @keywords internal gg_add_zone_perimeters <- function( g, L, perisize = 0.5 ) { # determine number of generations GenP1 <- ceiling(log(L + 1, base = 2)) # now get the relationships to include num_relat <- c(1, 3, 6, 10, 15)[GenP1] # get a tibble or perimeter endpoints rzp <- relationship_zone_perimeters() %>% filter(zone %in% relationship_zone_names[1:num_relat]) g2 <- g + annotate( "rect", xmin = rzp$xmin, xmax = rzp$xmax, ymin = rzp$ymin, ymax = rzp$ymax, fill = NA, colour = "black", size = perisize ) g2 }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/gg_add_zone_perimeters.R
#' Just a simple plot function #' #' Easy to do, but quicker to have it wrapped up in a plot. #' @param census a tibble of census counts with columns `year` and #' `age`, and then the counts of the different sexes in columns #' named `male`, and `female`. #' @return `ggplot_census_by_year_age_sex()` returns a ggplot object which is a #' stacked barplot with year on the x-axis, #' counts on the y-axis with fill mapped to age. It is facet-gridded #' with sex in the columns and populations in the rows. #' @export #' @examples #' # A single population example #' g <- ggplot_census_by_year_age_sex(species_1_slurped_results$census_postkill) #' #' # a three-population example #' g3 <- ggplot_census_by_year_age_sex(three_pops_with_mig_slurped_results$census_postkill) ggplot_census_by_year_age_sex <- function(census) { g <- census %>% pivot_longer( cols = c(male, female), names_to = "sex", values_to = "n" ) %>% ggplot( aes( x = year, y = n, fill = as.factor(age) ) ) + geom_col(colour = "black", size = 0.1) + facet_grid(pop ~ sex) + guides( fill = guide_legend(title = "Age") ) g }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/ggplot_census_by_year_age_sex.R
#### Import the pipe operator from magrittr #### #' Pipe operator #' #' @name %>% #' @rdname pipe #' @keywords internal #' @export #' @importFrom magrittr %>% #' @usage lhs \%>\% rhs NULL #' @importFrom dplyr anti_join arrange bind_cols bind_rows case_when count desc distinct ends_with everything filter group_by inner_join lead left_join mutate n n_distinct pull recode rename rename_all sample_n select slice starts_with summarise ungroup #' @importFrom ggplot2 aes annotate element_blank element_text facet_grid facet_wrap geom_boxplot geom_col geom_hex geom_histogram geom_hline geom_jitter geom_point geom_rect geom_segment geom_tile geom_vline ggplot ggtitle guide_legend guides scale_colour_manual scale_fill_manual scale_fill_viridis_c theme theme_bw xlab ylab #' @importFrom purrr map map2 map2_int map_chr map_int map_lgl #' @importFrom readr cols read_delim read_lines read_table2 #' @importFrom stats runif #' @importFrom stringr str_c str_detect str_replace str_split str_split_fixed #' @importFrom tibble as_tibble enframe tibble #' @importFrom tidyr extract gather nest pivot_longer pivot_wider replace_na separate unnest #' @importFrom utils combn unzip #' @importFrom Rcpp evalCpp #' @useDynLib CKMRpop NULL # quiets concerns of R CMD check re: the . and other column names # that appear in dplyr chains if (getRversion() >= "2.15.1") { utils::globalVariables( c( ".", "ID", "ID_1", "ID_2", "X2", "X3", "aes", "age", "age_1", "age_2", "amm", "amm_as_tib", "anc_match_matrix", "ancestors_1", "ancestors_2", "arrow", "assp", "born_year", "born_year_1", "born_year_2", "cc_1", "cc_2", "child_num", "cluster", "cohort", "conn_comp", "dom_relat", "dom_relat-max_hit", "dr", "dr_hits", "event", "extract", "female", "first", "from", "fract", "id", "id_1", "id_2", "ind_1", "ind_2", "indiv", "kid", "kid_id", "kid_idx", "kid_year", "kin_prob", "ma", "ma_1", "ma_2", "ma_age", "ma_id", "ma_surv_y", "ma_year", "male", "max_hit", "mean_fract", "mean_surv", "name", "no_relat", "nodes", "nojit_age1", "nojit_age2", "num_mates", "num_offs", "pa", "pa_1", "pa_2", "pa_age", "pa_id", "pa_year", "pair_type", "parent", "parent_idx", "pop", "pop_1", "pop_post", "pop_post_1", "prim_anc_1", "prim_anc_2", "primary_shared_ancestors", "psa_tibs", "relationship_zone_names", "relatives", "rero_1", "rero_ac", "sad_fem_counts", "samp_year_1", "samp_year_2", "samp_years_list", "samp_years_list_dur", "samp_years_list_post", "samp_years_list_pre", "samp_years_list_1", "samp_years_list_2", "sampling_year", "sampling_year_1", "sampling_year_2", "second", "sex", "sex_1", "sex_2", "surv_fract", "sy", "sy_1", "sy_2", "syears", "syears_dur", "syears_post", "syears_pre", "tag", "times_encountered", "tmp_1", "tmp_2", "to", "tot_dom", "tot_prob", "trio", "upper_member", "val", "value", "which_matrix", "x", "x_1", "x_2", "xjit", "xlab", "xmax", "xmin", "y", "y_1", "y_2", "year", "yjit", "ylab", "ymax", "ymin", "zone" ) ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/import.R
#' Download the spip binary and install it where CKMRpop expects it #' #' This checks the operating system and installs the correct version #' (either Darwin or Linux for Mac or Linux, respectively.) To install #' the spip binary this function downloads it from its GitHub site. It also #' installs a windows implementation of awk. #' @param Dir the directory to install spip into. Because of restrictions #' on functions writing to the user's home filespace, this is set, by default, #' to a temporary directory. But to really use this function to install spip, #' this parameter must be set to `system.file(package = "CKMRpop")`. #' @export #' @return No return value. Called for side effect of installing the 'spip' binary. #' @examples #' \dontrun{ #' install_spip(Dir = system.file(package = "CKMRpop")) #' } install_spip <- function( Dir = tempfile() ) { if(Dir != system.file(package = "CKMRpop")) { message("\n*** Note: To properly install spip, the function install_spip() must be called like this: ***\n\n install_spip(Dir = system.file(package = \"CKMRpop\")) \n*** The current invocation of install_spip() will not properly install it. ***") } # first check the OS Sys <- Sys.info()["sysname"] if(!(Sys %in% c("Darwin", "Linux", "Windows"))) { stop(paste("spip binary not available for operating system ", Sys, collapse = "")) } # then get the basename of the file we want pname <- paste("spip-", Sys, sep = "", collapse = "") if(Sys == "Windows") { pname <- paste(pname, ".zip", sep = "") } # have a variable to hold the base GitHub address: Git_base <- "https://github.com/eriqande/spip/raw/master/" Git_full <- paste(Git_base, pname, sep = "") # get the destination path and create the directory Dest_dir <- file.path(Dir, "bin") dir.create(Dest_dir, showWarnings = FALSE, recursive = TRUE) # record destination file name Dest_file <- file.path(Dest_dir, pname) # now, download the file and save to the correct destination: utils::download.file(url = Git_full, destfile = Dest_file) if(Sys == "Windows") { # extract the contents of the archive to the destination directory unzip(Dest_file, exdir = Dest_dir) # reset the name of the Dest file to not have the .zip extension Dest_file <- stringr::str_replace(Dest_file, "\\.zip$", ".exe") } # finally, change the file permissions to be user and group executable and writeable # and world readable Sys.chmod(Dest_file, mode = "0774", use_umask = FALSE) # if this is Windows, then also download gawk.exe and put it in the same spot if(Sys == "Windows") { message("Also downloading gawk.exe for Windows...") Dest_file <- file.path(Dest_dir, "gawk.zip") Gawk <- "https://github.com/eriqande/spip/raw/master/gawk.zip" utils::download.file(url = Gawk, destfile = Dest_file) unzip(Dest_file, exdir = Dest_dir) Dest_file <- stringr::str_replace(Dest_file, "\\.zip$", ".exe") Sys.chmod(Dest_file, mode = "0774", use_umask = FALSE) } }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/install_spip.R
#' Return a Leslie-like matrix from the spip parameters #' #' Here we take the survival rates for females and males and the sex ratio, #' as well as the annual new cohort size (assumed constant), #' and we make a leslie-like matrix #' to compute the stable age distribution. #' @param P a named list of the spip parameters. #' @param C the constant size of the newborn cohort each year #' @return #' This function returns a list with the following components: #' * `stable_age_distro_fem`: a vector of the expected number of females in each age #' group of 0 up to MaxAge-1 once the stable age distribution has been reached. Note that #' this corresponds to the PREKILL_CENSUS from spip. In this vector, the size of the #' MaxAge group is left out because this is how it is needed to be to insert into #' the `--initial-males` and `--initial-females` options in spip(). If you want the #' size of all age classes, use the output list component #' `stable_age_distro_fem_with_max_age_class`, described below. #' * `stable_age_distro_male`: same as above, but for males. #' * `stable_age_distro_fem_with_max_age_class`: The expected number of females from age 0 to #' MaxAge once the stable age distribution has been reached. #' * `stable_age_distro_male_with_max_age_class`: same as above, but for females. #' * `female_leslie_matrix`: The Leslie matrix implied by the spip parameters in P. #' @export #' @examples #' result <- leslie_from_spip(species_1_life_history, 300) #' #' # print the result list: #' result leslie_from_spip <- function(P, C) { # prepare a return list ret <- list() # clean up the friggin names in P. Once again, R doesn't do dashes well... names(P) <- gsub("\\p{Pd}", "-", names(P), perl = TRUE) # check to make sure that P has all the components we need needed <- c( "max-age", "fem-surv-probs", "fem-prob-repro", "fem-asrf", "male-surv-probs", "sex-ratio" ) needed <- gsub("\\p{Pd}", "-", needed, perl = TRUE) not_there <- setdiff(needed, names(P)) if(length(not_there) > 0) { stop( "You don't have the following needed elements in P: ", paste(not_there, collapse = ", ") ) } # first, get the values we need into convenient variables. A <- P[["max-age"]] fs <- P[["fem-surv-probs"]] pr <- P[["fem-prob-repro"]] ff <- P[["fem-asrf"]] ms <- P[["male-surv-probs"]] sr <- P[["sex-ratio"]] # now we make the matrix. We start by making a diagonal # matrix of s values, but we add an extra column onto that, # and then we slap a new row on the top. The first value of # that row is a 1, which signifies that the cohort size next year # is exactly the same as it was the year before (which is how things # work with the "const" cohort size in spip). m1 <- matrix(0, nrow = length(fs), ncol = length(fs)) diag(m1) <- fs m2 <- cbind(m1, 0.0) m3 <- rbind(0.0, m2) m3[1,1] <- 1.0 # that gives us our matrix for females: MF <- m3 # now, we do the same with the male survival probs m1 <- matrix(0, nrow = length(ms), ncol = length(ms)) diag(m1) <- ms m2 <- cbind(m1, 0.0) m3 <- rbind(0.0, m2) m3[1,1] <- 1.0 MM <- m3 # now, we get the stable age distros: eig_f <- eigen(MF)$vectors[,1] sad_f <- (1 - sr) * C * eig_f / eig_f[1] eig_m <- eigen(MM)$vectors[,1] sad_m <- sr * C * eig_m / eig_m[1] # put those in the return list. To make them conform to how spip # wants the values, take the last age class off of it. ret$stable_age_distro_fem <- sad_f[-length(sad_f)] ret$stable_age_distro_male <- sad_m[-length(sad_m)] # also return what the full stable age distro is ret$stable_age_distro_fem_with_max_age_class <- sad_f ret$stable_age_distro_male_with_max_age_class <- sad_m # finally, for the females, we want to return a what # a proper Leslie matrix would look like for a non-growing population # of this size. (i.e, we want to compute the fecundities that would go in the # top row of the actual leslie matrix). This could be used to later fiddle with # so as to design spip to simulate growing populations, etc. # The way we do this is we figure out the relative fecundities of each age class # using the prop of reproducing and the age-specific relative fecundities, then # we scale these so that the expected number of offspring in the next cohort, given # the stable age distribution, is C. rel_f <- fs * pr * ff tmp <- sum(rel_f * sad_f[-length(sad_f)]) f <- rel_f * (1 - sr) * C / tmp f_leslie <- MF f_leslie[1, ] <- c(f, 0.0) ret$female_leslie_matrix <- f_leslie ret }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/leslie_from_spip.R
#' plot an ancestry matrix (or multiple such matrices) from its (their) matrix form #' #' For illustration purposes, if you want to simply plot an ancestry #' matrix (or several) to show particular values, then this is the #' handy function for you. #' @param X input tibble with a factor or character column `ID` that gives #' the "name" of the ancestry matrix that will be used if you want to facet #' over the values in `ID`. And also `X` must have a list column `anc_match_matrix` each #' element of which is a logical ancestry match matrix. `X` may have a list column #' of tibbles called `psa_tibs` that says which cells are the primary shared ancestors. #' @return `plot_amm_from_matrix()` returns a ggplot object: each facet is an image of the #' ancestry match matrix. It is facet-wrapped over the values in the ID column of `X`. #' @export #' @examples #' # get some input: all the 2-generation AMMs in `example_amms` #' X <- example_amms[stringr::str_detect(names(example_amms), "2gen$")] %>% #' tibble::enframe(name = "ID", value = "anc_match_matrix") #' #' # plot those #' g <- plot_amm_from_matrix(X) + #' ggplot2::facet_wrap(~ ID) #' plot_amm_from_matrix <- function(X) { X2 <- X %>% select(ID, anc_match_matrix) %>% mutate(amm_as_tib = map(anc_match_matrix, amm2tibble)) %>% unnest(amm_as_tib) %>% mutate( ind_1 = factor(ancestor_abbrvs(max(x))[x], levels = ancestor_abbrvs(max(x))), ind_2 = factor(ancestor_abbrvs(max(y))[y], levels = ancestor_abbrvs(max(y))) ) %>% mutate(amm = as.character(amm)) basic_amm_plot(X2) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/plot_amm_from_matrix.R
#' plot the graph showing the connected components #' #' This is a simple wrapper for some tidygraph/ggraph functions #' that will let you find the connected components of a graph in which #' the related pairs are connected by edges. It also makes #' a plot of them. #' #' Note that it appears that the 'ggraph' package must be loaded #' for the plot output of this function to print correctly. #' @param Pairs the tibble that comes out of `compile_related_pairs()`. #' For this function it must have, at least the #' columns `id_1`, `id_2`, and `dom_relat`. #' @return #' This returns a list with two components: #' - `conn_comps`: a tibble with three columns: #' - `name`: the name of the sample #' - `cluster`: the index of the connected component the sample belongs to #' - `cluster_size`: the number of samples belonging #' to that cluster #' - `plot`: a ggraph/ggplot plot object showing the connected components as vertices with #' edges between them. #' @export #' @examples #' # get a Pairs tibble from the stored data #' Pairs <- compile_related_pairs(species_1_slurped_results_1gen$samples) #' PCC <- plot_conn_comps(Pairs) #' #' # look at the conn_comps: #' head(PCC$conn_comps) #' #' # if you want to print the plot, that seems to require #' # loading the ggraph library #' library(ggraph) #' PCC$plot plot_conn_comps <- function(Pairs) { fi_graph <- Pairs %>% mutate(`dom_relat-max_hit` = paste(dom_relat, max_hit, sep = "-")) %>% rename(from = id_1, to = id_2) %>% igraph::graph_from_data_frame(directed = FALSE) %>% tidygraph::as_tbl_graph() conn_comps <- fi_graph %>% igraph::components() %>% .$membership %>% enframe() %>% rename(cluster = value) %>% arrange(cluster, name) %>% group_by(cluster) %>% mutate(cluster_size = n()) %>% ungroup() fi_graph2 <- fi_graph %>% tidygraph::activate(nodes) %>% tidygraph::left_join(conn_comps, by = "name") # now, let's plot that thing pofs_clusters_plot <- ggraph::ggraph(fi_graph2, layout = "kk") + ggraph::geom_edge_link( aes( colour = `dom_relat-max_hit` ) ) + ggraph::geom_node_point() list( conn_comps = conn_comps, plot = pofs_clusters_plot ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/plot_conn_comps.R
#' Prepare input for the DFS relative-finding algorithm #' #' Uses the pedigree to convert individual IDs into indexes and #' compile information to make the data structures for the DFS #' algorithm to find relatives. #' @param ped the pedigree. A tibble with columns `kid`, `pa`, and `ma` #' @param samp_vec A character vector with the names of the individuals that were sampled #' @export #' @keywords internal prepare_for_dfs <- function(ped, samp_vec) { # figure out who the founders are. These are the individuals whose parents are "0" founders <- ped %>% filter(pa == "0" | ma == "0") %>% pull(kid) # get all the unique names of the individuals. Order doesn't matter, but we want # this to make a unique idx for each individual. Remove "0" after the fact levs <- unique(c(ped$pa, ped$ma, ped$kid)) levs <- levs[levs != "0"] # get the total number of individuals/nodes N <- length(levs) # get the total number of samples S <- length(samp_vec) # count up the number of children of each parent num_offs_pa <- ped %>% filter(pa != "0") %>% count(pa) %>% rename(parent = pa) num_offs_ma <- ped %>% filter(ma != "0") %>% count(ma) %>% rename(parent = ma) n_down <- bind_rows( num_offs_pa, num_offs_ma ) %>% rename(n_down = n) # here is a function for returning the 0-based index of a name idx0 <- function(name) { ret <- as.integer(factor(name, levels = levs)) - 1L ret[is.na(ret)] <- -1L ret } # now, we start adding columns to ped. These columns we will # eventually break off into a matrix. ped2 <- ped %>% mutate( kid_idx = idx0(kid), pa_idx = idx0(pa), ma_idx = idx0(ma), sampled = as.integer(kid %in% samp_vec) ) %>% left_join(n_down, by = c("kid" = "parent")) %>% mutate(n_down = ifelse(is.na(n_down), 0L, n_down)) # make the node matrix from that node_matrix <- ped2 %>% select(kid_idx:n_down) %>% as.data.frame() %>% as.matrix() # Now we need to make the down_matrix, counting children of every mother and father. # First, get a useful tibble. parents <- bind_rows( ped %>% filter(pa != "0") %>% select(pa, kid) %>% rename(parent = pa), ped %>% filter(ma != "0") %>% select(ma, kid) %>% rename(parent = ma) ) %>% #arrange(parent, kid) %>% # sorting this is not necessary and it takes a LONG time fog big pedigrees group_by(parent) %>% mutate( child_num = (1:n()) - 1L, ) %>% ungroup() %>% mutate( parent_idx = idx0(parent), kid_idx = idx0(kid) ) %>% select( parent, kid, parent_idx, child_num, kid_idx ) # then tweeze the down_matrix off of that. down_matrix <- parents %>% select(parent_idx, child_num, kid_idx) %>% as.data.frame() %>% as.matrix() # Get the names vec. This must just be levs. names_vec <- levs # get a vector of the 0-based indexes of the samples: sample_vec = sort(idx0(samp_vec)) # and, finally, return all that list( N = N, S = S, node_matrix = node_matrix, down_matrix = down_matrix, sample_vec = sample_vec, names_vec = names_vec ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/prepare_for_dfs.R
#' Return the recaptures from amongst the samples #' #' Given the tibble of sampled individuals #' return a tibble of all the recaptures. #' This is a somewhat complicated operation #' that expands recaptures to all possible pairs of recaptures. (i.e. if the #' individual was caught on 3 different occasions there will be three separate pairs). #' The column pair_type shows RC for recapture. #' #' This is broken now that sampling in different life episodes is #' demarcated as such. But I have left it in here unexported and internal #' in case I want to pick it up at some point. #' @param S the samples tibble with columns ID, sex, born_year, sampling_year #' @keywords internal recapture_pairs <- function(S) { S %>% rename_all(paste0, "_1") %>% group_by(ID_1) %>% filter(n() > 1) %>% arrange(sampling_year_1) %>% # always put the first sampling episode first dplyr::do( bind_cols( .[rep(1:nrow(.), each = nrow(.)), ], .[rep(1:nrow(.), nrow(.)), ] %>% rename_all(.funs = function(x) str_replace(x, "_1$", "_2")) ) ) %>% ungroup() %>% filter(sampling_year_1 < sampling_year_2) %>% mutate(pair_type = "RC") %>% select(pair_type, everything()) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/recapture_pairs.R
#' Return the perimeters of all the relationship zones #' #' This is primarily for plotting a figure in the paper about this package, #' showing where all the relationship zones are. It merely cycles over the #' possible relationships in [`relationship_zone_names`] and produces one or #' two rows in a tibble for each that has the corners of the rectangle of that #' zone in the columns xmin, xmax, ymin, and ymax. It is designed to be overlaid #' upon the ancestry_match_matrix plots. There are some additional columns that give #' us the midpoint of the area, etc. #' @return Returns a tibble with the following columns: #' - `which_matrix`: a column of values `M1` or `M2`. M1 denotes that the row's values #' are for the relationship zone found in or below the lower diagonal of the ancestry match matrix #' and M2 denotes that the row's value are of the zone found in the upper part of the #' ancestry match matrix. Symmetrical relationships are considered to be M1. #' - `zone`: The abbreviation for the relationship (e.g., Se, PO, Si, etc.) #' - `xmin`: The left-hand x value of the zone. #' - `xmax`: The right-hand x value of the zone. #' - `ymin`: The bottom y value of the zone. #' - `ymax`: The top y value of the zone. #' - `area`: The area in unit squares of the zone. #' - `xmid`: The x midpoint of the zone. #' - `ymid`: The y midpoint of the zone. #' #' @export #' @examples #' relationship_zone_perimeters() relationship_zone_perimeters <- function() { lapply(relationship_zone_names, function(R) { tmp_tib <- lapply(anc_match_masks(4, R), function(m) { xmin <- min(which(apply(m, 2, function(x) any(x==TRUE)))) xmax <- max(which(apply(m, 2, function(x) any(x==TRUE)))) ymin <- min(which(apply(m, 1, function(x) any(x==TRUE)))) ymax <- max(which(apply(m, 1, function(x) any(x==TRUE)))) tibble( zone = R, xmin = xmin - 0.5, xmax = xmax + 0.5, ymin = ymin - 0.5, ymax = ymax + 0.5 ) }) %>% bind_rows(.id = "which_matrix") if(R %in% c("Se", "Si", "FC", "SC", "TC")) { tmp_tib <- tmp_tib[1,] } tmp_tib }) %>% bind_rows() %>% mutate( which_matrix = paste0("M", which_matrix), area = (xmax - xmin) * (ymax - ymin), xmid = (xmax + xmin) / 2, ymid = (ymax + ymin) / 2, ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/relationship_zone_perimeters.R
#' Find connected components amongst the related pairs #' #' This is a little utility function that actually gets called from #' within `compile_related_pairs()` so we leave it as an internal function. #' This takes in the tibble Pairs, and then spits out a tibble that looks #' just the same, except that after the id_1 and id_2 columns it now has a #' column called `conn_comp` that gives the connected component index of the #' two pair members. #' @param Pairs a tibble with the related pairs. It must have columns id_1 and #' id_2 #' @keywords internal relpair_conn_comps <- function(Pairs) { clusters <- Pairs %>% rename(to = id_1, from = id_2) %>% select(to, from) %>% igraph::graph_from_data_frame() %>% igraph::components() %>% .$membership %>% enframe() %>% rename(indiv = name, cluster = value) %>% arrange(cluster, indiv) # now get a data frame that has the pairs and cc's pairs_n_ccs <- Pairs %>% left_join(clusters %>% rename(cc_1 = cluster), by = c("id_1" = "indiv")) %>% left_join(clusters %>% rename(cc_2 = cluster), by = c("id_2" = "indiv")) # cc_1 and cc_2 should be the same. If not we throw a warning. if(any(pairs_n_ccs$cc_1 != pairs_n_ccs$cc_2)) { warning("Weirdness, pair members with different cc_1 and cc_2. Please inspect.") } # collapse those down to a single column called conn_comp P <- pairs_n_ccs %>% rename(conn_comp = cc_1) %>% select(-cc_2) %>% select(id_1, id_2, conn_comp, everything()) # in the end, just return P P }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/relpair_conn_comps.R
#' Run spip in a user-specified directory #' #' This runs it in a directory and the output from stdout #' goes into a big file spip_out.txt in that directory. Currently #' this is pretty bare bones. #' @param pars A named list of parameter values. #' @param dir The directory to run it in. Defaults to a temp directory, #' which will be unique every time it is run. #' @param spip_seeds a vector of two positive integers. These get written to the #' file spip_seeds, which is used by spip to seed its random number generator. By #' default, R supplies these two integers from its own random number generator. This #' way reproducible results from spip can be obtained by calling `set.seed()` from within #' R before calling `run_spip()`. For the most part, the user should never really have #' to directly supply a value for spip_seeds. #' @param num_pops the number of demes that are being simulated. This is still being #' implemented... #' @param allele_freqs a list of allele frequencies provided if you want #' to simulate unlinked genotypes for the sampled individuals. The default #' is simply a single locus with two alleles at frequencies 0.5, 0.5, which #' is provided because spip has to be given some allele frequencies if sampling #' is to be carried out. Note that a user-specified value to this option should #' only be given if you want to actually simulate some genetic data from the #' sampled individuals. The length of the list should be the number of loci #' desired, and the length of each element should be the number of alleles. #' For examples for three loci with 2, 3, and 4 equifrequent alleles, respectively, #' you would provide `list(c(0.5, 0.5), c(0.3333, 0.3333, 0.3333), c(0.25, 0.25, 0.25, 0.25))`. #' Note that allele frequencies will be normalized to sum to one within each locus. #' @details This creates a temporary directory and runs spip in that directory, redirecting #' stdout and stderr to files. It then processes the output using awk to create a collection #' of files. If spip throws an error, the contents of stderr are written to the screen to notify #' the user of how to correct their input. #' #' For a full example of its use see the Vignette: #' `vignette("species_1_simulation", package = "CKMRpop")`. #' @return Returns the path to the temporary directory were `spip` was run and where the #' processed output files can be found to be read in using `slurp_spip()`. #' @export run_spip <- function( pars, dir = tempfile(), spip_seeds = ceiling(runif(2, 1, 1e9)), num_pops = 1, allele_freqs = list(c(0.5, 0.5)) ) { # before doing anything, check to see if the spip binary is there, and dump # an error if it is not: boing <- spip_binary() cwd = getwd() # get the current directory to change back to it after the system2 call on.exit(setwd(cwd)) dir.create(dir, showWarnings = FALSE, recursive = TRUE) # write parameters to demog.comm dfile <- file.path(dir, "demog.comm") sfile <- file.path(dir, "spip_out.txt") efile <- file.path(dir, "spip_err.txt") lfile <- file.path(dir, "alle_freq.txt") seedfile <- file.path(dir, "spip_seeds") # write the spip_seeds file in dir cat(spip_seeds, sep = " ", eol = "\n", file = seedfile) # now, make the allele frequency file cat(length(allele_freqs), file = lfile, sep = "\n") dump <- lapply(allele_freqs, function(x) { cat(length(x), " ", file = lfile, append = TRUE) cat(x/sum(x), "\n", sep = " ", file = lfile, append = TRUE) }) # now, make the demography and sampling file of commands. # If num_pops == 1 then we just dump the pars list into it. if(num_pops == 1) { cat("& generated from R &\n", file = dfile) dump <- lapply(names(pars), function(n) { # R is inconsistent in type of dash it prints, so standardize with # this line: n_clean <- gsub("\\p{Pd}", "-", n, perl = TRUE) cat( "--", n_clean, " ", paste(pars[[n]], collapse = " "), "\n", sep = "", file = dfile, append = TRUE ) }) } # if num_pops > 1, then we check to make sure that pars is a list of length # num_pops and we dump each element in the list into dfile separated by --new-pop # directives, as appropriate. if(num_pops > 1) { if(length(pars) != num_pops) { stop("Hold it! When num_pops > 1, the pars parameter must be a list with a single list element (or parameters) for each population.") } cat("& generated from R &\n", file = dfile) for(p in 1:num_pops) { subpars <- pars[[p]] dump <- lapply(names(subpars), function(n) { # R is inconsistent in type of dash it prints, so standardize with # this line: n_clean <- gsub("\\p{Pd}", "-", n, perl = TRUE) cat( "--", n_clean, " ", paste(subpars[[n]], collapse = " "), "\n", sep = "", file = dfile, append = TRUE ) }) cat( "--locus-file ", lfile, "\n", sep = "", file = dfile, append = TRUE ) if(p < num_pops) { cat("--new-pop", "\n", sep = "", file = dfile, append = TRUE ) } } } if(num_pops == 1) { args <- paste(" --num-pops ", num_pops, " --command-file ", dfile, " --locus-file ", lfile ) } else { args <- paste(" --num-pops ", num_pops, " --command-file ", dfile) } message("Running spip in directory ", dir) # Run this in system2 setwd(dir) spip_ret <- system2( command = spip_binary(), args = args, stdout = sfile, stderr = efile ) # catch the case where spip threw an error if(spip_ret != 0) { error_lines <- readr::read_lines(efile) message("\n\n*** spip reported the following errors ***\n\n") message(paste(error_lines, collapse = "\n")) stop("\n\nAborting. Please fix error to spip input and try again.\n\n For a brief listing of all available spip options use: system2(command = spip_binary(), args = \"--help\") For a long listing, use: system2(command = spip_binary(), args = \"--help-full\")\n\n ") } message( "Done running spip. Output file size is ", file.size(sfile) / 1e6, " Mb" ) message("Processing output file with awk") # now, use awk to process that large text file into some things that # can be read in by R. For very large output files, I think that # awk will almost certainly be faster. single_pass_awk <- system.file("shell/single_pass_cps.awk", package = "CKMRpop") awk_binary <- "awk" # on Linux or Mac this should be on the path Sys <- Sys.info()["sysname"] if(Sys == "Windows") { awk_binary <- system.file("bin/gawk.exe", package = "CKMRpop") if(awk_binary == "") { stop("Not finding gawk.exe binary on Windows. Please reinstall spip, with: install_spip(Dir = system.file(package = \"CKMRpop\"))") } } system2( command = awk_binary, args = c(" -f ", single_pass_awk, " spip_out.txt "), stdout = "single_pass_stdout.txt", stderr = "single_pass_stderr.txt" ) message("Done processing output into spip_pedigree.tsv, spip_prekill_census.tsv, and spip_samples.tsv") # here is how I used to call it using system() # call <- paste("./bin/spip --command-file ", dfile, " --locus-file ", lfile, " > ", sfile ) # system(call) # return the path of the directory where everything happened dir }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/run_spip.R
#' Read in the pedigree, census, and sampling information from the spip run #' #' This function is run after `run_spip()`. It assumes that `run_spip()` #' has left the files: `spip_pedigree.tsv`, `spip_prekill_census.tsv`, and #' `spip_samples.tsv`, `spip_postkill_census.tsv`, `spip_deaths.tsv`, #' `spip_genotypes.tsv`, and `spip_migrants.tsv` #' inside the directory where `run_spip()` was run. #' #' For an example of its use, see the Vignette: #' `vignette("species_1_simulation", package = "CKMRpop")`. #' @param dir the path to the directory where spip was run. This is #' returned by `run_spip()`. #' @param num_generations how many generations back do you wish to consider #' for find relatives of #' each sampled individual. 0 means just the individual themselves (so, not very #' interesting, and you likely wouldn't ever use it. 1 means up to #' and including the parents; 2 means up to and including the grandparents; 3 means up to #' and including the great grandparents; and so forth. #' @return A list of tibbles. Each tibble is a named component of #' the return list. The names are as follows: #' - `pedigree` #' - `census_prekill`, #' - `census_postkill`, #' - `samples`, #' - `deaths`, #' - `genotypes`, #' - `migrants` #' #' You can inspect some example output in #' the package data object `three_pops_with_mig_slurped_results` #' @export #' @examples #' # see Vignette: vignette("species_1_simulation", package = "CKMRpop") slurp_spip <- function( dir, num_generations ) { ped_file <- file.path(dir, "spip_pedigree.tsv") census_file <- file.path(dir, "spip_prekill_census.tsv") sample_file <- file.path(dir, "spip_samples.tsv") post_census_file <- file.path(dir, "spip_postkill_census.tsv") deaths_file <- file.path(dir, "spip_deaths.tsv") genos_file <- file.path(dir, "spip_genotypes.tsv") migrants_file <- file.path(dir, "spip_migrants.tsv") # read in the files, and do any necessary processing ped <- vroom::vroom( file = ped_file, delim = "\t", col_types = "iiccc" ) census <- vroom::vroom( file = census_file, delim = "\t", col_types = "iiiii" ) post_census <- vroom::vroom( file = post_census_file, delim = "\t", col_types = "iiiii" ) death_reports <- vroom::vroom( file = deaths_file, delim = "\t", col_types = "cii" ) migrants <- vroom::vroom( file = migrants_file, delim = "\t", col_types = "iic" ) %>% separate( event, into = c("ID", "from_pop", "arrow", "to_pop"), sep = " +", convert = TRUE ) %>% select(ID, everything()) %>% select(-arrow) samples <- vroom::vroom( file = sample_file, delim = "\t", col_types = "ccccccc" ) %>% mutate( samp_years_list_pre = str_split(syears_pre, " *"), samp_years_list_pre = map(.x = samp_years_list_pre, .f = function(x) as.integer(x)), samp_years_list = str_split(syears_post, " *"), samp_years_list = map(.x = samp_years_list, .f = function(x) as.integer(x)), samp_years_list_dur = str_split(syears_dur, " *"), samp_years_list_dur = map(.x = samp_years_list_dur, .f = function(x) as.integer(x)) ) %>% select(-syears_pre, -syears_post, -syears_dur) %>% extract( ID, into = c("sex", "born_year", "born_pop"), regex = "^([MF])([0-9]+)_([0-9]+)", remove = FALSE, convert = TRUE ) %>% mutate(samp_years_list_post = samp_years_list) # this is a weird thing I am doing here. I realized that # gtyp-ppn-{male,fem}-post should be what people usually use, # so I make that the samp_years_list that gets used downstream. #%>% # now, here we add a list column with the ancestors over num_generations # mutate( # ancestor_list = ancestor_vectors( # indivs = ID, # ped = ped, # num_generations = num_generations + 1 # ) # ) # The above implementation is too slow for millions of individuals # Now, get a data frame of the samples' ancestor and relatives and # join it to samples. SAR <- find_ancestors_and_relatives_of_samples(P = ped, S = samples$ID, num_generations) # finally, read in the genotypes genos <- readr::read_tsv( file = genos_file, col_names = FALSE ) genos <- genos[, -length(genos)] # this removes that empty column at the end names(genos) <- c("ID", paste("Locus", 1:(length(genos) - 1), sep = "_")) list( pedigree = ped, census_prekill = census, census_postkill = post_census, samples = left_join(samples, SAR, by = c("ID" = "sample_id")), deaths = death_reports, genotypes = genos, migrants = migrants ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/slurp_spip.R
#' file path to be used in a call to spip #' #' This version checks to make sure it is there and throws an #' error with a suggestion of how to get it if it is not there. #' @keywords internal spip_binary <- function() { if(!spip_exists()) { stop("Can't find the spip executable where it was expected at ", spip_binary_path(), ". Download and install spip with: install_spip(Dir = system.file(package = \"CKMRpop\")) ") } # then I should check to make sure it is executable # though I have not implemented that... # if so, return the path spip_binary_path() }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/spip_binary.R
#' return the path where spip should be in the R system paths #' #' It expects it to be in the R package directory after external installation. #' @keywords internal spip_binary_path <- function() { bin_name <- paste("spip", Sys.info()["sysname"], sep = "-") if(Sys.info()["sysname"] == "Windows") { bin_name <- paste(bin_name, ".exe", sep = "") } file.path(system.file(package = "CKMRpop"), "bin", bin_name) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/spip_binary_path.R
#' return TRUE if spip exists where it should be installed. #' #' This just checks for the file where it gets installed with #' `install_spip()`. This is exported so it can be used to control #' the flow in the vignettes, so that vignettes can still be #' written using saved results when spip is not installed (i.e., #' at CRAN, etc.) #' @export #' @return A single logical scalar, either TRUE or FALSE. #' @examples #' # will be FALSE unless spip has been externally installed #' spip_exists() spip_exists <- function() { file.exists(spip_binary_path()) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/spip_exists.R
#' print the abbreviated usage information from spip #' #' This simply calls spip with the `--help` option. #' @export #' @return This returns the exit status of `spip` if spip is installed, #' but the return value is of little use. Mainly this is run for the side #' effect of printing the `spip` help menu to the console. #' @examples #' \dontrun{spip_help()} spip_help <- function() { system2(command = spip_binary(), args = "--help") }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/spip_help.R
#' print the full usage information from spip #' #' This simply calls spip with the `--help-full` option. #' @export #' @return This returns the exit status of `spip` if spip is installed, #' but the return value is of little use. Mainly this is run for the side #' effect of printing the `spip` full help menu to the console. #' @examples #' \dontrun{spip_help()} spip_help_full <- function() { system2(command = spip_binary(), args = "--help-full") }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/spip_help_full.R
#' Summarize the distribution of number of offspring and number of mates #' #' More later #' @param census_postkill a tibble with the postkill numbers of individuals. This #' is here so we know the total number of individuals that could have reproduced in a given #' year. #' @param pedigree a tibble with columns of `year`, `kid`, `pa`, and `ma`. The IDs of the' #' individuals must by like MX_Y where M means male, X is the birth year, and Y is the unique #' ID number. #' @param deaths a tibble with columns of `ID`, `year`, and `age`, giving the years and ages at which #' different individuals died. #' @param lifetime_hexbin_width a vector of length two. The first element is the width in the #' age direction of each hexbin and the second is the width in the lifetime number of offspring #' direction for the `plot_lifetime_output_vs_age_at_death` output plot. #' @param contrib_bin_width width of bins of histogram of contribution of parents of #' each age and sex to the offspring. #' @export #' @return A list with three components, each of them a ggplot object: #' - `plot_age_specific_number_of_offspring`: a ggplot object that plots boxplots and jittered points. #' The x-axis are the ages of the individuals; the y-axis shows the number of offspring. Summarized #' over the entire spip simulation. This is faceted by sex. #' - `plot_lifetime_output_vs_age_at_death`: a ggplot object. This is a hexbin plot. The x-axis #' are age-at-death bins, the y axis are bins of total number of offspring produced in a lifetime. #' The fill color of each bin gives the number of individuals with that age at death and number #' of offspring encountered over the whole simulation. Plot is faceted by sex. #' - `plot_fraction_of_offspring_from_each_age_class`: a ggplot object. This shows the distribution #' over all years of the simulation, of the fraction of offspring produced each year that were #' produced by males or females of a given age (the plots are facet-wrapped by both age and sex). #' The blue vertical line gives the mean. #' @examples #' # get stored slurped output for an example #' X <- species_1_slurped_results #' g <- summarize_offspring_and_mate_numbers( #' X$census_postkill, #' X$pedigree, #' X$deaths #' ) #' #' # Now g is a list holding three plots, accessible like this: #' #' # g$plot_age_specific_number_of_offspring #' #' # g$plot_lifetime_output_vs_age_at_death #' #' # g$plot_fraction_of_offspring_from_each_age_class #' summarize_offspring_and_mate_numbers <- function( census_postkill, pedigree, deaths, lifetime_hexbin_width = c(1,1), contrib_bin_width = 0.01 ) { # first, we need to just wrangle the data to make pa_year and ma_year columns ped2 <- pedigree %>% filter(ma != "0" & pa != "0") %>% rename( kid_year = year, kid_id = kid, pa_id = pa, ma_id = ma ) %>% extract( pa_id, into = "pa_year", regex = "M([0-9]+)_", remove = FALSE, convert = TRUE ) %>% extract( ma_id, into = "ma_year", regex = "F([0-9]+)_", remove = FALSE, convert = TRUE ) %>% mutate(trio = 1:n()) %>% select(pop, trio, kid_year, pa_year, ma_year, kid_id, pa_id, ma_id) %>% mutate( pa_age = kid_year - pa_year, ma_age = kid_year - ma_year ) # offspring from each parent by age and year dads_y <- ped2 %>% count(pop, kid_year, pa_age, pa_id) moms_y <- ped2 %>% count(pop, kid_year, ma_age, ma_id) ### This blcok is a bunch of stuff that I ended up not needing for the final plots I wanted to make ### if(FALSE) { # then we also have to use the census_postkill information to know the # number of males and females still alive that produced no offspring. # First we need the number of dads and moms with at least one offspring, # each year, and of each age. This is quite the hassle, but we end up with # a tibble showing how many males (or females) had nkids = 0. zero_males <- dads_y %>% group_by(pop, kid_year, pa_age) %>% summarise(n_dads = n_distinct(pa_id)) %>% ungroup %>% left_join( x = census_postkill %>% select(-female), y = ., by = c( "pop" = "pop", "year" = "kid_year", "age" = "pa_age" ) ) %>% mutate(n_dads = replace_na(n_dads, 0)) %>% mutate( nkids = 0, n = male - n_dads ) %>% select(pop, year, age, nkids, n) zero_females <- moms_y %>% group_by(pop, kid_year, ma_age) %>% summarise(n_moms = n_distinct(ma_id)) %>% ungroup %>% left_join( x = census_postkill %>% select(-male), y = ., by = c( "pop" = "pop", "year" = "kid_year", "age" = "ma_age" ) ) %>% mutate(n_moms = replace_na(n_moms, 0)) %>% mutate( nkids = 0, n = female - n_moms ) %>% select(pop, year, age, nkids, n) # now we count up how many males and females had nkids with nkids > 1 dads_n <- dads_y %>% rename(nkids = n, year = kid_year, age = pa_age) %>% count(pop, year, age, nkids) %>% mutate(parent = "pa") moms_n <- moms_y %>% rename(nkids = n, year = kid_year, age = ma_age) %>% count(pop, year, age, nkids) %>% mutate(parent = "ma") } # put dads_y and mom_y into a single data frame to plot. num_offs <- bind_rows( male = dads_y %>% rename( age = pa_age, id = pa_id ), female = moms_y %>% rename( age = ma_age, id = ma_id ), .id = "sex" ) # we need to add explicit 0s in there for some ages to get the colors # consistent with the census plots bzs <- num_offs %>% group_by( sex ) %>% summarise( age = list(setdiff(0:max(age), age)) ) %>% unnest(cols = age) %>% mutate( id = "big_zero", pop = 0, n = 0, kid_year = min(num_offs$kid_year) ) # now, add those in there: num_offs2 <- bind_rows( num_offs, bzs ) %>% mutate(age = factor(age, levels = 0:max(age))) num_offs_boxplots <- ggplot( data = num_offs2, mapping = aes( x = age, y = n ) ) + geom_jitter( aes(colour = age), size = 0.2, width = 0.2, height = 0.3 ) + geom_boxplot( aes(fill = age), colour = "black", alpha = 0.9, outlier.shape = 21, outlier.fill = NA, outlier.stroke = 0.3, outlier.colour = "black" ) + facet_wrap( ~ sex, ncol = 1 ) #### Now we want to make a plot of the lifetime reproductive output as a function of age at death #### # We will do this only for the individuals that explicitly died in the simulation. # That means that anyone who had not died by the end of the simulation will not be # included # count up lifetime number of offspring for each individual lifetime <- pedigree %>% pivot_longer( cols = c(pa, ma), names_to = "parent", values_to = "ID" ) %>% filter(ID != "0") %>% count(ID) # now, join that onto the ages at death lt2 <- deaths %>% left_join(lifetime, by = "ID") %>% mutate( n = replace_na(n, 0), sex = case_when( str_detect(ID, "^M") ~ "male", str_detect(ID, "^F") ~ "female", TRUE ~ NA_character_ ) ) # now we can make hexbin plot of that lt_plot <- ggplot( lt2, aes(x = age, y = n) ) + geom_hex(binwidth = c(1, 2)) + scale_fill_viridis_c(option = "C", trans = "log10") + facet_wrap(~ sex, nrow = 1) + ylab("Lifetime number of offspring") + xlab("Age at death") ### Now, making a plot of what fraction of the offspring are from each age class ### # We are going to make histograms, faceted by age. # let's count up the fraction from each age group each year off_fracts <- ped2 %>% select(kid_year, pa_age, ma_age) %>% pivot_longer( cols = c(pa_age, ma_age), names_to = c("parent", ".value"), names_sep = "_" ) %>% mutate( sex = case_when( parent == "pa" ~ "male", parent == "ma" ~ "female", TRUE ~ NA_character_ ) ) %>% count(kid_year, sex, age) %>% group_by(kid_year, sex) %>% mutate(fract = n / sum(n)) # let's get the means of the fractions across all years mean_fracts <- off_fracts %>% group_by(sex, age) %>% summarise(mean_fract = mean(fract)) # now we plot that dude, faceting on both sex and age age_contrib <- ggplot( off_fracts, aes(x = fract) ) + geom_histogram( binwidth = contrib_bin_width, fill = "gray", colour = "black", size = 0.2 ) + geom_vline( data = mean_fracts, mapping = aes(xintercept = mean_fract), colour = "blue" ) + facet_wrap(age ~ sex) + theme_bw() + xlab("Fraction of annual offspring produced") ### Here we want to look at the distribution of number of mates producing offspring ### # we want to give a sense of the mean and variability in number of offspring produced with # different mates, to be able to verify that the polygamy vs monogamy settings are reasonable. list( plot_age_specific_number_of_offspring = num_offs_boxplots, plot_lifetime_output_vs_age_at_death = lt_plot, plot_fraction_of_offspring_from_each_age_class = age_contrib ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/summarize_offspring_and_mate_numbers.R
#' Summarize annual sex-and-age-specific survival rates from the census information #' #' The prekill census in year t+1 is the post-kill census in year t, so #' we can use the prekill census to record the realized fraction of individuals #' of each age and sex that survived the death episode in each year. In the #' output survival in year t is the fraction of j-year olds in year t that #' survive to be j+1 year-olds in year t+1. #' #' This function does not track migrants. Another one is eventually #' in order that accounts for migrants out of the population. Also, #' the plots here might not play well with multiple populations. #' @param census a tibble of census counts with columns `year` and #' `age`, and then the counts of the different sexes in columns #' named `male`, and `female`. #' @param fem_surv_probs a vector of the parameters used for the simulation. If present #' these are put on the histogram plots. If you provide one of these, you have to provide both. #' @param male_surv_probs a vector of the parameters used for the simulation. If present #' these are put on the histogram plots. #' @param nbins number of bins for the histograms #' @return A list with components: #' - `survival_tibble`: A tibble with the following columns: #' - `year`: The year #' - `pop`: The population whose census is being counted #' - `age`: The age of individuals #' - `sex`: The sex of individuals #' - `n`: The number of individuals alive and present of sex `sex` and age `age` in year #' `year` in pop `pop`. #' - `cohort`: The birth year of these individuals #' - `surv_fract`: The fraction of the n individuals that survive to have age `age + 1` in #' year `year + 1`. #' - `plot_histos_by_age_and_sex`: A ggplot object of histograms of observed survival fractions #' facet-wrapped by age and sex. Blue vertical lines are the observed means and dashed vertical #' red lines are the expected values given the simulation parameters. #' @export #' @examples #' result <- summarize_survival_from_census( #' species_1_slurped_results$census_prekill, #' species_1_life_history$`fem-surv-probs`, #' species_1_life_history$`male-surv-probs` #' ) #' #' # print the results if you want #' result$survival_tibble #' result$plot_histos_by_age_and_sex #' summarize_survival_from_census <- function( census, fem_surv_probs = NULL, male_surv_probs = NULL, nbins = 10 ) { # compute the survival fractions surv_fracts <- census %>% pivot_longer( cols = c(male, female), names_to = "sex", values_to = "n" ) %>% mutate(cohort = year - age) %>% arrange(pop, sex, cohort, year, age) %>% group_by(pop, sex, cohort) %>% mutate( surv_fract = replace_na( data = lead(n) / n, replace = 0 ) ) %>% ungroup() %>% filter(surv_fract <= 1.0) # there are some at the beginning that are wonky num_age_classes <- max(surv_fracts$age) if(xor(is.null(fem_surv_probs), is.null(male_surv_probs))) { stop("Sorry! You have to provide both male_surv_probs and fem_surv_probs or neither. Not just one of them") } if(!is.null(fem_surv_probs)) { stopifnot(length(fem_surv_probs) == num_age_classes) stopifnot(length(male_surv_probs) == num_age_classes) surv_param <- tibble( age = (1:length(fem_surv_probs)) - 1L, female = fem_surv_probs, male = male_surv_probs ) %>% pivot_longer( cols = c(male, female), names_to = "sex", values_to = "surv_param" ) } # compute age means: age_means <- surv_fracts %>% group_by(sex, age) %>% summarise(mean_surv = mean(surv_fract)) # make the histogram figure g <- ggplot(surv_fracts %>% filter(surv_fract > 0)) + geom_histogram( aes(x = surv_fract), bins = nbins, fill = "white", colour = "black", size = 0.2 ) + geom_vline( data = age_means %>% filter(mean_surv > 0), mapping = aes(xintercept = mean_surv), colour = "blue" ) + facet_wrap(age ~ sex) if(!is.null(male_surv_probs)) { g <- g + geom_vline( data = surv_param, mapping = aes(xintercept = surv_param), colour = "red", linetype = "dashed" ) } list( survival_tibble = surv_fracts, plot_histos_by_age_and_sex = g ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/summarize_survival_from_census.R
#' Summarise kin-pair information and use it to create uncooked spaghetti plots #' #' This gives a nice graphical summary of all the kin pairs along with when they #' were sampled and their age at the time of sampling and their sex. #' #' In order to visually summarize all the kin pairs that were found, #' with specific reference to their age, time of sampling, and sex, I find it #' helpful to use what I have named the "Uncooked Spaghetti Plot". There are multiple #' subpanels on this plot. Here is how to read/view these plots: #' - Each row of subpanels is for a different dominant relationship, going from #' closer relationships near the top and more distant ones further down. You can #' find the abbreviation for the dominant relationship at the right edge of the panels. #' - In each row, there are four subpanels: `F->F`, `F->M`, `M->F`, and `M->M`. These #' refer to the different possible combinations of sexes of the individuals in the pair. #' + For the non-symmetrical relationships these are naturally defined with the #' first letter (`F` for female or `M` for male) denoting the sex of the "upper_member" #' of the relationship. That is, if it is PO, then the sex of the parent is the first letter. #' The sex of the non-upper-member is the second letter. Thus a `PO` pair that consists of #' a father and a daughter would appear in a plot that is in the `PO` row in the `M->F` column. #' + For the symmetrical relationships, there isn't a comparably natural way of #' ordering the individuals' sexes for presentation. For these relationships, the #' first letter refers to the sex of the individual that was sampled in the earliest #' year. If both individuals were sampled in the same year, and they are of different #' sexes, then the female is considered the first one, so those all go on the `F->M` subpanel. #' - On the subpanels, each straight line (i.e., each piece of uncooked spaghetti) represents #' a single kin pair. The two endpoints represent the year/time of sampling (on the x-axis) #' and the age of the individual when it was sampled (on the y-axis) of the two members of #' the pair. #' + If the relationship is non-symmetrical, then the line is drawn as an arrow pointing #' from the upper member to the lower member. #' + The color of the line gives the number of shared ancestors (`max_hit`) at the level #' of the dominant relationship. This is how you can distinguish full-sibs from half-sibs, etc. #' @param Pairs The tibble of kin pairs that comes out of `compile_related_pairs()`. #' @param Samples The tibble of samples that comes out of `slurp_spip()`. #' @param jitter_age half the width of the uniform jitter window around age #' @param jitter_year half the width of the uniform jitter window around sampling year #' @return `uncooked_spaghetti()` returns a list with two components: `input_data` and `plot`. #' `plot` is a ggplot object of the plot described above in "Description." `input_data` is, #' itself, another list with the following named components: #' - `P5`: A tibble that is a processed version of the `Pairs` input. This is what #' goes into making the ggplot. #' - `age_grid`: A tibble giving the coordinates for placing the alternating pink and white #' horizontal background rectangles on the plot. #' - `year_grid`: A tibble giving the coordinates for placing the alternating pink and white #' vertical background rectangles on the plot. #' @export #' @examples #' # get the input variables #' # only take the first 50 samples to reduce time for example #' Samples <- species_1_slurped_results$samples[1:50, ] #' Pairs <- compile_related_pairs(Samples) #' result <- uncooked_spaghetti(Pairs, Samples) #' #' # produce the plot with: #' # result$plot uncooked_spaghetti <- function( Pairs, Samples, jitter_age = 0.2, jitter_year = 0.2 ) { # First, grab just the colums that we want to use for this P <- Pairs %>% select(id_1, id_2, dom_relat, max_hit, upper_member, pop_post_1:samp_years_list_2) # now, we get all combinations of the different sampling years through # a couple of left_joins s1 <- P %>% select(id_1, samp_years_list_1) %>% filter(!duplicated(id_1)) %>% unnest(cols = c(samp_years_list_1)) %>% rename(samp_year_1 = samp_years_list_1) s2 <- P %>% select(id_2, samp_years_list_2) %>% filter(!duplicated(id_2)) %>% unnest(cols = c(samp_years_list_2)) %>% rename(samp_year_2 = samp_years_list_2) # here we left_join to expand things over the sampling years and compute # the ages at sampling. We also determine which column each pair should be in. P2 <- P %>% left_join(s1, by = "id_1") %>% left_join(s2, by = "id_2") %>% select(-samp_years_list_1, -samp_years_list_2) %>% mutate( age_1 = samp_year_1 - born_year_1, age_2 = samp_year_2 - born_year_2, sex_config = case_when( (is.na(upper_member) | upper_member == 0) & (samp_year_1 < samp_year_2) ~ str_c(sex_1, "->", sex_2), (is.na(upper_member) | upper_member == 0) & (samp_year_1 > samp_year_2) ~ str_c(sex_2, "->", sex_1), (is.na(upper_member) | upper_member == 0) & (samp_year_1 == samp_year_2) & (sex_1 != sex_2) ~ "F->M", (is.na(upper_member) | upper_member == 0) & (samp_year_1 == samp_year_2) & (sex_1 == sex_2) ~ str_c(sex_1, "->", sex_2), upper_member == 1 ~ str_c(sex_1, "->", sex_2), upper_member == 2 ~ str_c(sex_2, "->", sex_1), TRUE ~ "WTF?!" ) ) # now, we really need to add the "Se" category to that. We do this by just expanding # the individuals that were sampled more than once. Selfies <- Samples %>% filter(map_int(samp_years_list, length) > 1) %>% mutate( first = map( .x = samp_years_list, .f = function(x) combn(x, 2)[1,] ), second = map( .x = samp_years_list, .f = function(x) combn(x, 2)[2,] ) ) %>% mutate(id_1 = ID, id_2 = ID) %>% unnest(cols = c(first, second)) %>% rename( samp_year_1 = first, samp_year_2 = second ) %>% mutate( dom_relat = "Se", max_hit = 1, upper_member = NA, pop_1 = pop_post, # this is going to need fixing when we start keeping track of which populations they were sampled from pop_2 = pop_post, sex_1 = sex, sex_2 = sex, born_year_1 = born_year, born_year_2 = born_year, age_1 = samp_year_1 - born_year_1, age_2 = samp_year_2 - born_year_2, sex_config = str_c(sex, "->", sex) ) %>% select(intersect(names(P2), names(.))) # hacky, dealing with all the extra columns after I added other census sizes in there if(nrow(Selfies) > 0) { P3 <- bind_rows( Selfies, P2 ) } else { P3 <- P2 } # now, we are going to want to jitter the endpoints consistently for these different individuals, # so that we can better see overlapping pairs. Also, if you get half-sibs of the same age in the # same year, you couldn't see them without some jittering. So, we are going to jitter things within jitter_age and jitter_year # of either side of their actual value, then we will throw down some light gray rectangles over those # areas so that we know which integer each corresponds to. This is going to involve some joins. xys <- bind_rows( P3 %>% select(id_1, samp_year_1, age_1) %>% rename(id = id_1, sy = samp_year_1, age = age_1), P3 %>% select(id_2, samp_year_2, age_2) %>% rename(id = id_2, sy = samp_year_2, age = age_2) ) %>% distinct() %>% mutate( x = sy + runif(n(), min = -jitter_year, max = jitter_year), y = age + runif(n(), min = -jitter_age, max = jitter_age) ) %>% select(id, x, y) # join those coordinates on, and, for a last hurrah, # make a factor out of dom_relat so the rows are in the proper order, # arrange everything by dom_relat and # max_hit so that the interesting ones get plotted on top. Relats <- c("Se", "PO", "Si", "GP", "A", "FC") # we will have to update this when we have more than two generations P4 <- P3 %>% left_join( xys, by = c("id_1" = "id") ) %>% rename( x_1 = x, y_1 = y ) %>% left_join( xys, by = c("id_2" = "id") ) %>% rename( x_2 = x, y_2 = y ) P5 <- P4 %>% mutate(dom_relat = factor(dom_relat, levels = Relats)) %>% arrange( dom_relat, max_hit ) # now, we are pretty much ready to start plotting this, except for figuring out the arrow # direction for the non-symmetrical relationships... # make a data frame for the background grids age_grid <- tibble( ymin = seq( from = min(c(P5$age_1, P5$age_2)) - jitter_age, to = max(c(P5$age_1, P5$age_2)) - jitter_age, by = 1 ) ) %>% mutate( ymax = ymin + jitter_age * 2 ) year_grid <- tibble( xmin = seq( from = min(c(P5$samp_year_1, P5$samp_year_2)) - jitter_year, to = max(c(P5$samp_year_1, P5$samp_year_2)) - jitter_year, by = 1 ) ) %>% mutate( xmax = xmin + jitter_age * 2 ) g <- ggplot(P5) + geom_rect( data = age_grid, aes( xmin = -Inf, xmax = Inf, ymin = ymin, ymax = ymax ), fill = "pink", alpha = 0.2 ) + geom_rect( data = year_grid, aes( xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf ), fill = "pink", alpha = 0.2 ) + geom_segment( aes( x = x_1, y = y_1, xend = x_2, yend = y_2, colour = as.factor(max_hit) ) ) + facet_grid(dom_relat ~ sex_config) + theme_bw() + scale_colour_manual( values = c(`1` = "gray", `2` = "red", `3` = "blue", `4` = "orange"), name = "Number of\nShared Ancestors" ) + xlab("Sampling Year") + ylab("Age at Time of Sampling") + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank() ) # return the plot and also the data that went into it list( input_data = list( P5 = P5, age_grid = age_grid, year_grid = year_grid ), plot = g ) }
/scratch/gouwar.j/cran-all/cranData/CKMRpop/R/uncooked_spaghetti.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ---- echo=FALSE, out.width="100%"-------------------------------------------- knitr::include_graphics("../man/figures/spip-periods.svg") ## ---- echo=FALSE, out.width="100%"-------------------------------------------- knitr::include_graphics("../man/figures/spip-periods-with-sampling.svg") ## ---- echo=FALSE, out.width="100%", fig.cap="Schematic describing the first stage of migration: migration out of a population. Each blue line shows individuals leaving the population and entering a pool of migrants."---- knitr::include_graphics("../man/figures/spip-periods-with-migration.svg")
/scratch/gouwar.j/cran-all/cranData/CKMRpop/inst/doc/about_spip.R
--- title: "About spip" resource_files: - ../man/figures/spip-periods.svg - ../man/figures/spip-periods-with-sampling.svg - ../man/figures/spip-periods-with-migration.svg author: "Eric C. Anderson" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: toc: true vignette: > %\VignetteIndexEntry{About spip} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This provides a short description of a few things that one should know about how `spip` works. ## Timing of events in a `spip` life cycle `spip` is a program that records time in discrete periods that can be thought of as years. When individuals are born at time $t$ they are considered to be of age 0 and they have a birth year of $t$. The user must input to the program the maximum possible age of an individual. Here, we will refer that maximum age as $\mathrm{MA}$. Within each year in `spip` the following events occur, in order: 1. The age of each individual is incremented at the beginning of the new year $t$. This means that newborns from year $t-1$ are turned into 1-year-olds as they enter year $t$, and so forth. 1. Next there is a chance to sample individuals before the death episode. Only individuals of ages 1 to $\mathrm{MA}$ can be sampled. These are the individuals, who, if they survive the upcoming death episode, might have the chance to contribute to the next generation. 1. Next there is an episode of death. Individuals that are $a$ years old in year $t$ survive this episode of death with a probability of $s_a$. Individuals that are $\mathrm{MA} + 1$ are all killed with probability of 1. 1. Then there is a chance to sample individuals after the episode of death. Only individuals of ages 1 to $\mathrm{MA}$ can be sampled. This is a sample from the individuals that are around and alive to contribute to the next generation. 1. Next there is an episode of reproduction which produces 0-year-olds born at time $t$. - During the reproduction episode there is an opportunity to draw a sample from the individuals that were chosen to be amongst the reproducing adults. (This is particularly useful for critters like salmon that can be sampled explicitly when they are migrating in fresh water to reproduce). - After the sampling period during reproduction, there is also the chance for individuals to die after reproduction according to the probability set by `--fem-postrep-die` and `--male-postrep-die`. With this value set to 1, for example, semelparity can be enforced. 1. After reproduction there are individuals of ages 0 to $\mathrm{MA}$ that sit around and don't do much of anything. Eventually the year gets advanced to the following one ($t+1$), and the ages of individuals get incremented, so that at the beginning of year $t+1$ individuals are of ages 1 to $\mathrm{MA}+1$. It is worth noting that even though there are some $\mathrm{MA}+1$-year-olds around at the beginning of each time period, they all die during the episode of death, and, because they cannot be sampled during the sampling episode before death, it is like they do not exist. The year in spip can thus be divided into three different periods between the demographic events/episodes: 1. The period before the episode of death. This is known as the _prekill_ period of the year, and, in the following, we will use a superscript $\mbox{}^\mathrm{pre}$ to denote census sizes during that period. 2. The period after the episode of death, but before reproduction. This is known as the _postkill_ period, and will be denoted with a superscript $\mbox{}^\mathrm{pok}$. 3. The period after reproduction, but before the year gets incremented. This is the _post-reproduction_ period and will be denoted with a superscript $\mbox{}^\mathrm{por}$. We will use $F_{t,a}^\mathrm{pre}$, $F_{t,a}^\mathrm{pok}$, and $F_{t,a}^\mathrm{por}$ to denote the number of $a$-year-old females during the prekill, postkill, and post-reproduction periods, respectively, of time $t$. The diagram below, showing these numbers in relation to one another, along with notations of their expected values should help users to understand the spip annual cycle. The numbers of males change across time periods in a similar fashion. ```{r, echo=FALSE, out.width="100%"} knitr::include_graphics("../man/figures/spip-periods.svg") ``` Annotated in the above are the three distinct periods in spip's annual cycle: the _prekill_, _postkill_ and _post-reproductive_ periods. When the output of spip is slurped up by CKMRpop, these numbers become the respective tibbles (elements of the output list of `slurp_spip()`) of: `census_prekill`, `census_postkill`, and `census_postrepro`, respectively. The expected numbers of individuals after each transition is as follows: - $F_{t,a}^\mathrm{pre} \equiv F_{t-1,a-1}^\mathrm{por}~~,~~a = 1,\ldots,\mathrm{MA}$ - $E[F_{t,a}^\mathrm{pok}] = s_a^F F_{t,a}^\mathrm{pre}~~,~~a = 1,\ldots,\mathrm{MA}$, where $s_a^F$ is the probability that an $a-1$ year old female survives to be an $a$ year old female, as given with the `--fem-surv-probs` option. - $E[F_{t,a}^\mathrm{por}] = (1 - r_a^Fd_a^F) F_{t,a}^\mathrm{pok}~~,~~a = 1,\ldots,\mathrm{MA}$, where $r_a^F$ is the probability that an $a$-year-old female reproduces (set with the `--fem-prob-repro` option) and $d_a^F$ is the probability that an $a$-year-old female will die after engaging in reproduction (even if no offspring were actually produced!), as given in the `--fem-postrep-die` option. This is an additional source of death that is useful for modeling anadromous species whose reproductive journey incurs a substantial cost. ## Sampling episodes in a `spip` annual cycle The two main sampling schemes available in spip are keyed to these different time periods within the spip annual cycle as shown by the following figure: ```{r, echo=FALSE, out.width="100%"} knitr::include_graphics("../man/figures/spip-periods-with-sampling.svg") ``` Thus, `--gtyp-ppn-fem-pre` and `--gtyp-ppn-male-pre` involve sampling from the simulated population at a different point in the year than do the `--gtyp-ppn-fem-post` and `--gtyp-ppn-male-post` options. It is also possible to only sample those individuals that are trying to reproduce in a certain year using a third sampling scheme requested with the `--gtyp-ppn-fem-dur` and `--gtyp-ppn-male-dur` options to spip. The probability that an individual would try to reproduce in a given year is age specific and is set using the `--fem-prob-repro` and `--male-prob-repro` options. It is worth noting that the `pre`, `post` and `dur`, sampling options all occur relatively independently (so long as sampling is not lethal---see the somewhat experimental `--lethal-sampling` option). spip reports the different years when an individual is sampled during the `pre`, `post`, and `dur` periods in the year. CKMRpop preserves those times in separate lists when it slurps up the spip output. For example `slurped$samples` has the list columns: `samp_years_list_pre`, `samp_years_list_post`, and `samp_years_list_dur`. For all downstream analyses, CKMRpop uses the list column `samp_years_list`, which, by default is the same as the `samp_years_list_post`. This means, at the present time, you should use the options to sample individuals after the episode of death using the the `--gtyp-ppn-fem-post` and `--gtyp-ppn-male-post` options. Note that, in most cases when exploring CKMR, the user will want to use the `--gtyp-ppn-fem-post` and `--gtyp-ppn-male-post` options, anyway, because those are samples from the adult population that are available for reproduction. If it is desired to sample all newborns at time $t$, then currently the way to do that is to sample 1-year-olds at time $t+1$ using the `--gtyp-ppn-fem-pre` and `--gtyp-ppn-male-pre` options. However, it would take some extra finagling to get those sampling years into the `samp_years_list` column referenced above for the downstream analyses. TODO ITEM: combine sampling at all times into the single `samp_years_list` column, perhaps, or make it easier for users to decide how to combine those different sampling episodes. For now, though, users should stick to using the `--gtyp-ppn-fem-post` and `--gtyp-ppn-male-post` options. ## How inter-population migration occurs in `spip` We can use the same diagrams developed above to describe how migration is implemented in `spip`. Migration in `spip` is a "two-stage" phenomenon: in the first stage, individuals leave a population with sex-, year- and age-specific out-migration rates specified with the population's options `--fem-prob-mig-out` and `--male-prob-mig-out`. They leave each population before the prekill census occurs and also before the prekill sampling occurs. Diagrammatically, it looks like this: ```{r, echo=FALSE, out.width="100%", fig.cap="Schematic describing the first stage of migration: migration out of a population. Each blue line shows individuals leaving the population and entering a pool of migrants."} knitr::include_graphics("../man/figures/spip-periods-with-migration.svg") ``` The expected numbers of individuals in the pool of migrants who have left the population is given by the time- and age-specific rates set by the user. We will denote the outmigration rate for age $a$ individuals at time $t$ from a given population by $m^\mathrm{out}_{t,a}$. It follows then that, for this given population: $$ E[F^\mathrm{out}_{t,a}] = m^\mathrm{out}_{t,a}F_{t-1,a-1},~a=1,\ldots, \mathrm{MA}. $$ In the following, we will want to refer to these outmigration rates for each population, so we may also adorn the notation, thus: $$ E[F^{\mathrm{out},i}_{t,a}] = m^{\mathrm{out},i}_{t,a}F^i_{t-1,a-1},~a=1,\ldots, \mathrm{MA}. $$ to refer to rates and sizes specifically for population $i$. After the outmigration stage, each population has a pool of migrants that are waiting to migrate into other populations. The rates by which this happens are specified with the `--fem-prob-mig-in` and `--male-prob-mig-in` options. These options set in-migration rates for different years and for different ages, effectively setting the fraction of the total number of out-migrated individuals from population $i$ of age $a$ at time $t$, $F^{\mathrm{out},i}_{t,a}$, that will migrate into the other populations. Thus, there is one number to set for each population. For example, if there are $K$ populations, we would have: $$ m^{\mathrm{in},i}_{t,a} = [m^{\mathrm{in},i}_{t,a,1},\ldots,m^{\mathrm{in},i}_{t,a,K}]~~,~~ \sum_{j=1}^K m^{\mathrm{in},i}_{t,a,j} = 1. $$ The probability of migrating back to the population from whence one came is always 0. So, even if the user sets that to some non-zero value, it will be forced to zero and the values of the remaining in-migration rates will be re-scaled so as to sum to 1. Given this set up, the expected number of individuals from the outmigrant pool from population $i$ that will arrive in population $j$, of age $a$ at time $t$ is $$ E[F^{\mathrm{in},i}_{t,a,j}] = m^{\mathrm{in},i}_{t,a,j} F^{\mathrm{out},i}_{t,a} $$ And, so we can also write that entirely in terms of current population sizes and migration rates: $$ E[F^{\mathrm{in},i}_{t,a,j}] = m^{\mathrm{in},i}_{t,a,j} m^{\mathrm{out},i}_{t,a}F^i_{t-1,a-1} $$ So, this whole system of specifying migrants is a little more complex than a system whereby the user specifies the fraction of individuals in population $j$ that originated from population $i$. But, it does provide a lot more control by the user, as well as realism, in that the number of migrants into a population depends on the size of the donor population.
/scratch/gouwar.j/cran-all/cranData/CKMRpop/inst/doc/about_spip.Rmd