code
stringlengths
1
13.8M
"Simulated_individual"
calc_commonness_error <- function(x, objective_matrix) { solution_matrix <- calculate_solution_commonness_rcpp(x$optimized_grid) MAE_c <- mean(abs(solution_matrix - objective_matrix), na.rm = TRUE) RCE <- MAE_c / mean(abs(objective_matrix), na.rm = TRUE) * 100 result <- c(MAE_c = MAE_c, RCE = RCE) return(result) }
context("SEMinR correctly estimates rho_A for the simple model\n") mobi_mm <- constructs( reflective("Image", multi_items("IMAG", 1:5)), reflective("Expectation", multi_items("CUEX", 1:3)), reflective("Value", multi_items("PERV", 1:2)), reflective("Satisfaction", multi_items("CUSA", 1:3)) ) mobi_sm <- relationships( paths(to = "Satisfaction", from = c("Image", "Expectation", "Value")) ) seminr_model <- estimate_pls(mobi, mobi_mm, mobi_sm,inner_weights = path_factorial) rho <- rho_A(seminr_model) rho_control <- as.matrix(read.csv(file = paste(test_folder,"rho1.csv", sep = ""), row.names = 1)) test_that("Seminr estimates rhoA correctly\n", { expect_equal(rho, rho_control, tolerance = 0.00001) }) context("SEMinR correctly estimates rhoA for the interaction model\n") mobi_mm <- constructs( reflective("Image", multi_items("IMAG", 1:5)), reflective("Expectation", multi_items("CUEX", 1:3)), reflective("Value", multi_items("PERV", 1:2)), reflective("Satisfaction", multi_items("CUSA", 1:3)), interaction_term(iv = "Image", moderator = "Expectation", method = orthogonal, weights = mode_A), interaction_term(iv = "Image", moderator = "Value", method = orthogonal, weights = mode_A) ) mobi_sm <- relationships( paths(to = "Satisfaction", from = c("Image", "Expectation", "Value", "Image*Expectation", "Image*Value")) ) seminr_model <- estimate_pls(mobi, mobi_mm, mobi_sm,inner_weights = path_factorial) rho <- rho_A(seminr_model) rho_control <- as.matrix(read.csv(file = paste(test_folder,"rho2.csv", sep = ""), row.names = 1)) test_that("Seminr estimates rho_A correctly\n", { expect_equal(rho, rho_control, tolerance = 0.00001) }) context("SEMinR correctly estimates PLSc path coefficients, rsquared and loadings for the simple model\n") mobi_mm <- constructs( reflective("Image", multi_items("IMAG", 1:5)), reflective("Expectation", multi_items("CUEX", 1:3)), reflective("Value", multi_items("PERV", 1:2)), reflective("Satisfaction", multi_items("CUSA", 1:3)) ) mobi_sm <- relationships( paths(to = "Satisfaction", from = c("Image", "Expectation", "Value")) ) seminr_model <- estimate_pls(mobi, mobi_mm, mobi_sm,inner_weights = path_factorial) path_coef <- seminr_model$path_coef loadings <- seminr_model$outer_loadings rSquared <- seminr_model$rSquared path_coef_control <- as.matrix(read.csv(file = paste(test_folder,"path_coef1.csv", sep = ""), row.names = 1)) loadings_control <- as.matrix(read.csv(file = paste(test_folder,"loadings1.csv", sep = ""), row.names = 1)) rSquared_control <- as.matrix(read.csv(file = paste(test_folder,"rsquaredplsc.csv", sep = ""), row.names = 1)) test_that("Seminr estimates PLSc path coefficients correctly\n", { expect_equal(path_coef, path_coef_control, tolerance = 0.00001) }) test_that("Seminr estimates PLSc loadings correctly\n", { expect_equal(loadings[,1:4], loadings_control, tolerance = 0.00001) }) test_that("Seminr estimates rsquared correctly\n", { expect_equal(rSquared[1:2,], rSquared_control[1:2,], tolerance = 0.00001) })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(bioassays) filelist <-list("L_HEPG2_P3_72HRS.csv","L_HEPG2_P3_24HRS.csv") fno<-1 result <- data.frame(stringsAsFactors= FALSE) zzz <- data.frame(stringsAsFactors= FALSE) filename<-extract_filename(filelist[fno])[1] filename nickname<-extract_filename(filelist[fno], split="_",end=".csv",remove="",sep="")[2] nickname data(rawdata96) rawdata<-rawdata96 head(rawdata) data(metafile96) metadata<-metafile96 head(metadata) rawdata<-data2plateformat(rawdata,platetype = 96) head(rawdata) OD_df<- plate2df(rawdata) head(OD_df) data<-matrix96(OD_df,"value",rm="TRUE") heatplate(data,"Plate 1", size=5) plate_info<-function(file,i){ file<-file[1] plate<- extract_filename(file,split = "_",end = ".csv", remove = " ", sep=" ")[5] if(plate == "P2"){ compound<-"CyclosporinA" concentration<-c(0,1,5,10,15,20,25,50) type<-c("S1","S2","S3","S4","S5","S6","S7","S8") dilution<-5 plate_meta<-list(compound=compound,concentration=round(concentration,2),type=type, dilution=dilution) } if(plate == "P3"){ compound<-"Taxol" concentration<-c(0,0.0125,.025,.05,0.1,1,5,10) type<-c("S1","S2","S3","S4","S5","S6","S7","S8") dilution<-5 plate_meta<-list(compound=compound,concentration=round(concentration,2),type=type, dilution=dilution) } if(plate =="p4"){ compound<-c("Cisplatin") concentration<-c(0,0.5,2,4,8,16,64,"") type<-c("S1","S2","S3","S4","S5","S6","S7","") dilution <- 5 plate_meta<-list(compound=compound,concentration=round(concentration,2),type=type, dilution=dilution) } return(plate_meta) } plate_details<-plate_info(filelist,1) plate_details metadata1<-plate_metadata(plate_details,metadata,mergeby="type") head(metadata1) data_DF<- dplyr::inner_join(OD_df,metadata1,by=c("row","col","position")) assign(paste("data",sep="_",nickname),data_DF) head(data_DF) data_DF<-reduceblank(data_DF, x_vector =c("All"),blank_vector = c("Blank"), "value") head(data_DF) assign(paste("Blkmin",sep="_",nickname),data_DF) std<- dplyr::filter(data_DF, data_DF$id=="STD") std<- aggregate(std$blankminus ~ std$concentration, FUN = mean ) colnames (std) <-c("con", "OD") head(std) fit1<-nplr::nplr(std$con,std$OD,npars=3,useLog = FALSE) x1 <- nplr::getX(fit1); y1 <- nplr::getY(fit1) x2 <- nplr::getXcurve(fit1); y2 <- nplr::getYcurve(fit1) plot(x1, y1, pch=15, cex=1, col="red", xlab="Concentration", ylab="Mean OD", main=paste("Standard Curve: ", nickname), cex.main=1) lines(x2, y2, lwd=3, col="seagreen4") params<-nplr::getPar(fit1)$params nplr::getGoodness(fit1) estimated_nplr<-estimate(data_DF,colname="blankminus",fitformula=fit1,method="nplr") head(estimated_nplr) fit2<-stats::lm(formula = con ~ OD,data = std) ggplot2::ggplot(std, ggplot2::aes(x=OD,y=con))+ ggplot2::ggtitle(paste("Std Curve:", nickname))+ ggplot2::geom_point(color="red",size=2)+ ggplot2::geom_line(data = ggplot2::fortify(fit2),ggplot2::aes(x=OD,y=.fitted), colour="seagreen4",size=1)+ ggplot2::theme_bw() conpred<-estimate(std,colname="OD",fitformula=fit2,method="linear") compare<-conpred[,c(1,3)] corAccuracy<-cor(compare)[1,2] corAccuracy summary(fit2) estimated_lr<-estimate(data_DF,colname="blankminus",fitformula=fit2,method="linear") head(estimated_lr) estimated_lr$estimated2 <- estimated_lr$estimated * estimated_lr$dilution head(estimated_lr) result<-dfsummary(estimated_lr,"estimated2",c("id","type"), c("STD","Blank"),"plate1", rm="FALSE", param=c(strict="FALSE",cutoff=40,n=12)) result pval<-pvalue(result, control="S1", sigval=0.05) head(pval) data(rawdata384) rawdata2<-rawdata384 dim(rawdata2) head(rawdata2) data(metafile384) metadata2<-metafile384 head(metadata2) rawdata2<-data2plateformat(rawdata2,platetype = 384) head(rawdata2) OD_df2 <- plate2df(rawdata2) head(OD_df2) data2<-matrix96(OD_df2,"value",rm="TRUE") heatplate(data2,"Plate 384", size=1.5) data_DF2<- dplyr::inner_join(OD_df2,metadata2,by=c("row","col","position")) head(data_DF2) data3<-matrix96(data_DF2,"cell",rm="TRUE") heatplate(data3,"Plate 384", size=2) data4<-matrix96(data_DF2,"compound",rm="TRUE") heatplate(data4,"Plate 384", size=2) data_blk<-reduceblank(data_DF2, x_vector=c("drug1","drug2","drug3","drug4"), blank_vector = c("blank1","blank2","blank3","blank4"), "value") dim(data_blk) head(data_blk) result2<-dfsummary(data_blk,"blankminus", c("cell","compound","concentration","type"), c("blank1","blank2","blank3","blank4"), nickname="384well", rm="FALSE",param=c(strict="FALSE",cutoff=40,n=12)) head (result2) dim (result2) result3<-dfsummary(data_blk,"blankminus", c("cell","compound","concentration"), c("B","drug2","huh7"), nickname="", rm="FALSE",param=c(strict="FALSE",cutoff=40,n=12)) head (result3) dim (result3) pvalue<-pvalue(result3,"C3",sigval=0.05) pvalue
recreate.pathway <- function(setup, pathway){ setup$super.pathway <- setup$pathway npath <- length(pathway) path <- list() for(i in 1:npath){ path[[i]] <- setup$super.pathway[setup$super.pathway$Gene %in% pathway[[i]][, 'Gene'], ] } setup$pathway <- path setup }
f2.ld.f1 <- function(y, time, group1, group2, subject, time.name="Time", group1.name="GroupA", group2.name="GroupB", description=TRUE, time.order=NULL, group1.order=NULL, group2.order=NULL,plot.RTE=TRUE,show.covariance=FALSE,order.warning=TRUE) { var<-y if(is.null(var)||is.null(time)||is.null(group1)||is.null(group2)||is.null(subject)) stop("At least one of the input parameters (y, time, group1, group2, or subject) is not found.") sublen<-length(subject) varlen<-length(var) timlen<-length(time) gro1len<-length(group1) gro2len<-length(group2) if((sublen!=varlen)||(sublen!=timlen)||(sublen!=gro1len)||(sublen!=gro2len)) stop("At least one of the input parameters (y, time, group1, group2, or subject) has a different length.") library(MASS) tlevel <- unique(time) slevel <- unique(subject) g1level <- unique(group1) g2level <- unique(group2) t <- length(tlevel) s <- length(slevel) a <- length(g1level) b <- length(g2level) if((t*s)!=length(var)) stop("Number of levels of subject (",s, ") times number of levels of time (",t,") is not equal to the total number of observations (",length(var),").",sep="") if(!is.null(time.order)) { tlevel <- time.order tlevel2 <- unique(time) if(length(tlevel)!=length(tlevel2)) stop("Length of the time.order vector (",length(tlevel), ") is not equal to the levels of time vector (",length(tlevel2),").",sep="") if(mean(sort(tlevel)==sort(tlevel2))!=1) stop("Elements in the time.order vector is different from the levels specified in the time vector.",sep="") } if(!is.null(group1.order)) { g1level <- group1.order g1level2 <- unique(group1) if(length(g1level)!=length(g1level2)) stop("Length of the group1.order vector (",length(g1level), ") is not equal to the levels of group1 vector (",length(g1level2),").",sep="") if(mean(sort(g1level)==sort(g1level2))!=1) stop("Elements in the group1.order vector is different from the levels specified in the group1 vector.",sep="") } if(!is.null(group2.order)) { g2level <- group2.order g2level2 <- unique(group2) if(length(g2level)!=length(g2level2)) stop("Length of the group2.order vector (",length(g2level), ") is not equal to the levels of group2 vector (",length(g2level2),").",sep="") if(mean(sort(g2level)==sort(g2level2))!=1) stop("Elements in the group2.order vector is different from the levels specified in the group2 vector.",sep="") } newgroup1<-double(length(var)) newgroup2<-double(length(var)) gvector<-double(length(var)) for(i in 1:length(var)) { gvector[i]<-b*which(g1level==group1[i])+which(g2level==group2[i])-b newgroup1[i]<-which(g1level==group1[i]) newgroup2[i]<-which(g2level==group2[i]) } sortvector<-double(length(var)) newsubject<-double(length(var)) newtime<-double(length(var)) for(i in 1:length(var)) { row<-which(subject[i]==slevel) col<-which(time[i]==tlevel) newsubject[i]<-row newtime[i]<-col sortvector[((col-1)*s+row)]<-i } subject<-newsubject[sortvector] var<-var[sortvector] time<-newtime[sortvector] group1<-newgroup1[sortvector] group2<-newgroup2[sortvector] grouptemp<-order(gvector[1:s]) groupplus<-(rep(c(0:(t-1)),e=s))*s groupsort<-(rep(grouptemp,t))+groupplus subject<-rep(c(1:s),t) var<-var[groupsort] time<-time[groupsort] group1<-group1[groupsort] group2<-group2[groupsort] origg1level<-g1level origg2level<-g2level origtlevel<-tlevel origslevel<-slevel g1level<-unique(group1) g2level<-unique(group2) tlevel<-unique(time) slevel<-unique(subject) factor1<-group1 factor2<-group2 factor1.name<-group1.name factor2.name<-group2.name time<-factor(time) FAC.1<-factor(factor1) FAC.2<-factor(factor2) facs.1 <- levels(FAC.1) facs.2 <- levels(FAC.2) tlevel <- levels(time) varL <- 1-is.na(var) T<-nlevels(time) A<-nlevels(FAC.1) B<-nlevels(FAC.2) vmat<-matrix(ncol=T, nrow=length(var)/T) Lamdamat<-matrix(ncol=T, nrow=length(var)/T) for(i in 1:T) { tempV<-var[which(time==tlevel[i])] tempL<-varL[which(time==tlevel[i])] subj<-subject[which(time==tlevel[i])] ordering<-order(subj) if(i==1) { fact1<-factor1[which(time==tlevel[i])] fact2<-factor2[which(time==tlevel[i])] FAC.1<-fact1[ordering] FAC.2<-fact2[ordering] FAC.1<-factor(FAC.1) FAC.2<-factor(FAC.2) } vmat[,i]<-tempV[ordering] Lamdamat[,i]<-tempL[ordering] } D <- vmat colnames(D) <- NULL rownames(D) <- NULL N <- length(D[,1]) RD <- rank(c(D)) Rmat <- matrix(RD, nrow=N, ncol=T) NN <- sum(varL) Rmat <- Rmat * Lamdamat RMeans <- rep(0, (A + B + T + (A*B) + (A*T) + (B*T) + (A*B*T))) Ni <- apply(Lamdamat, 2, sum) Rmat.fac <- cbind(FAC.1, FAC.2, Rmat) colnames(Rmat.fac) <- NULL Lamdamat.fac <- cbind(FAC.1, FAC.2, Lamdamat) colnames(Lamdamat.fac) <- NULL fn.fact.manip <- function(fullRmat, n, n.a, n.b, n.t, A.ni, B.ni) { res.list <- list(0) res.list.A <- list(0) res.A <- list(0) res.AB <- list(0) res.AT <- list(0) for(i in 1:n.a) { temp.Rmat <- matrix(0, nrow=A.ni[i], ncol=(n.t+1)) temp.Rmat <- fullRmat[(fullRmat[,1]==i),-1] res.A[[i]] <- c(temp.Rmat[,-1]) res.AB[[i]] <- list(0) for(j in 1:n.b) res.AB[[i]][[j]] <- temp.Rmat[(temp.Rmat[,1]==j),-1] res.AT[[i]] <- temp.Rmat[,-1] } res.list.A[[1]] <- res.A res.list.A[[2]] <- res.AB res.list.A[[3]] <- res.AT res.list.B <- list(0) res.B <- list(0) res.BT <- list(0) for(i in 1:n.b) { temp.Rmat <- matrix(0, nrow=B.ni[i], ncol=(n.t+1)) temp.Rmat <- fullRmat[(fullRmat[,2]==i),-2] res.B[[i]] <- c(temp.Rmat[,-1]) res.BT[[i]] <- temp.Rmat[,-1] } res.list.B[[1]] <- res.B res.list.B[[2]] <- res.BT res.list[[1]] <- res.list.A res.list[[2]] <- res.list.B return(res.list) } Ra.list <- fn.fact.manip(Rmat.fac, N, A, B, T, as.vector(summary(FAC.1)), as.vector(summary(FAC.2))) R1a.list <- fn.fact.manip(Lamdamat.fac, N, A, B, T, as.vector(summary(FAC.1)), as.vector(summary(FAC.2))) for(i in 1:A) RMeans[i] <- (sum(Ra.list[[1]][[1]][[i]]) / sum(R1a.list[[1]][[1]][[i]])) ric <- A for(i in 1:B) RMeans[(ric + i)] <- (sum(Ra.list[[2]][[1]][[i]]) / sum(R1a.list[[2]][[1]][[i]])) ric <- ric + B RMeans[(ric + 1) : (ric + T)] <- (apply(Rmat, 2, sum) / apply(Lamdamat, 2, sum)) ric <- ric + T ric.l <- ric + (A*B) + (A*T) + (B*T) for(i in 1:A) { for(j in 1:B) { RMeans[(ric + (i-1)*B + j)] <- (sum(Ra.list[[1]][[2]][[i]][[j]]) / sum(R1a.list[[1]][[2]][[i]][[j]])) RMeans[(ric.l + ((i-1)*B + (j-1))*T + 1) : (ric.l + ((i-1)*B + (j-1))*T + T)] <- apply( Ra.list[[1]][[2]][[i]][[j]], 2, sum) / apply(R1a.list[[1]][[2]][[i]][[j]], 2, sum) } } rm(ric.l) ric <- ric + A*B for(i in 1:A) RMeans[(ric + (i-1)*T + 1): (ric + (i-1)*T + T)] <- apply(Ra.list[[1]][[3]][[i]],2, sum) / apply( R1a.list[[1]][[3]][[i]], 2, sum) ric <- ric + A*T for(i in 1:B) RMeans[(ric + (i-1)*T + 1): (ric + (i-1)*T + T)] <- apply(Ra.list[[2]][[2]][[i]], 2, sum) / apply(R1a.list[[2]][[2]][[i]], 2, sum) RTE <- (RMeans - 0.5) / NN time.vec <- tlevel fn.nice.out <- function(A, B, T) { SOURCE <- rep(0,0) for(i in 1:A) SOURCE <- c(SOURCE, paste(factor1.name, origg1level[i],sep="")) for(i in 1:B) SOURCE <- c(SOURCE, paste(factor2.name, origg2level[i],sep="")) for(i in 1:T) SOURCE <- c(SOURCE, paste(time.name, origtlevel[i],sep="")) for(i in 1:A) for(j in 1:B) SOURCE <- c(SOURCE, paste(factor1.name,origg1level[i],":",factor2.name,origg2level[j],sep="")) for(i in 1:A) for(j in 1:T) SOURCE <- c(SOURCE, paste(factor1.name,origg1level[i],":",time.name,origtlevel[j],sep="")) for(i in 1:B) for(j in 1:T) SOURCE <- c(SOURCE, paste(factor2.name,origg2level[i],":",time.name,origtlevel[j],sep="")) for(i in 1:A) for(j in 1:B) for(k in 1:T) SOURCE <- c(SOURCE, paste(factor1.name,origg1level[i],":",factor2.name,origg2level[j],":",time.name,origtlevel[k],sep="")) return(SOURCE) } SOURCE <- fn.nice.out(A, B, T) Nobs <- rep(0, (A + B + T + (A*B) + (A*T) + (B*T) + (A*B*T))) for(i in 1:A) Nobs[i] <- sum(R1a.list[[1]][[1]][[i]]) ric <- A for(i in 1:B) Nobs[(ric + i)] <- sum(R1a.list[[2]][[1]][[i]]) ric <- ric + B Nobs[(ric + 1) : (ric + T)] <- apply(Lamdamat, 2, sum) ric <- ric + T ric.l <- ric + (A*B) + (A*T) + (B*T) for(i in 1:A) { for(j in 1:B) { Nobs[(ric + (i-1)*B + j)] <- sum(R1a.list[[1]][[2]][[i]][[j]]) Nobs[(ric.l + ((i-1)*B + (j-1))*T + 1) : (ric.l + ((i-1)*B + (j-1))*T + T)] <- apply(R1a.list[[1]][[2]][[i]][[j]], 2, sum) } } rm(ric.l) ric <- ric + A*B for(i in 1:A) Nobs[(ric + (i-1)*T + 1): (ric + (i-1)*T + T)] <- apply(R1a.list[[1]][[3]][[i]], 2, sum) ric <- ric + A*T for(i in 1:B) Nobs[(ric + (i-1)*T + 1): (ric + (i-1)*T + T)] <- apply(R1a.list[[2]][[2]][[i]], 2, sum) PRes1 <- data.frame(RankMeans=RMeans, Nobs, RTE) rd.PRes1 <- round(PRes1, Inf) rownames(rd.PRes1)<-SOURCE model.name<-"F2 LD F1 Model" if(description==TRUE) { cat(" Total number of observations: ",NN,"\n") cat(" Total number of subjects: " , N,"\n") cat(" Total number of missing observations: ",(N*T - NN),"\n") cat("\n Class level information ") cat("\n ----------------------- \n") cat(" Levels of", time.name, "(sub-plot factor time):", T, "\n") cat(" Levels of", factor1.name, "(whole-plot factor group1):", A,"\n") cat(" Levels of", factor2.name, "(whole-plot factor group2):", B,"\n") cat("\n Abbreviations ") cat("\n ----------------------- \n") cat(" RankMeans = Rank means\n") cat(" Nobs = Number of observations\n") cat(" RTE = Relative treatment effect\n") cat(" Wald.test = Wald-type test statistic\n") cat(" ANOVA.test = ANOVA-type test statistic with Box approximation\n") cat(" ANOVA.test.mod.Box = modified ANOVA-type test statistic with Box approximation\n") cat(" covariance = Covariance matrix","\n") cat(" Note: The description output above will disappear by setting description=FALSE in the input. See the help file for details.","\n\n") } if(order.warning==TRUE) { cat(" F2 LD F1 Model ") cat("\n ----------------------- \n") cat(" Check that the order of the time, group1, and group2 levels are correct.\n") cat(" Time level: " , paste(origtlevel),"\n") cat(" Group1 level: " , paste(origg1level),"\n") cat(" Group2 level: " , paste(origg2level),"\n") cat(" If the order is not correct, specify the correct order in time.order, group1.order, or group2.order.\n\n") } fn.P.mat <- function(arg1) { I <- diag(1, arg1, arg1) J <- matrix((1/arg1), arg1, arg1) return(I - J) } PA <- fn.P.mat(A) PB <- fn.P.mat(B) PT <- fn.P.mat(T) A1 <- matrix((1/A), 1, A) B1 <- matrix((1/B), 1, B) T1 <- matrix((1/T), 1, T) CA <- kronecker(PA, kronecker(B1, T1)) CB <- kronecker(A1, kronecker(PB, T1)) CT <- kronecker(A1, kronecker(B1, PT)) CAB <- kronecker(PA, kronecker(PB, T1)) CBT <- kronecker(A1, kronecker(PB, PT)) CAT <- kronecker(PA, kronecker(B1, PT)) CABT <- kronecker(PA, kronecker(PB, PT)) fn.covr<-function(N, d, NN, Rmat.list, DatRMeans, Lamdamat.list, A, B, T) { V<-matrix(0,d,d); temp.mat <- matrix(0, T, T); fn.covr.block.mats <- function(N,d,NN,Ni,Rmat,DatRMeans,Lamdamat) { V<-matrix(0,d,d); for(s in 1:d) { for(sdash in 1:d) { if(s==sdash) { temp<-(Rmat[,s]-DatRMeans[s])*(Rmat[,s]-DatRMeans[s]); V[s,sdash]<-V[s,sdash]+N*(Lamdamat[,s]%*%temp)/(NN^2*Ni[s]*(Ni[s]-1)); } if(s!=sdash) { temp<-(Rmat[,s]-DatRMeans[s])*(Rmat[,sdash]-DatRMeans[sdash]); temp1<-Lamdamat[,s]*Lamdamat[,sdash]; ks<-(Ni[s]-1)*(Ni[sdash]-1)+Lamdamat[,s]%*%Lamdamat[,sdash]-1; V[s,sdash]<-V[s,sdash]+N*(temp1%*%temp)/(NN^2*ks); } } } return(V); } for(i in 1:A) { for(j in 1:B) { temp.Rmat <- Rmat.list[[i]][[j]] temp.Lamdamat <- Lamdamat.list[[i]][[j]] Ni <- apply(temp.Lamdamat, 2, sum) temp.mat <- fn.covr.block.mats(nrow(temp.Rmat), T, NN, Ni, temp.Rmat, DatRMeans[(((i-1)* B + (j-1))*T + 1) : (((i-1)*B + (j-1))*T + T)], temp.Lamdamat) V[((((i-1)*B + (j-1))*T + 1) : (((i-1)*B + (j-1))*T + T)), ((((i-1)*B + (j-1))*T + 1) : (((i-1)*B + (j-1))*T + T))] <- (N/nrow(temp.Rmat))*temp.mat } } return(V); } ric <- (A + B + T + B*A + T*A + B*T) V <- fn.covr(N, A*B*T, NN, Ra.list[[1]][[2]], RMeans[(ric + 1) : (ric + A*B*T)], R1a.list[[1]][[2]], A, B, T) SING.COV <- FALSE if(qr(V)$rank < (A*B*T)) SING.COV <- TRUE WARN.1 <- FALSE if(T > N) WARN.1 <- TRUE pvec <- RTE[(ric + 1) : (ric + A*B*T)] if((T > 1) && (A > 1) && (B > 1)) { WA <- N*t(CA%*%pvec)%*%ginv(CA%*%V%*%t(CA))%*%(CA%*%pvec) WB <- N*t(CB%*%pvec)%*%ginv(CB%*%V%*%t(CB))%*%(CB%*%pvec) WT <- N*t(CT%*%pvec)%*%ginv(CT%*%V%*%t(CT))%*%(CT%*%pvec) WAB <- N*t(CAB%*%pvec)%*%ginv(CAB%*%V%*%t(CAB))%*%(CAB%*%pvec) WAT <- N*t(CAT%*%pvec)%*%ginv(CAT%*%V%*%t(CAT))%*%(CAT%*%pvec) WBT <- N*t(CBT%*%pvec)%*%ginv(CBT%*%V%*%t(CBT))%*%(CBT%*%pvec) WABT <- N*t(CABT%*%pvec)%*%ginv(CABT%*%V%*%t(CABT))%*%(CABT%*%pvec) dfWA <- qr(CA)$rank dfWB <- qr(CB)$rank dfWT <- qr(CT)$rank dfWAB <- qr(CAB)$rank dfWAT <- qr(CAT)$rank dfWBT <- qr(CBT)$rank dfWABT <- qr(CABT)$rank if(!is.na(WA) && WA > 0) pWA <- pchisq(WA, dfWA, lower.tail=FALSE) else pWA <- NA if(!is.na(WB) && WB > 0) pWB <- pchisq(WB, dfWB, lower.tail=FALSE) else pWB <- NA if(!is.na(WT) && WT > 0) pWT <- pchisq(WT, dfWT, lower.tail=FALSE) else pWT <- NA if(!is.na(WAB) && WAB > 0) pWAB <- pchisq(WAB, dfWAB, lower.tail=FALSE) else pWAB <- NA if(!is.na(WBT) && WBT > 0) pWBT <- pchisq(WBT, dfWBT, lower.tail=FALSE) else pWBT <- NA if(!is.na(WAT) && WAT > 0) pWAT <- pchisq(WAT, dfWAT, lower.tail=FALSE) else pWAT <- NA if(!is.na(WABT) && WABT > 0) pWABT <- pchisq(WABT, dfWABT, lower.tail=FALSE) else pWABT <- NA W <- rbind(WA, WB, WT, WAB, WAT, WBT, WABT) pW <- rbind(pWA, pWB, pWT, pWAB, pWAT, pWBT, pWABT) dfW <- rbind(dfWA, dfWB, dfWT, dfWAB, dfWAT, dfWBT, dfWABT) WaldType <- data.frame(W, dfW, pW) rd.WaldType <- round(WaldType, Inf) Wdesc <- rbind(factor1.name, factor2.name, time.name, paste(factor1.name, ":", factor2.name, sep=""), paste(factor1.name, ":", time.name, sep=""), paste(factor2.name, ":", time.name, sep=""), paste(factor1.name, ":", factor2.name, ":", time.name, sep="")) colnames(rd.WaldType) <- c("Statistic", "df", "p-value") rownames(rd.WaldType) <- Wdesc fn.tr <- function(mat) { return(sum(diag(mat))) } RTE.B <- RTE[(A + B + T + B*A + T*A + B*T + 1) : (A + B + T + B*A + T*A + B*T + A*B*T)] BtA <- t(CA)%*%(ginv(CA%*%t(CA)))%*%CA BtB <- t(CB)%*%(ginv(CB%*%t(CB)))%*%CB BtT <- t(CT)%*%(ginv(CT%*%t(CT)))%*%CT BtAB <- t(CAB)%*%(ginv(CAB%*%t(CAB)))%*%CAB BtAT <- t(CAT)%*%(ginv(CAT%*%t(CAT)))%*%CAT BtBT <- t(CBT)%*%(ginv(CBT%*%t(CBT)))%*%CBT BtABT <- t(CABT)%*%(ginv(CABT%*%t(CABT)))%*%CABT TVA <- BtA%*%V BA <- (N/fn.tr(TVA)) * ((t(RTE.B)) %*% BtA %*% (RTE.B)) BAf <- ((fn.tr(BtA%*%V))^2)/(fn.tr(BtA%*%V%*%BtA%*%V)) if((!is.na(BA))&&(!is.na(BAf))&&(BA > 0)&&(BAf > 0)) BAp <- pf(BA, BAf, Inf, lower.tail=FALSE) else BAp <- NA TVB <- BtB%*%V BB <- (N/fn.tr(TVB)) * ((t(RTE.B)) %*% BtB %*% (RTE.B)) BBf <- ((fn.tr(BtB%*%V))^2)/(fn.tr(BtB%*%V%*%BtB%*%V)) if((!is.na(BB))&&(!is.na(BBf))&&(BB > 0)&&(BBf > 0)) BBp <- pf(BB, BBf, Inf, lower.tail=FALSE) else BBp <- NA TVT <- BtT%*%V BT <- (N/fn.tr(TVT)) * ((t(RTE.B)) %*% BtT %*% (RTE.B)) BTf <- ((fn.tr(BtT%*%V))^2)/(fn.tr(BtT%*%V%*%BtT%*%V)) if((!is.na(BT))&&(!is.na(BTf))&&(BT > 0)&&(BTf > 0)) BTp <- pf(BT, BTf, Inf, lower.tail=FALSE) else BTp <- NA TVAB <- BtAB%*%V BAB <- (N/fn.tr(TVAB)) * ((t(RTE.B)) %*% BtAB %*% (RTE.B)) BABf <- ((fn.tr(BtAB%*%V))^2)/(fn.tr(BtAB%*%V%*%BtAB%*%V)) if((!is.na(BAB))&&(!is.na(BABf))&&(BAB > 0)&&(BABf > 0)) BABp <- pf(BAB, BABf, Inf, lower.tail=FALSE) else BABp <- NA TVAT <- BtAT%*%V BAT <- (N/fn.tr(TVAT)) * ((t(RTE.B)) %*% BtAT %*% (RTE.B)) BATf <- ((fn.tr(BtAT%*%V))^2)/(fn.tr(BtAT%*%V%*%BtAT%*%V)) if((!is.na(BAT))&&(!is.na(BATf))&&(BAT > 0)&&(BATf > 0)) BATp <- pf(BAT, BATf, Inf, lower.tail=FALSE) else BATp <- NA TVBT <- BtBT%*%V BBT <- (N/fn.tr(TVBT)) * ((t(RTE.B)) %*% BtBT %*% (RTE.B)) BBTf <- ((fn.tr(BtBT%*%V))^2)/(fn.tr(BtBT%*%V%*%BtBT%*%V)) if((!is.na(BBT))&&(!is.na(BBTf))&&(BBT > 0)&&(BBTf > 0)) BBTp <- pf(BBT, BBTf, Inf, lower.tail=FALSE) else BBTp <- NA TVABT <- BtABT%*%V BABT <- (N/fn.tr(TVABT)) * ((t(RTE.B)) %*% BtABT %*% (RTE.B)) BABTf <- ((fn.tr(BtABT%*%V))^2)/(fn.tr(BtABT%*%V%*%BtABT%*%V)) if((!is.na(BABT))&&(!is.na(BABTf))&&(BABT > 0)&&(BABTf > 0)) BABTp <- pf(BABT, BABTf, Inf, lower.tail=FALSE) else BABTp <- NA QB <- rbind(BA, BB, BT, BAB, BAT, BBT, BABT) pB <- rbind(BAp, BBp, BTp, BABp, BATp, BBTp, BABTp) dfB <- rbind(BAf, BBf, BTf, BABf, BATf, BBTf, BABTf) BoxType <- data.frame(QB, dfB, pB) rd.BoxType <- round(BoxType, Inf) Bdesc <- rbind(factor1.name, factor2.name, time.name, paste(factor1.name, ":", factor2.name, sep=""), paste(factor1.name,":", time.name, sep=""), paste(factor2.name, ":", time.name, sep=""), paste(factor1.name, ":", factor2.name, ":", time.name, sep="")) colnames(rd.BoxType) <- c("Statistic", "df", "p-value") rownames(rd.BoxType) <- Bdesc b2.ni <- as.vector(summary(FAC.1 : FAC.2)) b2.lamda <- solve((diag(b2.ni) - diag(1, length(b2.ni), length(b2.ni)))) b2.mat <- kronecker(diag(1, A, A), kronecker(diag(1, B, B), matrix((1/T), 1, T))) b2.sd <- b2.mat %*% V %*% t(b2.mat) b2.dA <- diag(kronecker(PA, matrix((1/B), B, B))) b2.dA <- diag(b2.dA, length(b2.dA), length(b2.dA)) b2.dB <- diag(kronecker(matrix((1/A), A, A), PB)) b2.dB <- diag(b2.dB, length(b2.dB), length(b2.dB)) b2.dAB <- diag(kronecker(PA, PB)) b2.dAB <- diag(b2.dAB, length(b2.dAB), length(b2.dAB)) b2.df1 <- (fn.tr(b2.dA %*% b2.sd) %*% fn.tr(b2.dA %*% b2.sd)) / fn.tr(b2.dA %*% b2.dA %*% b2.sd %*% b2.sd %*% b2.lamda) b2.df2 <- (fn.tr(b2.dB %*% b2.sd) %*% fn.tr(b2.dB %*% b2.sd)) / fn.tr(b2.dB %*% b2.dB %*% b2.sd %*% b2.sd %*% b2.lamda) b2.df3 <- (fn.tr(b2.dAB %*% b2.sd) %*% fn.tr(b2.dAB %*% b2.sd)) / fn.tr(b2.dAB %*% b2.dAB %*% b2.sd %*% b2.sd %*% b2.lamda) if((!is.na(BA))&&(!is.na(BAf))&&(BA > 0)&&(BAf > 0)&&(b2.df1 > 0)) B2.Ap <- pf(BA, BAf, b2.df1, lower.tail=FALSE) else BAp <- NA if((!is.na(BB))&&(!is.na(BBf))&&(BB > 0)&&(BBf > 0)&&(b2.df2 > 0)) B2.Bp <- pf(BB, BBf, b2.df2, lower.tail=FALSE) else BBp <- NA if((!is.na(BAB))&&(!is.na(BABf))&&(BAB > 0)&&(BABf > 0)&&(b2.df3 > 0)) B2.ABp <- pf(BAB, BABf, b2.df3, lower.tail=FALSE) else BABp <- NA B2 <- rbind(BA, BB, BAB) pB <- rbind(B2.Ap, B2.Bp, B2.ABp) df1.B2 <- rbind(BAf, BBf, BABf) df2.B2 <- rbind(b2.df1, b2.df2, b2.df3) BoxType2 <- data.frame(B2, df1.B2, df2.B2, pB) rd.BoxType2 <- round(BoxType2, Inf) B2.desc <- rbind(factor1.name, factor2.name, paste(factor1.name, ":", factor2.name, sep="")) colnames(rd.BoxType2) <- c("Statistic", "df1", "df2", "p-value") rownames(rd.BoxType2) <- B2.desc } if(WARN.1 || SING.COV) { cat("\n Warning(s):\n") if(WARN.1) cat(" There are less subjects than sub-plot factor levels.\n") if(SING.COV) cat(" The covariance matrix is singular. \n\n") } if (plot.RTE == TRUE) { id.rte <- A + T + B + A * T + B * T + A * B plot.rte <- rd.PRes1[, 3][(id.rte + 1):(id.rte + A * B * T)] frank.group1 <- rep(0, 0) frank.group2 <- rep(0, 0) frank.time <- rep(0, 0) for (i in 1:A) { for (j in 1:B) { for (k in 1:T) { frank.group1 <- c(frank.group1, paste(origg1level[i])) frank.group2 <- c(frank.group2, paste(origg2level[j])) frank.time <- c(frank.time, paste(origtlevel[k])) } } } Frank <- data.frame(Group1 = frank.group1, Time = frank.time, Group2 = frank.group2, RTE = plot.rte) plot.samples <- split(Frank, Frank$Group1) lev.G1 <- levels(factor(plot.samples[[1]]$Group1)) lev.G2 <- levels(factor(plot.samples[[1]]$Group2)) lev.T <- levels(factor(Frank$Time)) par(mfrow = c(1, A)) for (hh in 1:A) { id.g <- which(names(plot.samples) == origg1level[hh]) plot(1:T, plot.samples[[id.g]]$RTE[1:T], pch = 10, type = "b", ylim = c(0, 1.1), xaxt = "n", xlab = "", ylab = "", cex.lab = 1.5, xlim = c(0, T + 1), lwd = 3) title(main = paste(group1.name, origg1level[hh]), xlab = paste(time.name)) for (s in 1:B) { points(1:T, plot.samples[[id.g]]$RTE[plot.samples[[hh]]$Group2 == lev.G2[s]], col = s, type = "b", lwd = 3) } axis(1, at = 1:T, labels = origtlevel) legend("top", col = c(1:B), paste(group2.name, lev.G2), pch = c(rep(10, B)), lwd = c(rep(3, B))) } } if (show.covariance == FALSE) { V <- NULL } out.f2.ld.f1 <- list(RTE=rd.PRes1,Wald.test=rd.WaldType, ANOVA.test=rd.BoxType, ANOVA.test.mod.Box=rd.BoxType2, covariance=V, model.name=model.name) return(out.f2.ld.f1) }
create_table_pages_pdf <- function(rs, cntnt, lpg_rows) { ts <- cntnt$object content_blank_row <- cntnt$blank_row pgby_var <- NA if (!is.null(rs$page_by)) pgby_var <- rs$page_by$var else if (!is.null(ts$page_by)) pgby_var <- ts$page_by$var if (all(ts$show_cols == "none") & length(ts$col_defs) == 0) { stop("ERROR: At least one column must be defined if show_cols = \"none\".") } font_name <- rs$font dat <- as.data.frame(ts$data, stringsAsFactors = FALSE) dat$..blank <- "" dat$..row <- 1 dat$..page_by <- NA if (is.null(ts$page_var)) { if (is.na(pgby_var)) dat$..page <- NA else dat$..page <- dat[[pgby_var]] } else { if (any(class(dat[[ts$page_var]]) == "factor")) dat$..page <- as.character(dat[[ts$page_var]]) else dat$..page <- dat[[ts$page_var]] } if (!is.na(pgby_var)) { if (any(class(dat[[pgby_var]]) == "factor")) { dat[[pgby_var]] <- as.character(dat[[pgby_var]] ) dat$..page_by <- dat[[pgby_var]] if (any(class(dat$..page) == "factor")) dat$..page <- as.character(dat[[pgby_var]]) } else { dat$..page_by <- dat[[pgby_var]] } if (is.unsorted(dat[[pgby_var]], strictly = FALSE)) message("Page by variable not sorted.") } keys <- get_table_cols(ts) dat <- get_data_subset(dat, keys, rs$preview) ts$col_defs <- set_column_defaults(ts, keys) labels <- get_labels(dat, ts) aligns <- get_aligns(dat, ts) label_aligns <- get_label_aligns(ts, aligns) cdat <- clear_formats(dat) formats(cdat) <- get_col_formats(dat, ts) fdat <- fdata(cdat) fdat <- prep_data(fdat, ts, rs$char_width, rs$missing) keys <- names(fdat) if ("width" %in% ts$use_attributes) widths(fdat) <- widths(dat) widths_uom <- get_col_widths_variable(fdat, ts, labels, rs$font, rs$font_size, rs$units, rs$gutter_width) sp <- split_cells_variable(fdat, widths_uom, rs$font, rs$font_size, rs$units, rs$output_type) fdat <- sp$data wdat <- sp$widths wraps <- get_page_wraps(rs$line_size, ts, widths_uom, 0) tmp_pi <- list(keys = keys, col_width = widths_uom, label = labels, label_align = label_aligns, table_align = cntnt$align) content_offset <- get_content_offsets_pdf(rs, ts, tmp_pi, content_blank_row) splits <- get_splits_text(fdat, widths_uom, rs$body_line_count, lpg_rows, content_offset$lines, ts, TRUE) if (!is.null(rs$preview)) { if (rs$preview < length(splits)) splits <- splits[seq(1, rs$preview)] } tot_count <- length(splits) * length(wraps) counter <- 0 wrap_flag <- FALSE blnk_ind <- "none" spstart <- 1 spend <- 1 fp_offset <- lpg_rows pg_lst <- list() for(s in splits) { spend <- spstart + nrow(s) - 1 spwidths <- wdat[seq(spstart, spend)] for(pg in wraps) { counter <- counter + 1 if (counter < tot_count) wrap_flag <- TRUE else wrap_flag <- FALSE blnk_ind <- get_blank_indicator(counter, tot_count, content_blank_row, rs$body_line_count, content_offset$lines, nrow(s)) if (!is.na(pgby_var)) pgby <- trimws(s[1, "..page_by"]) else pgby <- NULL pi <- page_info(data= s[, pg], keys = pg, label=labels[pg], col_width = widths_uom[pg], col_align = aligns[pg], font_name = font_name, label_align = label_aligns[pg], pgby, cntnt$align) pg_lst[[length(pg_lst) + 1]] <- create_table_pdf(rs, ts, pi, blnk_ind, wrap_flag, fp_offset, spwidths) fp_offset <- 0 } spstart <- spend + 1 } ret <- list(widths = widths_uom, page_list = pg_lst) return(ret) } create_table_pdf <- function(rs, ts, pi, content_blank_row, wrap_flag, lpg_rows, spwidths) { rh <- rs$row_height ys <- lpg_rows * rh conv <- rs$point_conversion bf <- FALSE ls <- rs$content_size[["width"]] ys <- sum(ys, rs$page_template$page_header$points, rs$page_template$titles$points, rs$page_template$title_hdr$points) if (!is.null(pi$col_width)) ls <- sum(pi$col_width, na.rm = TRUE) if (content_blank_row %in% c("above", "both")) ys <- ys + rh if (!is.null(ts$title_hdr)) ttls <- get_title_header_pdf(ts$title_hdr, ls, rs, pi$table_align, ystart = ys) else ttls <- get_titles_pdf(ts$titles, ls, rs, pi$table_align, ystart = ys) ys <- ys + ttls$points if (ttls$lines > 0) bf <- ttls$border_flag if (!is.null(rs$page_by)) { pgby <- get_page_by_pdf(rs$page_by, rs$content_size[["width"]], pi$page_by, rs, pi$table_align, ystart = ys, brdr_flag = bf) } else if(!is.null(ts$page_by)) pgby <- get_page_by_pdf(ts$page_by, ls, pi$page_by, rs, pi$table_align, ystart = ys, brdr_flag = bf) else pgby <- c() if (length(pgby) > 0) { ys <- ys + pgby$points bf <- pgby$border_flag } shdrs <- list(lines = 0, points = 0) hdrs <- list(lines = 0, points = 0) if (ts$headerless == FALSE) { shdrs <- get_spanning_header_pdf(rs, ts, pi, ystart = ys, brdr_flag = bf) ys <- ys + shdrs$points hs <- FALSE if (shdrs$lines > 0) { bf <- shdrs$border_flag hs <- TRUE } hdrs <- get_table_header_pdf(rs, ts, pi$col_width, pi$label, pi$label_align, pi$table_align, ystart = ys, brdr_flag = bf, has_spans = hs) ys <- ys + hdrs$points } bdy <- get_table_body_pdf(rs, pi$data, pi$col_width, pi$col_align, pi$table_align, ts$borders, ystart = ys, spwidths, frb = ts$first_row_blank) ys <- ys + bdy$points if (bdy$lines > 0) bf <- bdy$border_flag ftnts <- get_page_footnotes_pdf(rs, ts, ls, lpg_rows, ys, wrap_flag, content_blank_row, pi$table_align, brdr_flag = bf) rc <- sum(ttls$lines, pgby$lines, shdrs$lines, hdrs$lines, bdy$lines, ftnts$lines) ret <- list(pdf = c(ttls$pdf, pgby$pdf, shdrs$pdf, hdrs$pdf, bdy$pdf, ftnts$pdf), lines = rc, points = rc * rh) return(ret) } get_page_footnotes_pdf <- function(rs, spec, spec_width, lpg_rows, ystart, wrap_flag, content_blank_row, talgn, brdr_flag = FALSE) { ftnts <- list(lines = 0, twips = 0, border_flag = FALSE) vflag <- "none" fl <- rs$page_template$page_footer$lines if (!is.null(spec$footnotes)) { if (!is.null(spec$footnotes[[length(spec$footnotes)]])) { if (spec$footnotes[[length(spec$footnotes)]]$valign == "bottom") { vflag <- "bottom" ftnts <- get_footnotes_pdf(spec$footnotes, spec_width, rs, talgn, footer_lines = fl) } else { vflag <- "top" ftnts <- get_footnotes_pdf(spec$footnotes, spec_width, rs, talgn, ystart = ystart, brdr_flag = brdr_flag) } } } else { if (!is.null(rs$footnotes[[1]])) { if (!is.null(rs$footnotes[[1]]$valign)) { if (rs$footnotes[[1]]$valign == "top") { vflag <- "top" ftnts <- get_footnotes_pdf(rs$footnotes, spec_width, rs, talgn, ystart = ystart, brdr_flag = brdr_flag) } else { if (wrap_flag) vflag <- "bottom" } } } } blen <- 0 if (content_blank_row %in% c("below", "both")) { blen <- 1 } tlns <- ftnts$lines + blen ret <- list(pdf = ftnts$pdf, lines = tlns, points = tlns * rs$line_height, border_flag = ftnts$border_flag) return(ret) } get_content_offsets_pdf <- function(rs, ts, pi, content_blank_row) { ret <- c(upper = 0, lower = 0, blank_upper = 0, blank_lower = 0) cnt <- c(upper = 0, lower = 0, blank_upper = 0, blank_lower = 0) wdth <- rs$content_size[["width"]] if (!is.null(pi$col_width)) wdth <- sum(pi$col_width) shdrs <- list(lines = 0, points = 0) hdrs <- list(lines = 0, points = 0) if (ts$headerless == FALSE) { shdrs <- get_spanning_header_pdf(rs, ts, pi) hdrs <- get_table_header_pdf(rs, ts, pi$col_width, pi$label, pi$label_align, pi$table_align) } if (is.null(ts$title_hdr)) ttls <- get_titles_pdf(ts$titles, wdth, rs) else ttls <- get_title_header_pdf(ts$title_hdr, wdth, rs) pgb <- list(lines = 0, points = 0) if (!is.null(ts$page_by)) pgb <- get_page_by_pdf(ts$page_by, wdth, NULL, rs, pi$table_align) else if (!is.null(rs$page_by)) pgb <- get_page_by_pdf(rs$page_by, wdth, NULL, rs, pi$table_align) ret[["upper"]] <- shdrs$points + hdrs$points + ttls$points + pgb$points cnt[["upper"]] <- shdrs$lines + hdrs$lines + ttls$lines + pgb$lines if (content_blank_row %in% c("above", "both")) { ret[["blank_upper"]] <- rs$line_height cnt[["blank_upper"]] <- 1 } ftnts <- get_footnotes_pdf(ts$footnotes, wdth, rs) rftnts <- get_footnotes_pdf(rs$footnotes, wdth, rs) if (has_top_footnotes(rs)) { ret[["lower"]] <- ftnts$points + rftnts$points cnt[["lower"]] <- ftnts$lines + rftnts$lines } else { ret[["lower"]] <- ftnts$points cnt[["lower"]] <- ftnts$lines } brdrs <- strip_borders(ts$borders ) if (any(brdrs %in% c("all", "inside"))) { epnts <- floor(rs$body_line_count - cnt[["lower"]] - cnt[["upper"]]) * rs$border_height ret[["lower"]] <- ret[["lower"]] + epnts - rs$line_height cnt[["lower"]] <- cnt[["lower"]] + floor(epnts / rs$row_height) - 1 } if (content_blank_row %in% c("both", "below")) { ret[["blank_lower"]] <- rs$line_height cnt[["blank_lower"]] <- 1 } res <- list(lines = cnt, points = ret) return(res) } get_table_header_pdf <- function(rs, ts, widths, lbls, halgns, talgn, ystart = 0, brdr_flag = FALSE, has_spans = FALSE) { ret <- c() cnt <- 0 rh <- rs$row_height bs <- rs$border_spacing bh <- rs$border_height tbl <- ts$data conv <- rs$point_conversion nms <- names(lbls)[is.controlv(names(lbls)) == FALSE] unts <- rs$units wdths <- widths[nms] brdrs <- strip_borders(ts$borders) pnts <- 0 width <- sum(wdths, na.rm = TRUE) if (talgn == "right") { tlb <- rs$content_size[["width"]] - width trb <- rs$content_size[["width"]] } else if (talgn %in% c("center", "centre")) { tlb <- (rs$content_size[["width"]] - width) / 2 trb <- width + tlb } else { tlb <- 0 trb <- width } cnt <- 1 pdf(NULL) par(family = get_font_family(rs$font), ps = rs$font_size) tmplst <- list() mxlns <- 0 for(k in seq_along(nms)) { tmplst[[k]] <- split_string_text(lbls[k], wdths[k], rs$units) if (tmplst[[k]]$lines > mxlns) mxlns <- tmplst[[k]]$lines pnts <- mxlns * rh } if (any(brdrs %in% c("all", "outside", "top"))) { if (!brdr_flag & !has_spans) { tbs <- ystart + bs - rh pnts <- pnts + bs + 1 } else { tbs <- ystart - rh + 1 pnts <- pnts + 3 } } else { tbs <- ystart - rh + 1 pnts <- pnts + bh } for(k in seq_along(nms)) { tmp <- tmplst[[k]] yline <- ystart + (rh * (mxlns - tmp$lines)) if (any(brdrs %in% c("all", "outside", "top")) & !brdr_flag & !has_spans) { yline <- yline + bh } if (k == 1) { lb <- tlb rb <- lb + wdths[k] } else { lb <- rb rb <- lb + wdths[k] } for (ln in seq_len(tmp$lines)) { ret[[length(ret) + 1]] <- page_text(tmp$text[ln], rs$font_size, bold = FALSE, xpos = get_points(lb, rb, tmp$widths[ln], units = unts, align = halgns[k]), ypos = yline) yline <- yline + rh } if (any(brdrs %in% c("all", "inside"))) { ret[[length(ret) + 1]] <- page_vline(rb * conv, tbs, (rh * mxlns) + bs) } xtr <- tmp$lines if (xtr > cnt) cnt <- xtr } dev.off() if (ts$first_row_blank == TRUE) { cnt <- cnt + 1 pnts <- pnts + rh } if ((any(brdrs == "all")) | (any(brdrs %in% c("outside", "top")) & !has_spans)) { ret[[length(ret) + 1]] <- page_hline(tlb * conv, tbs, (trb - tlb) * conv) } if (any(brdrs %in% c("all", "outside", "left"))) { ret[[length(ret) + 1]] <- page_vline(tlb * conv, tbs, (rh * cnt) + bs) } if (any(brdrs %in% c("all", "outside", "right"))) { ret[[length(ret) + 1]] <- page_vline(trb * conv, tbs, (rh * cnt) + bs) } yline <- tbs + (rh * mxlns) + bs if (!any(brdrs %in% c("all", "outside", "top")) & brdr_flag) { } if (ts$first_row_blank == TRUE) { if (any(brdrs %in% c("all", "inside")) ) { ret[[length(ret) + 1]] <- page_hline(tlb * conv, yline + rh, (trb - tlb) * conv) } } ret[[length(ret) + 1]] <- page_hline(tlb * conv, yline, (trb - tlb) * conv) res <- list(pdf = ret, lines = pnts / rh, points = pnts ) return(res) } get_spanning_header_pdf <- function(rs, ts, pi, ystart = 0, brdr_flag = FALSE) { spns <- ts$col_spans cols <- pi$keys cols <- cols[!is.controlv(cols)] w <- pi$col_width w <- w[cols] gutter <- 0 gap <- 3 cnt <- c() rh <- rs$row_height bs <- rs$border_spacing bh <- rs$border_height border_flag <- FALSE wlvl <- get_spanning_info(rs, ts, pi, w, gutter) lvls <- sort(seq_along(wlvl), decreasing = TRUE) conv <- rs$point_conversion talgn <- pi$table_align brdrs <- strip_borders(ts$borders) rh <- rs$row_height if (any(brdrs %in% c("all", "inside"))) rh <- rh + bh width <- sum(w) if (talgn == "right") { tlb <- rs$content_size[["width"]] - width trb <- rs$content_size[["width"]] } else if (talgn %in% c("center", "centre")) { tlb <- (rs$content_size[["width"]] - width) / 2 trb <- width + tlb } else { tlb <- 0 trb <- width } ret <- list() lline <- ystart if (brdr_flag) { lline <- ystart + bs } pdf(NULL) par(family = get_font_family(rs$font), ps = rs$font_size) ln <- c() for (l in lvls) { s <- wlvl[[l]] widths <- s$width names(widths) <- s$name algns <- s$align names(algns) <- s$name lbls <- s$label names(lbls) <- s$name cs <- s$col_span r <- "" cnt[length(cnt) + 1] <- 1 mxyl <- 0 mxlns <- 0 lnadj <- 0 tmps <- list() for (k in seq_along(lbls)) { tmps[[k]] <- split_string_text(lbls[k], widths[k], rs$units) if (tmps[[k]]$lines > mxlns) mxlns <- tmps[[k]]$lines } for(k in seq_along(lbls)) { yline <- lline if (k == 1) { lb <- tlb rb <- lb + widths[k] } else { lb <- rb rb <- lb + widths[k] } if (lbls[k] != "") { tmp <- tmps[[k]] for (ln in seq_len(tmp$lines)) { if (ln == 1) yline <- yline + ((mxlns - tmp$lines) * rh) adj <- 0 if (any(brdrs %in% c("all", "inside"))) adj <- 4 ret[[length(ret) + 1]] <- page_text(tmp$text[ln], rs$font_size, bold = FALSE, xpos = get_points(lb, rb, tmp$widths[ln], units = rs$units, align = algns[k]), ypos = yline - adj) yline <- yline + rh if (yline > mxyl) mxyl <- yline } if (any(brdrs %in% c("all", "inside"))) { ret[[length(ret) + 1]] <- page_vline(lb * conv, lline - rh, (mxlns * rh) + .5) ret[[length(ret) + 1]] <- page_vline(rb * conv, lline - rh, (mxlns * rh) + .5) } else { if (s$span[k] > 0 & s$underline[k]) { lnadj <- .5 yline <- mxyl + lnadj - (rh * .75) + 1 ret[[length(ret) + 1]] <- page_hline((lb * conv) + gap, yline, ((rb - lb) * conv) - (gap * 2)) } } xtr <- tmp$lines + lnadj if (xtr > cnt[length(cnt)]) cnt[length(cnt)] <- xtr } } if (any(brdrs %in% c("all", "inside"))) { ret[[length(ret) + 1]] <- page_hline(tlb * conv, lline - rh, (trb - tlb) * conv) } lline <- mxyl + (rh * lnadj) } dev.off() cnts <- sum(cnt) if (length(lvls) > 0) { ypos <- ystart - rh + bs if (any(brdrs %in% c("all", "outside", "top"))) { ret[[length(ret) + 1]] <- page_hline(tlb * conv, ypos, (trb - tlb) * conv) } if (any(brdrs %in% c("all", "outside", "left"))) { ret[[length(ret) + 1]] <- page_vline(tlb * conv, ypos, (cnts * rh)) } if (any(brdrs %in% c("all", "outside", "right"))) { ret[[length(ret) + 1]] <- page_vline(trb * conv, ypos, (cnts * rh)) } } res <- list(pdf = ret, lines = cnts, points = (cnts * rh), border_flag = border_flag) return(res) } get_table_body_pdf <- function(rs, tbl, widths, algns, talgn, tbrdrs, ystart = 0, spwidths = list(), brdr_flag = FALSE, frb = FALSE) { border_flag <- FALSE if ("..blank" %in% names(tbl)) flgs <- tbl$..blank else flgs <- NA rws <- c() cnt <- 0 nms <- names(widths) nms <- nms[!is.na(nms)] nms <- nms[!is.controlv(nms)] wdths <- widths[nms] if (!"..blank" %in% names(tbl)) blnks <- rep("", nrow(tbl)) else blnks <- tbl$..blank if (length(nms) == 1) { t <- as.data.frame(tbl[[nms]]) names(t) <- nms } else t <- tbl[ , nms] conv <- rs$point_conversion unts <- rs$units bs <- rs$border_spacing bh <- rs$border_height cp <- rs$cell_padding brdrs <- strip_borders(tbrdrs) if (all(tbrdrs == "body")) brdrs <- c("top", "bottom", "left", "right") if (any(brdrs %in% c("all", "inside"))) rh <- rs$row_height + bh else rh <- rs$row_height width <- sum(wdths, na.rm = TRUE) if (talgn == "right") { tlb <- rs$content_size[["width"]] - width trb <- rs$content_size[["width"]] } else if (talgn %in% c("center", "centre")) { tlb <- (rs$content_size[["width"]] - width) / 2 trb <- width + tlb } else { tlb <- 0 trb <- width } rline <- ystart + 1 ret <- c() fs <- rs$font_size pdf(NULL) par(family = get_font_family(rs$font), ps = fs) for(i in seq_len(nrow(t))) { yline <- rline mxrw <- yline cnt <- cnt + 1 for(j in nms) { if (class(tbl[i, j]) != "character") vl <- as.character(tbl[i, j]) else vl <- tbl[i, j] tmp <- strsplit(vl, "\n", fixed = TRUE)[[1]] if (j == nms[1]) { lb <- tlb rb <- lb + wdths[j] } else { lb <- rb rb <- lb + wdths[j] } if (length(tmp) == 0) { yline <- yline + rh } else if (length(trimws(tmp)) == 0) { yline <- yline + rh } else { for (ln in seq_len(length(tmp))) { ret[[length(ret) + 1]] <- page_text(tmp[ln], fs, bold = FALSE, xpos = get_points(lb, rb, spwidths[[i]][[j]][ln], units = unts, align = algns[j]), ypos = yline) yline <- yline + rh } } if (yline > mxrw) mxrw <- yline yline <- rline } for(j in nms) { if (any(brdrs %in% c("all", "inside")) & j != nms[length(nms)] & !blnks[i] %in% c("B", "L")) { if (j == nms[1]) { lb <- tlb rb <- lb + wdths[j] } else { lb <- rb rb <- lb + wdths[j] } if (i == 1) { if (is.null(frb)) { ret[[length(ret) + 1]] <- page_vline(rb * conv, (rline + bs) - rh - 1, mxrw - rline + 1) } else if (frb == FALSE) { ret[[length(ret) + 1]] <- page_vline(rb * conv, (rline + bs) - rh - 1, mxrw - rline + 1) } else { ret[[length(ret) + 1]] <- page_vline(rb * conv, (rline + bs) - rh, mxrw - rline + 1) } } else if (i == nrow(t)) { ret[[length(ret) + 1]] <- page_vline(rb * conv, (rline + bs) - rh, mxrw - rline + 1) } else { ret[[length(ret) + 1]] <- page_vline(rb * conv, (rline + bs) - rh, mxrw - rline ) } } } if (any(brdrs %in% c("all", "inside")) & i < nrow(t)) { ret[[length(ret) + 1]] <- page_hline(tlb * conv, mxrw -rh + bs, (trb - tlb) * conv) } rline <- mxrw } ypos <- ystart - rs$row_height + bh - 1 ylen <- rline - rh + bs + 1 if (any(brdrs %in% c("all", "left", "outside"))) { ret[[length(ret) + 1]] <- page_vline(tlb * conv, ypos, ylen - ypos) } if (any(brdrs %in% c("all", "right", "outside"))) { ret[[length(ret) + 1]] <- page_vline(trb * conv, ypos, ylen - ypos) } pnts <- ylen - ystart + rh if (any(brdrs %in% c("all", "bottom", "outside"))) { ret[[length(ret) + 1]] <- page_hline(tlb * conv, ylen, (trb - tlb) * conv) border_flag <- TRUE if (any(brdrs %in% c("all"))) { pnts <- pnts - bh } } dev.off() rws <- rline res <- list(pdf = ret, lines = pnts / rs$row_height, points = pnts , border_flag = border_flag) return(res) }
mat.dissim <- function(inFossil, inModern, llMod=c(), modTaxa=c(), llFoss=c(), fosTaxa=c(), numAnalogs = 1, counts=T, sitenames = 1:length(inFossil[, 1]), dist.method = "euclidean") { modchar=deparse(substitute(inModern)) fosschar=deparse(substitute(inFossil)) if (length(modTaxa) != length(fosTaxa)) stop("Number of taxa in modern sample does not equal number of taxa in fossil sample") if (counts) { inModern[,modTaxa]=inModern[,modTaxa]/rowSums(inModern[,modTaxa]) inFossil[,fosTaxa]=inFossil[,fosTaxa]/rowSums(inFossil[,fosTaxa]) } nColsMatrix = length(inFossil[, 1]) LocMinRow = matrix(NA, nrow = numAnalogs, ncol = nColsMatrix) PosMinRow = matrix(NA, nrow = numAnalogs, ncol = nColsMatrix) DistMinRow <- matrix(NA, nrow = numAnalogs, ncol = nColsMatrix) DirMinRow <- matrix(NA, nrow = numAnalogs, ncol = nColsMatrix) CompxMinRow <- matrix(NA, nrow = numAnalogs, ncol = nColsMatrix) CompyMinRow <- matrix(NA, nrow = numAnalogs, ncol = nColsMatrix) colNames = vector("character") modMatrix = as.matrix(inModern[, modTaxa]) fossilMatrix = sqrt(as.matrix(inFossil[, fosTaxa])) fossilLongLatm=as.matrix(inFossil[,llFoss]) modernLongLatm=as.matrix(inModern[, llMod]) dimnames(fossilLongLatm)=NULL dimnames(modernLongLatm)=NULL dimnames(modMatrix) = NULL dimnames(fossilMatrix) = NULL modMatrix = sqrt(t(modMatrix)) for(i in 1:length(inFossil[, 1])) { currSpectrum = fossilMatrix[i, ] sqdistVec = (currSpectrum - modMatrix) sqdistVec= sqdistVec*sqdistVec x = colSums(sqdistVec) y = rank(x,ties.method="first") ysubset = y <= numAnalogs xysubset = x[ysubset] zorder = order(xysubset) x = sort(xysubset) tseq=1:length(y) topn = tseq[ysubset][zorder] if(dist.method == "spherical") { DistMinRow[, i] <- apply(rbind(modernLongLatm[topn, ]), 1, great.circle.distance.f, fossilLongLatm[i, ]) DirMinRow[, i] <- rep(NA, numAnalogs) } else if(dist.method == "euclidean") { DistMinRow[, i] <- apply(rbind(modernLongLatm[topn, ]), 1, euclidean.distance.f, fossilLongLatm[i, ]) DirMinRow[, i] <- apply(rbind(modernLongLatm[topn, ]), 1, euclidean.direction.f, fossilLongLatm[i, ]) CompxMinRow[, i] <- apply(rbind(modernLongLatm[topn, ]), 1, euclidean.compx.f, fossilLongLatm[i, ]) CompyMinRow[, i] <- apply(rbind(modernLongLatm[topn, ]), 1, euclidean.compy.f, fossilLongLatm[i, ]) } LocMinRow[, i] = x PosMinRow[, i] = topn } colNames = sitenames dimnames(LocMinRow) = list(NULL, colNames) dimnames(PosMinRow) = list(NULL, colNames) dimnames(DistMinRow) = list(NULL, colNames) dimnames(DirMinRow) = list(NULL, colNames) return(list( x = inFossil[, llFoss[1]], y = inFossil[, llFoss[2]], sqdist = LocMinRow, position = PosMinRow, distance = DistMinRow, direction = DirMinRow, xcomponent = CompxMinRow, ycomponent = CompyMinRow, inModern=modchar, inFossil=fosschar, llmod=llMod, modTaxa=modTaxa, counts=counts )) }
odb.read = function( odb, sqlQuery, stringsAsFactors = FALSE, check.names = FALSE, encode = TRUE, autoLogical = TRUE ) { if (!is(odb, "ODB")) { stop("'odb' must be an 'ODB' object") } validObject(odb) if (!is.character(sqlQuery) || length(sqlQuery) != 1 || is.na(sqlQuery)) { stop(call.=FALSE, "'sqlQuery' must be a unique non NA character vector") } tryCatch( query <- dbSendQuery(odb, sqlQuery), error = function(e) { stop(call.=FALSE, "Error while executing SQL query : \"", conditionMessage(e), "\"") }, warning = function(w) { stop(call.=FALSE, "Warning while executing SQL query : \"", conditionMessage(w), "\"") } ) results = fetch(res=query, n=-1) if (!check.names) { columns = dbColumnInfo(res=query) names(results) = as.character(columns$field.name) } if (!stringsAsFactors) { for(k in 1:ncol(results)) { if (is.factor(results[,k])) { results[,k] = as.character(results[,k]) } } } if (encode) { for(k in 1:ncol(results)) { if (is.character(results[,k]) | is.factor(results[,k])) { naVals = is.na(results[,k]) results[,k] = iconv(results[,k], from="UTF-8", to="") if (length(naVals) > 0) { results[naVals,k] = NA } } } } if (autoLogical) { for(k in 1:ncol(results)) { if (all(is.na(results[,k]) | results[,k] %in% c("true", "false"))) { results[,k] = as.logical(results[,k]) } } } return(results) }
f.points.CKrige<- function( formula, data, locations, object, method = 2, ex.out = F ) { t.support.designmat <- model.matrix(object = formula, data = data) t.response <- model.response( model.frame( formula, data ) ) locations <- terms( x= locations) attr(locations, "intercept") = 0 locations <- model.matrix(object = locations, data = data) if( dim( object@data )[1] == 0 && dim( object@data )[2] == 0 ) { t.pred.designmat <- matrix( rep( 1, dim( object@coords )[1] ) , ncol = 1 ) } else { t.terms.wr <- delete.response( termobj = terms( x = formula ) ) t.pred.designmat <- model.matrix( object = t.terms.wr, data = object@data) rm( t.terms.wr ) } model.me.free <- object@model[unlist(lapply(1:length(object@model), function(i,m){m[[i]]$model != "mev"}, m = object@model))] t.support.covmat <- f.covmat.support( object@model, locations ) t.ichol <- forwardsolve( t.chol <- t( chol(t.support.covmat ) ), diag( nrow( t.support.covmat ) ) ) t.isupport.covmat <- crossprod( t.ichol, t.ichol ) t.orth.designmat <- t.ichol %*% t.support.designmat t.orth.data <- t.ichol %*% t.response t.qr <- qr( as.data.frame( t.orth.designmat ) ) t.R <- qr.R( t.qr ) t.iR <- backsolve( t.R, diag( nrow( t.R ) ) ) t.beta.coef <- matrix( qr.coef( t.qr, as.data.frame( t.orth.data )), ncol = 1) t.cov.beta.coef <- crossprod( t( t.iR ), t( t.iR ) ) t.orth.resid <- qr.resid( t.qr, t.orth.data ) t.residuals <- t.chol %*% t.orth.resid t.index <- as.list( 1:dim( object@coords )[1] ) t.krige.res <- lapply(t.index, function(i, coords, posindex, t.bb.covmat.list, t.pred.designmat, locations, model, t.ichol, t.isupport.covmat, t.beta.coef, t.cov.beta.coef , t.orth.resid, t.orth.designmat, t.iR, method) { t.indices <- posindex[[ i ]] coords <- matrix( coords[ t.indices, ], ncol= 2 ) t.bb.covmat <- as.matrix( t.bb.covmat.list[[ t.indices[1] ]] ) t.pred.designmat <- matrix(t.pred.designmat[ t.indices, ], ncol = length( t.beta.coef ), nrow = length( t.indices ) ) t.dist <- f.row.dist( locations, coords ) t.pred.covmat <- matrix(f.pp.cov( as.vector(t.dist), model), ncol = ncol(t.dist) ) rm( t.dist ) t.pred.covmat.ichol.trans <- crossprod( t.pred.covmat, t( t.ichol) ) t.sk.weights <- t.pred.covmat.ichol.trans %*% t.ichol t.lin.trend.est <- crossprod( t( t.pred.designmat), t.beta.coef ) t.weighted.resid <- crossprod( t( t.pred.covmat.ichol.trans ), t.orth.resid ) t.uk.pred <- t.lin.trend.est + t.weighted.resid t.aux <- crossprod( t( t.pred.designmat - crossprod(t(t.pred.covmat.ichol.trans), t.orth.designmat) ) , t.iR) t.uk.mspe <- t.bb.covmat - tcrossprod( t.pred.covmat.ichol.trans, t.pred.covmat.ichol.trans ) + t.aux %*% t( t.aux ) t.result <- f.kriging.method( t.lin.trend.est, t.cov.beta.coef, t.weighted.resid, t.uk.mspe, t.bb.covmat, t.pred.designmat, t.orth.designmat, t.pred.covmat.ichol.trans, method) if(method == 1) { return( list( prediction = t.result[[1]], sqrt.mspe = t.result[[2]], sk.weights = t.sk.weights ) ) } if( method == 2 ) { return( list( prediction = t.result[[1]], sqrt.mspe = t.result[[2]], P1 = t.result[[3]], Q1 =t.result[[4]], K = t.result[[5]], sk.weights = t.sk.weights) ) } if( method == 3) { return( list( prediction = t.result[[1]], mspe = t.result[[2]], P1 = t.result[[3]], Q1 =t.result[[4]], K = t.result[[5]], sk.weights = t.sk.weights ) ) } }, coords = object@coords, posindex = object@posindex, t.bb.covmat.list = object@covmat, t.pred.designmat = t.pred.designmat, locations = locations, model = model.me.free, t.ichol = t.ichol, t.isupport.covmat = t.isupport.covmat, t.beta.coef = t.beta.coef, t.cov.beta.coef = t.cov.beta.coef, t.orth.resid = t.orth.resid, t.orth.designmat = t.orth.designmat, t.iR = t.iR, method = method ) if( method == 1 ){ krige.result <- data.frame( matrix( NaN, nrow = nrow( t.pred.designmat ), ncol = 2 ) ) krige.result[,1] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$prediction ) } ) ) krige.result[,2] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$sqrt.mspe ) } ) ) colnames( krige.result) = c("prediction", "prediction.se") } if( method == 2 ) { krige.result <- data.frame( matrix( NaN, nrow = nrow(t.pred.designmat), ncol = 5 ) ) krige.result[,1] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$prediction ) } ) ) krige.result[,2] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$sqrt.mspe ) } ) ) krige.result[,3] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$P1 ) } ) ) krige.result[,4] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$Q1 ) } ) ) krige.result[,5] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$K ) } ) ) colnames( krige.result) = c("prediction", "prediction.se", "P1", "Q1", "K") } if( method == 3) { krige.result <- data.frame( matrix( NaN, nrow = nrow(t.pred.designmat), ncol = 5 ) ) krige.result[,1] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$prediction[1,1] ) } ) ) krige.result[,2] <- unlist( lapply( t.krige.res, function( poly ){ return( sqrt( poly$mspe[1,1] ) ) } ) ) krige.result[,3] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$P1[1,1] ) } ) ) krige.result[,4] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$Q1[1,1] ) } ) ) krige.result[,5] <- unlist( lapply( t.krige.res, function( poly ){ return( poly$K[1,1] ) } ) ) colnames( krige.result) = c("prediction", "prediction.se","P1.11", "Q1.11", "K.11") } if( ex.out == T) { if( method == 1 | method == 2 ) { if( is.null( dim(t.krige.res[[1]]$sk.weights) ) ) { sk.weights.matrix <- t(matrix( unlist( lapply( t.krige.res, function( points ){ return( points$sk.weights ) } ) ), ncol = nrow( data ), byrow = T )) }else{ sk.weights.matrix <- t(matrix( unlist( lapply( t.krige.res, function( points ){ return( points$sk.weights[1,] ) } ) ), ncol = nrow( data ), byrow = T)) } object <- SpatialPointsDataFrame( SpatialPoints( object@coords ), data = krige.result, match.ID = F) res <- list( object = object, krig.method = method, parameter = list( beta.coef = t.beta.coef, cov.beta.coef = t.cov.beta.coef), sk.weights = sk.weights.matrix, inv.Sigma = t.isupport.covmat, residuals = t.residuals ) class( res ) <- "CKrige.exout.points" return( res ) } else { object <- SpatialPointsDataFrame( SpatialPoints(object@coords ), data = krige.result, match.ID = F) P1.list = lapply( t.krige.res, function( points ){ return(points$P1)}) Q1.list = lapply( t.krige.res, function( points ){ return(points$Q1)}) K.list = lapply( t.krige.res, function( points ){ return(points$K)}) sk.weights.list <-lapply( t.krige.res, function( points ){ return(t(points$sk.weights))}) res <- list( object = object, krig.method = method, CMCK.par = list(P1 = P1.list, Q1 =Q1.list,K = K.list), parameter = list( beta.coef = t.beta.coef, cov.beta.coef = t.cov.beta.coef), sk.weights = sk.weights.list, inv.Sigma = t.isupport.covmat, residuals = t.residuals ) class( res ) <- "CKrige.exout.points" return( res ) } } else { row.names( krige.result ) <- row.names( object@coords ) object <- SpatialPointsDataFrame( SpatialPoints( object@coords ), krige.result ) return( object ) } }
encrypt_data <- function(data, key, dest = NULL) { if (!is.raw(data)) { stop("Expected a raw vector; consider serialize(data, NULL)") } assert_is(key, "cyphr_key") res <- key$encrypt(data) if (is.null(dest)) { res } else { writeBin(res, dest) } } encrypt_object <- function(object, key, dest = NULL, rds_version = NULL) { encrypt_data(serialize(object, NULL, version = rds_version), key, dest) } encrypt_string <- function(string, key, dest = NULL) { if (!(is.character(string) && length(string) == 1L)) { stop("'string' must be a scalar character") } encrypt_data(charToRaw(string), key, dest) } encrypt_file <- function(path, key, dest = NULL) { encrypt_data(read_binary(path), key, dest) } decrypt_data <- function(data, key, dest = NULL) { assert_is(key, "cyphr_key") if (is.character(data)) { if (file.exists(data)) { data <- read_binary(data) } else { stop("If given as a character string, data must be a file that exists") } } res <- key$decrypt(data) if (is.null(dest)) { res } else { writeBin(res, dest) } } decrypt_object <- function(data, key) { unserialize(decrypt_data(data, key, NULL)) } decrypt_string <- function(data, key) { rawToChar(decrypt_data(data, key, NULL)) } decrypt_file <- function(path, key, dest = NULL) { decrypt_data(read_binary(path), key, dest) }
`cleanphe` <- function(x,string='Buffer') { require(qtl) if ( ! any(class(x) == 'cross') & ! any(class(x) == 'scanone') ) stop("Input should have class \"cross\" or class \"scanone\".") if ( ! is.character(string) & !is.vector(string)) stop("Expecting a characte r vector for string") if ( class(x)[1] == 'scanone') { coord <- grep(string,names(x)) cat("Drop ",length(coord),"lodcolumn\n"); if(!length(coord)) return(x); nf <- x[,-coord] } else { coord <- grep(string,names(x$pheno)) cat("Drop ",length(coord),"phenotypes\n"); if(!length(coord)) return(x); nf <- x nf$pheno <- x$pheno[,-coord] } attributes(nf)$class <- class(x) try(return(nf),silent=FALSE) }
bfactor <- function(data, model, model2 = paste0('G = 1-', ncol(data)), group = NULL, quadpts = NULL, invariance = '', ...) { Call <- match.call() dots <- list(...) if(!is.null(dots$dentype)) stop('bfactor does not currently support changing the dentype input', call.=FALSE) if(!is.null(dots$method)) stop('method cannot be changed for bifactor models', call.=FALSE) if(!is.null(dots$formula)) stop('bfactor does not currently support latent regression models', call.=FALSE) if(missing(model)) missingMsg('model') if(!is.numeric(model)) stop('model must be a numeric vector', call.=FALSE) if(is.numeric(model)) if(length(model) != ncol(data)) stop('length of model must equal the number of items', call.=FALSE) uniq_vals <- sort(na.omit(unique(model))) specific <- model for(i in seq_len(length(uniq_vals))) specific[uniq_vals[i] == model & !is.na(model)] <- i nspec <- length(uniq_vals) if(is.character(model2)){ tmp <- any(sapply(colnames(data), grepl, x=model2)) model2 <- mirt.model(model2, itemnames = if(tmp) colnames(data) else NULL) } if(!is(model2, 'mirt.model')) stop('model2 must be an appropriate second-tier model', call.=FALSE) model <- bfactor2mod(specific, ncol(data)) model$x <- rbind(model2$x, model$x) attr(model, 'nspec') <- nspec attr(model, 'specific') <- specific if(is.null(group)) group <- rep('all', nrow(data)) mod <- ESTIMATION(data=data, model=model, group=group, method='EM', quadpts=quadpts, BFACTOR = TRUE, invariance=invariance, ...) if(is(mod, 'SingleGroupClass') || is(mod, 'MultipleGroupClass')) mod@Call <- Call return(mod) }
call(arg, , more_args) a[, , drop = FALSE]
pie2 <- function (x, label = "", radius = 0.8, pie.bord=.1, pie.col='white', pie.col2 = 'grey', bg = 'white', border.width = 1) { x <- c(1-x, x) t2xy <- function(t, radius) { t2p <- twopi * t + init.angle * pi/180 list(x = radius * cos(t2p), y = radius * sin(t2p)) } init.angle <- 90 edges = 200 angle <- 45 density = c(NULL, NULL) lty = c(NULL, NULL) clockwise = FALSE col = c(pie.col2, pie.col) border = c(TRUE, TRUE) radius2 <- radius - radius*pie.bord n <- 200 x <- c(0, cumsum(x)/sum(x)) dx <- diff(x) nx <- length(dx) twopi <- 2 * pi plot.new() pin <- par("pin") xlim <- ylim <- c(-1, 1) plot.window(xlim, ylim, "", asp = 1) par("fg") for (i in 1L:nx) { P <- t2xy(seq.int(x[i], x[i + 1], length.out = n), radius) polygon(c(P$x, 0), c(P$y, 0), density = density[i], angle = angle[i], border = border[i], col = col[i], lty = lty[i], lwd = border.width) } border2 <- TRUE P2 <- t2xy(seq.int(x[1], x[3], length.out = n), radius2) polygon(c(P2$x, 0), c(P2$y, 0), density = NULL, angle = 45, border=TRUE, col=bg, lty=NULL, lwd = border.width) P3 <- t2xy(seq.int(x[1], x[3], length.out = n), radius2-radius2*.001) polygon(c(P2$x, 0), c(P2$y, 0), density = NULL, angle = 45, border=FALSE, col=bg, lty=NULL, lwd = border.width) text(0,0,label) }
expected <- eval(parse(text="complex(0)")); test(id=0, code={ argv <- eval(parse(text="list(logical(0), logical(0))")); do.call(`as.complex`, argv); }, o=expected);
bayesianLayman <- function(mu.post) { nr <- dim(mu.post[[1]])[1] layman.B <- list() for (k in 1:length(mu.post)) { layman.B[[k]] <- matrix(NA, nrow = nr, ncol = 6) for (i in 1:nr) { layman <- laymanMetrics(mu.post[[k]][i,1,], mu.post[[k]][i,2,]) layman.B[[k]][i,] <- layman$metrics } colnames(layman.B[[k]]) <- names(layman$metrics) } return(layman.B) }
test_that("Test suite aal.R, functionality in math.R",{ testequal <- function(x,y){testzero(x-y)} testzero <- function(x, TOL= 1e-8){expect_true(max(Mod(x))<TOL)} n <- 4 checker1 <- function(a){ stopifnot(length(a)==1) testequal(a,cumsum(a)) testequal(a,cumprod(a)) } checker1a <- function(a){ testequal(a,asin(sin(a))) testequal(a,atan(tan(a))) testzero(Mod(acos(cos(a))/a)-1) testequal(a,asinh(sinh(a))) testequal(a,atanh(tanh(a))) testzero(Mod(acosh(cosh(a))/a)-1) testzero(Mod(sign(a))-1) testequal(log(a,base=exp(1)),log(a)) } checker3 <- function(a){ stopifnot(length(a) == 3) testequal(c(a[1],a[1]*a[2],(a[1]*a[2])*a[3]),cumprod(a)) testequal(c(a[1],a[1]+a[2],(a[1]+a[2])+a[3]), cumsum(a)) testequal(a[1]+a[2]+a[3],sum(a)) if(is.quaternion(a)){testequal(a[1]*a[2]*a[3],prod(a))} if(is.octonion(a)){expect_error(prod(a))} expect_error(digamma(a)) expect_error(digamma(as.onionmat(a))) expect_error(Arg(a)) expect_error(Arg(as.onionmat(a))) expect_error(Complex(a)) expect_error(Complex(as.onionmat(a))) testequal(Norm(a),Mod(a)^2) testequal(Norm(as.onionmat(a)),Mod(as.onionmat(a))^2) } jj <- romat() testequal(jj,Conj(Conj(jj))) expect_true(all(Mod(jj) >= 0)) for(i in seq_len(n)){ checker1(rquat(1)) checker1(roct(1)) checker1a(rquat(3)/31) checker1a(roct(3)/31) checker3(rquat(3)) checker3(roct(3)) } })
set.seed(1) total_dp <- 10 tau_t <- rep(0.8, total_dp) p_t <- rep(0.4, total_dp) gamma <- 0.05 b <- 0.2 g_t <- cbind(rep(1, total_dp), 1:total_dp) alpha <- as.matrix(c(-0.2, -0.1), ncol = 1) mu0_t <- exp(g_t %*% alpha) f_t <- cbind(rep(1, total_dp), 1:total_dp) beta <- as.matrix(c(0.15, - 0.01), ncol = 1) mee_t <- f_t %*% beta mu1_t <- mu0_t * exp(mee_t) p_t <- rep(0.4, total_dp) gamma <- 0.05 b <- 0.2 g_t <- cbind(rep(1, total_dp), 1:total_dp) alpha <- as.matrix(c(-0.2, -0.1), ncol = 1) mu0_t <- exp(g_t %*% alpha) f_t <- cbind(rep(1, total_dp), 1:total_dp) beta <- as.matrix(c(0.15, - 0.01), ncol = 1) mee_t <- f_t %*% beta mu1_t <- mu0_t * exp(mee_t) g_new <- cbind(rep(1, total_dp), 1:total_dp, (1:total_dp)^2) alpha_new <- as.matrix(c(-0.2, -0.1, .01), ncol = 1) f_new <- cbind(rep(1, total_dp), 1:total_dp, (1:total_dp)^2) beta_new <- as.matrix(c(0.15, - 0.01, -.1), ncol = 1) test_that( "check if first error check of invalid probabilities catches error", { expect_error( compute_m_sigma(tau_t, f_t, -g_t, beta, alpha, p_t), message="g_t and alpha values led to invalid probabilities") } ) test_that( "check if second error check of invalid probabilities catches error", { expect_error( compute_m_sigma(tau_t, f_t, g_t, beta+1, alpha, p_t, gamma, b), message="f_t and beta values led to invalid probabilities") } )
vcov.fitfrail <- function(object, boot=FALSE, B=100, Lambda.times=NULL, cores=0, ...) { fit <- object Call <- match.call() if (is.null(Lambda.times)) { Lambda.times <- fit$Lambda$time } if (!boot) { Lambda.times = NULL } if (!is.null(fit$VARS[["COV"]]) && !is.null(fit$VARS[["COV.call"]])) { new.Call <- fit$VARS[["COV.call"]] cache.Call <- Call new.Call$object <- NULL new.Call$cores <- NULL cache.Call$object <- NULL cache.Call$cores <- NULL if(identical(new.Call, cache.Call)) return(fit$VARS[["COV"]]) } vcov.boot <- function() { fn <- function(s) { set.seed(s) weights <- rexp(fit$n.clusters) weights <- weights/mean(weights) new.call <- fit$call new.call$weights <- weights new.fit <- eval(new.call) c(new.fit$beta, new.fit$theta, setNames(new.fit$Lambda.fun(Lambda.times), paste("Lambda.", format(Lambda.times, nsmall=2), sep=""))) } hats <- t(simplify2array(plapply(B, fn, cores=cores))) cov(hats) } vcov.estimator <- function() with(fit$VARS, { jac <- score_jacobian() V <- Reduce('+', lapply(1:n.clusters, function(i) { xi_[i,] %*% t(xi_[i,]) }))/n.clusters Q_beta_ <- lapply(1:n.beta, function(r) { Q_beta(X_, K_, H_, R_star, phi_1_, phi_2_, phi_3_, r) }) Q_theta_ <- lapply((n.beta+1):(n.beta+n.theta), function(r) { Q_theta(H_, R_star, phi_1_, phi_2_, phi_prime_1_[[r - n.beta]], phi_prime_2_[[r - n.beta]]) }) Q_ <- c(Q_beta_, Q_theta_) Ycal_ <- Ycal(X_, R_star, Y_, psi_, hat.beta) eta_ <- eta(phi_1_, phi_2_, phi_3_) Upsilon_ <- Upsilon(X_, R_star, K_, R_dot_, eta_, Ycal_, hat.beta) Omega_ <- Omega(X_, R_star, N_, R_dot_, eta_, Ycal_, hat.beta) p_hat_ <- p_hat(I_, Upsilon_, Omega_, N_tilde_) pi_ <- lapply(1:n.gamma, function(r) { pi_r(Q_[[r]], N_tilde_, p_hat_) }) G <- outer(1:n.gamma, 1:n.gamma, Vectorize(function(r, l) { G_rl(pi_[[r]], pi_[[l]], p_hat_, Ycal_, N_) })) M_hat_ <- M_hat(X_, R_star, N_, Y_, psi_, hat.beta, Lambda) u_star_ <- u_star(pi_, p_hat_, Ycal_, M_hat_) C <- outer(1:n.gamma, 1:n.gamma, Vectorize(function(r, l) { sum(vapply(1:n.clusters, function(i) { xi_[i,r] * u_star_[i,l] + xi_[i,l] * u_star_[i,r] }, 0)) }))/n.clusters D_inv <- solve(jac) (D_inv %*% (V + G + C) %*% t(D_inv))/n.clusters }) if (boot) { COV <- vcov.boot() } else { COV <- vcov.estimator() } param.names <- c(names(fit$beta), names(fit$theta)) if (length(Lambda.times) > 0) { param.names <- c(param.names, paste("Lambda.", format(Lambda.times, nsmall=2), sep="")) } rownames(COV) <- param.names colnames(COV) <- param.names fit$VARS[["COV"]] <- COV fit$VARS[["COV.call"]] <- Call COV }
optim.boxcox <- function (formula, groups = 1, data, K = 3, steps = 500, tol = 0.5, start = "gq", EMdev.change = 1e-04, find.in.range = c(-3, 3), s = 60, plot.opt = 3, verbose = FALSE, noformat = FALSE, ...) { call <- match.call() mform <- strsplit(as.character(groups), "\\|") mform <- gsub(" ", "", mform) if (!noformat) { if (steps > 8) graphics::par(mfrow = c(4, 4), cex = 0.5) else graphics::par(mfrow = c(3, 3), cex = 0.5, cex.axis = 1.1) } result <- disp <- loglik <- EMconverged <- rep(0, s + 1) S <- 0:s lambda <- find.in.range[1] + (find.in.range[2] - find.in.range[1]) * S/s for (t in 1:(s + 1)) { fit <- try(np.boxcoxmix(formula = formula, groups = groups, data = data, K = K, lambda = lambda[t], steps = steps, tol = tol, start = start, EMdev.change = EMdev.change, plot.opt = plot.opt, verbose = verbose)) if (class(fit) == "try-error") { cat("optim.boxcox failed using lambda=", lambda[t], ". Hint: specify another range of lambda values and try again.") return() } EMconverged[t] <- fit$EMconverged result[t] <- fit$loglik if (!all(is.finite(result[t]))) { print.plot <- FALSE } } s.max <- which.max(result) max.result <- result[s.max] lambda.max <- lambda[s.max] fit <- np.boxcoxmix(formula = formula, groups = groups, data = data, K = K, lambda = lambda.max, steps = steps, tol = tol, start = start, EMdev.change = EMdev.change, plot.opt = 0, verbose = verbose) W <- fit$w P <- fit$p se <- fit$se iter <- fit$EMiteration names(P) <- paste("MASS", 1:K, sep = "") Z <- fit$mass.point names(Z) <- paste("MASS", 1:K, sep = "") Beta <- fit$beta Sigma <- fit$sigma Disp <- fit$disparity Disparities <- fit$Disparities n <- NROW(data) if (fit$model == "pure") { if(K==1){ aic <- Disp + 2 * 2 bic <- Disp + log(n) * 2 } else { aic <- Disp + 2 * (2 * K) bic <- Disp + log(n) * (2 * K) }} else {if(K==1){ aic <- Disp + 2 * (length(Beta) +1) bic <- Disp + log(n) * (length(Beta) +1) } else { aic <- Disp + 2 * (length(Beta) + 2 * K) bic <- Disp + log(n) * (length(Beta) + 2 * K) }} y <- fit$y yt <- fit$yt fitted <- fit$fitted fitted.transformed <- fit$fitted.transformed masses <- fit$masses ylim <- fit$ylim residuals <- fit$residuals residuals.transformed <- fit$residuals.transformed predicted.re <- fit$predicted.re Class <- fit$Class xx <- fit$xx model <- fit$model Disp <- fit$disparity Disparities <- fit$Disparities Loglik <- fit$loglik npcolors <- "green" ylim1 = range(result, max.result) maxl <- paste("Maximum profile log-likelihood:", round(max.result, digits = 3), "at lambda=", round(lambda.max, digits = 2), "\n") if (plot.opt == 3) { graphics::plot(lambda, result, type = "l", xlab = expression(lambda), ylab = "Profile log-likelihood", ylim = ylim1, col = "green") plims <- graphics::par("usr") y0 <- plims[3] graphics::segments(lambda.max, y0, lambda.max, max.result, lty = 1, col = "red", lwd = 2) cat("Maximum profile log-likelihood:", max.result, "at lambda=", lambda.max, "\n") result <- list(call = call, y0 = y0, p = P, mass.point = Z, beta = Beta, sigma = Sigma, se = se, w = W, Disparities = Disparities, formula = formula, data = data, loglik = Loglik, aic = aic, bic = bic, masses = masses, y = y, yt = yt, All.lambda = lambda, profile.loglik = result, disparity = Disp, EMconverged = EMconverged, Maximum = lambda.max, mform = length(mform), ylim = ylim, fitted = fitted, Class = Class, fitted.transformed = fitted.transformed, predicted.re = predicted.re, residuals = residuals, residuals.transformed = residuals.transformed, objective = max.result, kind = 3, EMiteration = iter, ss = s, s.max = s.max, npcolor = npcolors, ylim1 = ylim1, xx = xx, maxl = maxl, model = model) class(result) <- "boxcoxmix" } else { result <- list(call = call, p = P, mass.point = Z, beta = Beta, sigma = Sigma, se = se, w = W, Disparities = Disparities, formula = formula, data = data, loglik = Loglik, aic = aic, bic = bic, masses = masses, y = y, yt = yt, All.lambda = lambda, profile.loglik = result, disparity = Disp, EMconverged = EMconverged, Maximum = lambda.max, mform = length(mform), ylim = ylim, fitted = fitted, Class = Class, fitted.transformed = fitted.transformed, predicted.re = predicted.re, residuals = residuals, residuals.transformed = residuals.transformed, objective = max.result, kind = 3, EMiteration = iter, ss = s, s.max = s.max, npcolor = npcolors, ylim1 = ylim1, xx = xx, maxl = maxl, model = model) class(result) <- "boxcoxmix" } return(result) }
imp.rfnode.prox <- function( data, num.imp = 5, max.iter = 5, num.trees = 10, pre.boot = TRUE, print.flag = FALSE, ...) { return(mice( data = data, method = "rfnode", m = num.imp, maxit = max.iter, num.trees.node = num.trees, pre.boot = pre.boot, use.node.cond.dist = FALSE, obs.eq.prob = FALSE, do.sample = TRUE, printFlag = print.flag, maxcor = 1.0, eps = 0, remove.collinear = FALSE, remove.constant = FALSE, ...)) }
ExponentSet <- R6Class("ExponentSet", inherit = ProductSet, public = list( initialize = function(set, power) { if (power == "n") { lower <- set$lower upper <- set$upper setlist <- list(set) private$.power <- "n" cardinality <- NULL } else { lower <- Tuple$new(rep(set$lower, power)) upper <- Tuple$new(rep(set$upper, power)) setlist <- rep(list(set), power) private$.power <- as.integer(power) if (is.null(set$properties$cardinality)) { cardinality <- NULL } else if (grepl("Beth|Aleph", set$properties$cardinality)) { cardinality <- set$properties$cardinality } else { cardinality <- set$properties$cardinality^power } } type <- "{}" super$initialize(setlist = setlist, lower = lower, upper = upper, type = type, cardinality = cardinality) }, strprint = function(n = 2) { if (inherits(self$wrappedSets[[1]], "SetWrapper")) { paste0("(", self$wrappedSets[[1]]$strprint(n = n), ")^", self$power) } else { paste(self$wrappedSets[[1]]$strprint(n = n), self$power, sep = "^") } }, contains = function(x, all = FALSE, bound = FALSE) { x <- listify(x) if (self$power == "n") { ret <- vapply(x, function(.x) { if (testSet(.x)) { self$wrappedSets[[1]]$contains(.x$elements, all = TRUE, bound = bound) } else { self$wrappedSets[[1]]$contains(.x, all = TRUE, bound = bound) } }, logical(1)) } else { ret <- sapply(x, function(el) { if (!testSet(el)) { el <- as.Set(el) } if (el$length != self$power) { return(FALSE) } all(self$wrappedSets[[1]]$contains(el$elements, bound = bound)) }) } returner(ret, all) } ), active = list( power = function() { return(private$.power) } ), private = list( .power = 1L ) )
sGBJ_scores=function(surv, factor_matrix, covariates = NULL, nperm = 300){ lsScores <- .survival_scores(factor_matrix = factor_matrix, covariates = covariates, surv = surv) epsilon <- .epsilon_matrix(Z = lsScores$Z, nperm = nperm, surv = surv, factor_matrix = lsScores$updatedFactor_matrix, covariates = covariates, dat = lsScores$datas) scores_GBJ <- list("test_stats" = lsScores$Z, "cor_mat" = epsilon) return(scores_GBJ) }
context("MULTSBM test") library(greed) library(ggplot2) set.seed(1234) test_that("MULTSBM sim", { N = 100 K = 3 pi = rep(1/K,K) mu = array(dim=c(K,K,3)) mu[,,1] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[1,1,1]=runif(1)*0.005 mu[,,2] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[2,2,1]=runif(1)*0.005 mu[,,3] = 1- mu[,,1]-mu[,,2] lambda = 10 multsbm = rmultsbm(N,pi,mu,10) expect_equal(dim(multsbm$x)[1], N) expect_equal(dim(multsbm$x)[2], N) expect_equal(length(multsbm$cl),N) expect_gte(min(multsbm$cl), 1) expect_lte(max(multsbm$cl), K) }) test_that("MULTSBM hybrid", { N = 100 K = 3 pi = rep(1/K,K) mu = array(dim=c(K,K,3)) mu[,,1] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[1,1,1]=runif(1)*0.005 mu[,,2] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[2,2,1]=runif(1)*0.005 mu[,,3] = 1- mu[,,1]-mu[,,2] lambda = 10 multsbm = rmultsbm(N,pi,mu,10) sol=greed(multsbm$x,model=new('multsbm')) expect_equal(sol@K, K) solc = cut(sol,2) expect_true(is.ggplot(plot(solc,type='tree'))) expect_true(is.ggplot(plot(solc,type='path'))) expect_true(is.ggplot(plot(solc,type='front'))) expect_true(is.ggplot(plot(solc,type='blocks'))) expect_true(is.ggplot(plot(solc,type='nodelink'))) }) test_that("MULTSBM seed", { N = 100 K = 3 pi = rep(1/K,K) mu = array(dim=c(K,K,3)) mu[,,1] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[1,1,1]=runif(1)*0.005 mu[,,2] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[2,2,1]=runif(1)*0.005 mu[,,3] = 1- mu[,,1]-mu[,,2] lambda = 10 multsbm = rmultsbm(N,pi,mu,10) sol=greed(multsbm$x,model=new('multsbm'),alg=new("seed")) expect_gte(sol@K, K-2) expect_lte(sol@K, K+2) solc = cut(sol,2) expect_true(is.ggplot(plot(solc,type='tree'))) expect_true(is.ggplot(plot(solc,type='path'))) expect_true(is.ggplot(plot(solc,type='front'))) expect_true(is.ggplot(plot(solc,type='blocks'))) expect_true(is.ggplot(plot(solc,type='nodelink'))) }) test_that("MULTSBM multitstart", { N = 100 K = 3 pi = rep(1/K,K) mu = array(dim=c(K,K,3)) mu[,,1] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[1,1,1]=runif(1)*0.005 mu[,,2] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[2,2,1]=runif(1)*0.005 mu[,,3] = 1- mu[,,1]-mu[,,2] lambda = 10 multsbm = rmultsbm(N,pi,mu,10) sol=greed(multsbm$x,model=new('multsbm'),alg=new("multistarts")) expect_gte(sol@K, K-2) expect_lte(sol@K, K+2) solc = cut(sol,2) expect_true(is.ggplot(plot(solc,type='tree'))) expect_true(is.ggplot(plot(solc,type='path'))) expect_true(is.ggplot(plot(solc,type='front'))) expect_true(is.ggplot(plot(solc,type='blocks'))) expect_true(is.ggplot(plot(solc,type='nodelink'))) }) test_that("MULTSBM genetic", { N = 100 K = 3 pi = rep(1/K,K) mu = array(dim=c(K,K,3)) mu[,,1] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[1,1,1]=runif(1)*0.005 mu[,,2] = diag(rep(1/5,K))+runif(K^2)*0.005 mu[2,2,1]=runif(1)*0.005 mu[,,3] = 1- mu[,,1]-mu[,,2] lambda = 10 multsbm = rmultsbm(N,pi,mu,10) sol=greed(multsbm$x,model=new('multsbm'),alg=new("genetic")) expect_gte(sol@K, K-2) expect_lte(sol@K, K+2) solc = cut(sol,2) expect_true(is.ggplot(plot(solc,type='tree'))) expect_true(is.ggplot(plot(solc,type='path'))) expect_true(is.ggplot(plot(solc,type='front'))) expect_true(is.ggplot(plot(solc,type='blocks'))) expect_true(is.ggplot(plot(solc,type='nodelink'))) })
plot_weighting_continuous <- function(mod, covariate, alpha = 0.05, ...) { checkmate::assert_class(mod, "regweight") checkmate::assert_numeric(covariate) ok <- stats::complete.cases(covariate, mod$weights) n <- sum(ok) covariate <- covariate[ok] wts <- mod$weights[ok] range <- stats::quantile(covariate, probs = c(0.05, 0.95)) eval_pts <- seq(range[1], range[2], length = 250) wkde <- lpdensity::lpdensity( covariate, grid = eval_pts, Pweights = wts / sum(wts) * n, kernel = "epanechnikov", bwselect = "imse-dpi" ) kde <- lpdensity::lpdensity( covariate, grid = eval_pts, kernel = "epanechnikov", bwselect = "imse-dpi" ) tbl <- dplyr::tibble( weight = rep(c("Implicit regression", "Nominal"), c(250, 250)), transp = rep(c(1, 0.5), c(250, 250)), covariate = c(eval_pts, eval_pts), density = c(wkde$Estimate[, "f_p"], kde$Estimate[, "f_p"]), std_error = c(wkde$Estimate[, "se_q"], kde$Estimate[, "se_q"]), lwr = .data$density - stats::qnorm(1 - alpha / 2) * .data$std_error, upr = .data$density + stats::qnorm(1 - alpha / 2) * .data$std_error ) ggplot2::ggplot(tbl, ggplot2::aes( x = .data$covariate, alpha = .data$transp, color = .data$weight, fill = .data$weight ) ) + ggplot2::geom_line(aes(y = .data$density)) + ggplot2::geom_line(aes(y = .data$lwr), linetype = "dashed") + ggplot2::geom_line(aes(y = .data$upr), linetype = "dashed") + ggplot2::scale_x_continuous("") + ggplot2::scale_y_continuous("Covariate density") + ggplot2::scale_fill_manual("", values = c("Implicit regression" = "black", "Nominal" = "red") ) + ggplot2::scale_color_manual("", values = c("Implicit regression" = "black", "Nominal" = "red") ) + ggplot2::scale_alpha_continuous(guide = "none", limits = c(0, 1)) + ggplot2::scale_linetype_discrete(guide = "none") + ggplot2::theme_minimal() }
randTree <- function(n, wndmtrx=FALSE, parallel=FALSE) { .randomPrinds <- function(n) { pool <- rep((1:(n-1)), each=2) res <- rep(NA, length(pool)+1) res[1] <- 1 for(i in 2:length(res)) { pssbls <- which(i > pool) if(length(pssbls) == 1) { i_pool <- pssbls } else { i_pool <- sample(pssbls, 1) } res[i] <- pool[i_pool] pool[i_pool] <- NA } res } if(n < 3) { stop("`n` is too small") } prinds <- .randomPrinds(n) .cnstrctTree(n, prinds, wndmtrx=wndmtrx, parallel=parallel) } blncdTree <- function(n, wndmtrx=FALSE, parallel=FALSE) { if(n < 3) { stop("`n` is too small") } prinds <- c(1, rep((1:(n-1)), each=2)) .cnstrctTree(n, prinds, wndmtrx=wndmtrx, parallel=parallel) } unblncdTree <- function(n, wndmtrx=FALSE, parallel=FALSE) { if(n < 3) { stop("`n` is too small") } prinds <- c(1, 1:(n-1), 1:(n-1)) .cnstrctTree(n, prinds, wndmtrx=wndmtrx, parallel=parallel) } .cnstrctTree <- function(n, prinds, wndmtrx, parallel) { .add <- function(i) { nd <- vector("list", length=4) names(nd) <- c('id', 'ptid', 'prid', 'spn') nd[['id']] <- ids[i] nd[['spn']] <- spns[i] nd[['prid']] <- ids[prinds[i]] nd[['ptid']] <- ptids[ptnds_pool == i] nd } nnds <- length(prinds) spns <- c(0, runif(nnds-1, 0, 1)) ids <- rep(NA, nnds) tinds <- which(!1:nnds %in% prinds) ids[tinds] <- paste0('t', 1:n) ids[1:nnds %in% prinds] <- paste0('n', 1:(n-1)) ptnds_pool <- prinds[-1] ptids <- ids[-1] ndlst <- plyr::mlply(.data=1:nnds, .fun=.add, .parallel=parallel) attr(ndlst, "split_labels") <- attr(ndlst, "split_type") <- NULL names(ndlst) <- ids tree <- new('TreeMan', ndlst=ndlst, root='n1', wtxnyms=FALSE, ndmtrx=NULL, prinds=prinds, tinds=tinds) tree <- updateSlts(tree) if(wndmtrx) { tree <- addNdmtrx(tree) } tree } twoer <- function(tids=c('t1', 't2'), spns=c(1,1), rid='root', root_spn=0) { ndlst <- list() ndlst[[rid]] <- list('id'=rid, 'prid'=rid, 'ptid'=tids[1:2], 'spn'=root_spn) ndlst[[tids[1]]] <- list('id'=tids[[1]], 'prid'=rid, 'ptid'=NULL, 'spn'=spns[1]) ndlst[[tids[2]]] <- list('id'=tids[[2]], 'prid'=rid, 'ptid'=NULL, 'spn'=spns[2]) prinds <- c(1, 1, 1) tinds <- c(2, 3) tree <- new('TreeMan', ndlst=ndlst, root='root', wtxnyms=FALSE, ndmtrx=NULL, prinds=prinds, tinds=tinds) updateSlts(tree) }
perspdepth=function(x,method="Tukey",output=FALSE,tt=50,xlab="X",ylab="Y",zlab=NULL,col=NULL,...){ if(is.data.frame(x)) x=as.matrix(x) if(is.list(x)) { m=length(x) n=length(x[[1]]) y=matrix(0,n,m) for(i in 1:m){ y[,i]=x[[i]] if(length(x[[i]])!=n){ stop("When using a list, each element must be a vector of the same length.") } } x=y } match.arg(method,c("Tukey","Liu","Oja")) p=length(x[1,]) n=length(x[,1]) if(p>n) { warning(message=paste("Is your data ",n," points in ",p," dimensions.\nIf not, you should transpose your data matrix.")) } if(p!=2) { stop("Data must be bivariate.\n") } if(is.null(zlab)){ zlab=paste(method,"'s depth",sep="") } if(method=="Tukey"||method=="Liu"){ y=x[,2] x=x[,1] minx=min(x) miny=min(y) ecx=max(x)-minx ecy=max(y)-miny xx=minx yy=miny for (i in 1:tt){ xx=c(xx,minx+i/tt*ecx) yy=c(yy,miny+i/tt*ecy) } ans = .Fortran("iso3d", as.numeric(x), as.numeric(y), z=numeric((tt+1)^2), as.integer(n), as.integer(tt), as.integer(method=="Liu"), as.numeric(xx), as.numeric(yy), PACKAGE="depth") zz=matrix(ans$z,tt+1,tt+1) if(output==FALSE){ if(is.null(col)){ col="lightblue" } persp3d(xx,yy,zz,col=col,xlab=xlab,ylab=ylab,zlab=zlab,...) rep=NULL } if(output==TRUE){ return(list(x=as.vector(xx),y=as.vector(yy),z=as.matrix(zz))) } } if(method=="Oja"){ w=x y=x[,2] x=x[,1] minx=min(x) miny=min(y) ecx=max(x)-minx ecy=max(y)-miny xx=minx yy=miny for (i in 1:tt){ xx=c(xx,minx+i/tt*ecx) yy=c(yy,miny+i/tt*ecy) } ans = .Fortran("ojaiso3d", as.numeric(w), z=numeric((tt+1)^2), as.integer(n), as.integer(tt), as.numeric(xx), as.numeric(yy), PACKAGE="depth") zz=matrix(ans$z,tt+1,tt+1) if(output==FALSE){ if(is.null(col)){ col="lightblue" } persp3d(xx,yy,zz,col=col,xlab=xlab,ylab=ylab,zlab=zlab,...) rep=NULL } if(output==TRUE){ return(list(x=as.vector(xx),y=as.vector(yy),z=as.matrix(zz))) } } invisible() }
discretizeDF.supervised <- function(formula, data, method = "mdlp", dig.lab = 3, ...) { if(!is(data, "data.frame")) stop("data needs to be a data.frame") methods = c("mdlp", "caim", "cacc", "ameva", "chi2", "chimerge", "extendedchi2", "modchi2") method <- methods[pmatch(tolower(method), methods)] if(is.na(method)) stop(paste("Unknown method! Available methods are", paste(methods, collapse = ", "))) vars <- .parseformula(formula, data) cl_id <- vars$class_ids var_ids <- vars$var_ids if(any(!sapply(data[var_ids], is.numeric))) stop("Cannot discretize non-numeric column: ", colnames(data)[var_ids[!sapply(data[var_ids], is.numeric)]]) if(method == "mdlp") { cps <- structure(vector("list", ncol(data)), names = colnames(data)) for(i in var_ids) { missing <- is.na(data[[i]]) cPts <- try(discretization::cutPoints(data[[i]][!missing], data[[cl_id]][!missing]), silent = TRUE) if(is(cPts, "try-error")) stop("Problem with discretizing column ", i, " (maybe not enough non-missing values?)") cps[[i]] <- list( breaks = c(-Inf, cPts, Inf), method = "fixed") } } else { data_num_id <- var_ids data_num <- data[,c(data_num_id, cl_id)] res <- switch(method, caim = discretization::disc.Topdown(data_num, method = 1), cacc = discretization::disc.Topdown(data_num, method = 2), ameva = discretization::disc.Topdown(data_num, method = 3), chi2 = discretization::chi2(data_num, ...), chimerge = discretization::chiM(data_num, ...), extendedchi2 = discretization::extendChi2(data_num, ...), modchi2 = discretization::modChi2(data_num, ...) ) cps <- structure(vector("list", ncol(data)), names = colnames(data)) for(i in 1:length(data_num_id)) { cps[[data_num_id[i]]] <- list( breaks = c(-Inf, res$cutp[[i]], Inf), method = "fixed") } } data <- discretizeDF(data, methods = cps, default = list(method = "none")) for(i in var_ids) attr(data[[i]], "discretized:method") <- method data }
"ktaskv" <- function(x,n=nrow(x),tau=.dFvGet()$tua,f=.dFvGet()$fff) { if (missing(x)) messagena("x") np <- ncol(x) mdx <- nrow(x) ncov <- np*(np+1)/2 a <- single(ncov) cov <- single(ncov) f.res <- .Fortran("ktaskvz", x=to.single(x), n=to.integer(n), np=to.integer(np), mdx=to.integer(mdx), ncov=to.integer(ncov), tau=to.single(tau), f=to.single(f), a=to.single(a), cov=to.single(cov)) list(a=f.res$a,cov=f.res$cov) }
test_that("performance_and_fairness with plot", { paf <- performance_and_fairness(fobject) expect_s3_class(paf, "performance_and_fairness") suppressWarnings(expect_error(performance_and_fairness(fobject, fairness_metric = "non_existing"))) suppressWarnings(expect_error(performance_and_fairness(fobject, performance_metric = "non_existing"))) suppressWarnings(expect_error(performance_and_fairness(fairness_metric = c("d", "f")))) suppressWarnings(expect_error(performance_and_fairness(performance_metric = c("d", "f")))) suppressWarnings(expect_error(performance_and_fairness(fairness_metric = 17))) suppressWarnings(expect_error(performance_and_fairness(performance_metric = 17))) plt <- plot(paf) expect_s3_class(plt, "ggplot") paf <- suppressWarnings(performance_and_fairness(fobject, performance_metric = "auc")) paf <- performance_and_fairness(fobject, performance_metric = "accuracy") paf <- performance_and_fairness(fobject, performance_metric = "precision") paf <- performance_and_fairness(fobject, performance_metric = "recall") })
library(nlsem) mod <- specify_sem(num.x=4, num.y=4, num.xi=2, num.eta=2, xi="x1-x2,x3-x4", eta="y1-y2,y3-y4", constraints="direct1", num.classes=2, interaction="none", rel.lat="eta1~xi1,eta2~xi2,eta2~eta1,eta1~eta2") dat <- as.data.frame(mod) dat[c(2,8,10,16),2:3] <- 1 dat[c(58,62),2:3] <- 0 dat[65:72,2:3] <- 1 model <- create_sem(dat) parameters <- c( rep(0.5, 2), c(-0.3, 0.7), rep(0.5, 10), rep(1, 2), rep(1, 2), rep(1, 2), rep(-0.5, 2), c(0.7, -0.3), rep(0.5, 10), rep(1, 2), rep(1, 2), rep(4, 2) ) data <- simulate(model, seed=7, parameters=parameters) set.seed(8) parameters <- runif(count_free_parameters(model), 0.1, 1.5)
library(lazytrade) library(testthat) library(magrittr) library(dplyr) context("util_profit_factor") test_that("test value of the calculation", { data(profit_factor_data) DF_Stats <- profit_factor_data %>% group_by(X1) %>% summarise(PnL = sum(X5), NumTrades = n(), PrFact = util_profit_factor(X5)) %>% select(PrFact) %>% head(1) %>% round(3) expect_equal(DF_Stats$PrFact, 0.68) })
negbin.pow <- function(n,lambda1,k,disp=1.5,alpha,seed = 200, numsim = 1000,monitor=TRUE,sig=3) { n.integer <- function(x, tol = .Machine$double.eps) { abs(x - round(x)) < tol } if(alpha >= 1 || alpha <= 0) stop("Error: alpha must be between 0 and 1") if( any(k <= 0) ) stop("Error: k <= 0") if( any(disp <= 0) ) stop("Error: Dispersion <= 0. See documentation for underdispersion specification") if( mean(n.integer(n)) !=1 || n<= 0) stop("n must be positive integer") negbin.disp<-function (n, lambda,disp) { if (disp==1) {rpois(n, lambda)} else {rnbinom(n, size=(1/(disp-1)), mu=lambda)} } l <- list(n=n,lambda1=lambda1,k=k,disp=disp,alpha=alpha,seed = seed,numsim=numsim) store <- expand.grid(l) inner.fcn <- function(n,lambda1,k,disp,alpha,seed,numsim) { T_nb <- NULL set.seed(seed) for (i in 1:numsim) { x <- negbin.disp(n, lambda1,disp) y <- negbin.disp(n, lambda1,disp) a <- mean(x); b <- mean(y) se <- sqrt((a+(disp-1)*a^2)/n + (b+(disp-1)*b^2)/n) t <- ( mean(x) - mean(y) ) / se T_nb[i] <- t } T_nb <- na.omit(T_nb) T_crit <- c(quantile(T_nb,alpha/2),quantile(T_nb,1-alpha/2)) T_nb.alt <- NULL for (i in 1:numsim) { x <- negbin.disp(n, lambda1,disp) y <- negbin.disp(n, k*lambda1, disp) a <- mean(x); b <- mean(y) se <- sqrt((a+(disp-1)*a^2)/n + (b+(disp-1)*b^2)/n) t <- ( mean(x) - mean(y) ) / se T_nb.alt[i] <- t } summary(T_nb.alt) val1 <- length(T_nb.alt[T_nb.alt > T_crit[2]]) val2 <- length(T_nb.alt[T_nb.alt < T_crit[1]]) power <- sum(val1,val2)/numsim } if (monitor == TRUE) { pb <- txtProgressBar(min = 0, max = dim(store)[1], style = 3) for (i in 1:dim(store)[1]) { power <- mapply(inner.fcn,store[,1],store[,2],store[,3],store[,4],store[,5],store[,6],store[,7]) std.err <- sqrt(power*(1-power)/store[,7]) out <- cbind(store[,1:5],round(power,sig),round(std.err,3)) colnames(out) <- c("N","Mean.Null","Effect.Size","Disp.Par","Type.I.Error","Power","Std.Err") setTxtProgressBar(pb, i) } close(pb) return(out) } if (monitor == FALSE) { power <- mapply(inner.fcn,store[,1],store[,2],store[,3],store[,4],store[,5],store[,6],store[,7]) std.err <- sqrt(power*(1-power)/store[,7]) out <- cbind(store[,1:5],round(power,sig),round(std.err,3)) colnames(out) <- c("N","Mean.Null","Effect.Size","Disp.Par","Type.I.Error","Power","Std.Err") return(out) } }
context("Binary") test_that("Rational example works", { suppressWarnings({ Rational <- defineClass("Rational", contains = c("Show", "Binary"), { numer <- 0 denom <- 1 .g <- 1 .gcd <- function(a, b) if(b == 0) a else Recall(b, a %% b) init <- function(numer, denom) { .self$.g <- .gcd(numer, denom) .self$numer <- numer / .g .self$denom <- denom / .g } show <- function() { cat(paste0(.self$numer, "/", .self$denom, "\n")) } ".+" <- function(that) { Rational(numer = numer * that$denom + that$numer * denom, denom = denom * that$denom) } neg <- function() { Rational(numer = -.self$numer, denom = .self$denom) } ".-" <- function(that) { .self + that$neg() } }) rational <- Rational(2, 3) expect_equal(rational$numer, 2) expect_equal(rational$denom, 3) rational <- rational + rational expect_equal(rational$numer, 4) expect_equal(rational$denom, 3) rational <- rational$neg() expect_equal(rational$numer, -4) expect_equal(rational$denom, 3) rational <- rational - rational expect_equal(rational$numer, 0) expect_equal(rational$denom, 1) x <- Rational(numer = 1, denom = 3) y <- Rational(numer = 5, denom = 7) z <- Rational(numer = 3, denom = 2) rational <- x - y - z expect_equal(rational$numer, -79) expect_equal(rational$denom, 42) }) })
structure(list(url = "https://api.twitter.com/2/tweets/search/all?query=%23standwithhongkong&max_results=500&start_time=2020-06-20T00%3A00%3A00Z&end_time=2020-06-21T00%3A00%3A00Z&tweet.fields=attachments%2Cauthor_id%2Cconversation_id%2Ccreated_at%2Centities%2Cgeo%2Cid%2Cin_reply_to_user_id%2Clang%2Cpublic_metrics%2Cpossibly_sensitive%2Creferenced_tweets%2Csource%2Ctext%2Cwithheld&user.fields=created_at%2Cdescription%2Centities%2Cid%2Clocation%2Cname%2Cpinned_tweet_id%2Cprofile_image_url%2Cprotected%2Cpublic_metrics%2Curl%2Cusername%2Cverified%2Cwithheld&expansions=author_id%2Centities.mentions.username%2Cgeo.place_id%2Cin_reply_to_user_id%2Creferenced_tweets.id%2Creferenced_tweets.id.author_id&place.fields=contained_within%2Ccountry%2Ccountry_code%2Cfull_name%2Cgeo%2Cid%2Cname%2Cplace_type&q=%23CPC100Years", status_code = 401L, headers = structure(list(date = "Sun, 04 Jul 2021 13:14:24 UTC", server = "tsa_o", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "91", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `strict-transport-security` = "max-age=631138519", `x-connection-hash` = "cf5ec88fb71130f8e692029e90502ae4a86a4ca038611670dd0f5955841268e9"), class = c("insensitive", "list")), all_headers = list(list(status = 401L, version = "HTTP/2", headers = structure(list(date = "Sun, 04 Jul 2021 13:14:24 UTC", server = "tsa_o", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "91", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `strict-transport-security` = "max-age=631138519", `x-connection-hash` = "cf5ec88fb71130f8e692029e90502ae4a86a4ca038611670dd0f5955841268e9"), class = c("insensitive", "list")))), cookies = structure(list(domain = c(".twitter.com", ".twitter.com"), flag = c(TRUE, TRUE), path = c("/", "/"), secure = c(TRUE, TRUE), expiration = structure(c(1688456705, 1688456705), class = c("POSIXct", "POSIXt")), name = c("personalization_id", "guest_id"), value = c("REDACTED", "REDACTED")), row.names = c(NA, -2L), class = "data.frame"), content = charToRaw("{\"title\":\"Unauthorized\",\"type\":\"about:blank\",\"status\":401,\"detail\":\"Unauthorized\"}"), date = structure(1625404464, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 4.4e-05, connect = 4.6e-05, pretransfer = 0.000186, starttransfer = 0.125812, total = 0.125846)), class = "response")
sideBySideQQPlot <- function(x, fun, envelope = TRUE, half.normal = FALSE, n.samples = 250, level = .95, id.n = 3, qqline = TRUE, ...) { confidence.envelope <- function(n, sd = 1, n.samples = 250, level = 0.95, half.normal = FALSE) { lower <- upper <- matrix(0.0, n, n.models) alphaOver2 <- (1.0 - level) / 2.0 probs <- c(alphaOver2, 1.0 - alphaOver2) env <- matrix(rnorm(n * n.samples, sd = sd), n.samples, n) if(half.normal) env <- abs(env) env <- apply(env, 1, sort) env <- apply(env, 1, quantile, probs = probs) list(lower = env[1, ], upper = env[2, ]) } n.models <- length(x) mod.names <- names(x) res <- lapply(x, fun) n.res <- sapply(res, length) px <- py <- list() for(i in 1:n.models) { tmp <- qqnorm(res[[i]], plot.it = FALSE) px[[i]] <- tmp$x py[[i]] <- tmp$y } if(half.normal) { py <- lapply(py, abs) px <- lapply(n.res, function (u) .5 + (0:(u-1)) / (2*u)) px <- lapply(px, qnorm) for(i in 1:n.models) px[[i]][order(py[[i]])] <- px[[i]] } if(envelope) { sigma.hats <- numeric(n.models) for(i in 1:n.models) { if(!is.null(x[[i]]$scale)) sigma.hats[i] <- x[[i]]$scale else { x.sum <- summary(x[[i]]) if(!is.null(x.sum$dispersion)) sigma.hats[i] <- sqrt(x.sum$dispersion) else if(!is.null(x.sum$sigma)) sigma.hats[i] <- x.sum$sigma else stop("unable to determine residual scale") } } env <- list() for(i in 1:n.models) env[[i]] <- confidence.envelope(n.res[i], sigma.hats[i], n.samples, level, half.normal) lower <- lapply(env, function(u) u$lower) upper <- lapply(env, function(u) u$upper) den.range <- c(min(unlist(py), unlist(lower)), max(unlist(py), unlist(upper))) } else den.range <- c(min(unlist(py)), max(unlist(py))) if(envelope && half.normal) { mod <- factor(rep(rep(mod.names, n.res), 3), levels = mod.names) tdf <- data.frame(py = c(unlist(py), unlist(lower), unlist(upper)), px = rep(unlist(px), 3), mod = mod) panel.special <- function(x, y, id.n, qqline, ...) { dat.idx <- 1:(length(x)/3) panel.xyplot(x[dat.idx], y[dat.idx], ...) if(qqline) { u <- quantile(x[!is.na(x)], c(0.25, 0.75)) v <- quantile(y[!is.na(y)], c(0.25, 0.75)) slope <- diff(v) / diff(u) int <- v[1] - slope * u[1] panel.abline(int, slope, ...) } panel.addons(x[dat.idx], y[dat.idx], id.n = id.n) dat.idx <- ((length(x)/3)+1):(2*length(x)/3) llines(sort(x[dat.idx]), sort(y[dat.idx]), col.line = "black", lty = 2) dat.idx <- (2*(length(x)/3)+1):(length(x)) llines(sort(x[dat.idx]), sort(y[dat.idx]), col.line = "black", lty = 2) invisible() } } else if(envelope) { mod <- factor(rep(rep(mod.names, n.res), 3), levels = mod.names) tdf <- data.frame(py = c(unlist(py), unlist(lower), unlist(upper)), px = rep(unlist(px), 3), mod = mod) panel.special <- function(x, y, id.n, qqline, ...) { dat.idx <- 1:(length(x)/3) panel.xyplot(x[dat.idx], y[dat.idx], ...) panel.addons(x[dat.idx], y[dat.idx], id.n = id.n) if(qqline) { u <- quantile(x[!is.na(x)], c(0.25, 0.75)) v <- quantile(y[!is.na(y)], c(0.25, 0.75)) slope <- diff(v) / diff(u) int <- v[1] - slope * u[1] panel.abline(int, slope, ...) } dat.idx <- ((length(x)/3)+1):(2*length(x)/3) llines(sort(x[dat.idx]), sort(y[dat.idx]), col.line = "black", lty = 2) dat.idx <- (2*(length(x)/3)+1):(length(x)) llines(sort(x[dat.idx]), sort(y[dat.idx]), col.line = "black", lty = 2) invisible() } } else { mod <- factor(rep(mod.names, n.res), levels = mod.names) tdf <- data.frame(px = unlist(px), py = unlist(py), mod = mod) panel.special <- function(x, y, id.n, qqline, ...) { panel.xyplot(x, y, ...) panel.addons(x, y, id.n = id.n) if(qqline) { u <- quantile(x[!is.na(x)], c(0.25, 0.75)) v <- quantile(y[!is.na(y)], c(0.25, 0.75)) slope <- diff(v) / diff(u) int <- v[1] - slope * u[1] panel.abline(int, slope, ...) } invisible() } } p <- xyplot(py ~ px | mod, data = tdf, id.n = id.n, qqline = qqline, panel = panel.special, strip = function(...) strip.default(..., style = 1), layout = c(n.models, 1, 1), ...) print(p) invisible(p) }
sample(x=1:10, size=3) sample(x=c(1.5, 2.5, 3, 6.7), size=2) sample(x=1:10, size=15) sample(x=1:10, size=15, replace=T) sample.int(n=100, size=30, replace=F) month.abb[1:12] sample(x=month.abb[1:12], size=3, replace=T) sample(x=c('M','F'), size=10, replace=T)
ClusterTreeCompile <- function(dag, node.class) { elim.order <- EliminationOrder(dag, node.class=node.class) graph.mor <- Moralize(dag) graph.tri <- Triangulate(graph.mor, elim.order) cs <- ElimTreeNodes(graph.tri, elim.order) strongET <- StrongEliminationTree(cs, elim.order) semiET <- SemiEliminationTree(strongET, cs, node.class, elim.order) output <- list(tree.graph=semiET, dag=dag, cluster.sets=cs, node.class=node.class, elimination.order=elim.order) return(output) }
require(geometa, quietly = TRUE) require(testthat) context("ISOReferenceIdentifier") test_that("encoding",{ testthat::skip_on_cran() md <- ISOReferenceIdentifier$new(code = "4326", codeSpace = "EPSG") expect_is(md, "ISOReferenceIdentifier") expect_equal(md$code, "4326") expect_equal(md$codeSpace, "EPSG") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOReferenceIdentifier$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
addGhostVars <- function(obj, keyVar, ghostVars) { addGhostVarsX(obj, keyVar, ghostVars) } setGeneric("addGhostVarsX", function(obj, keyVar, ghostVars) { standardGeneric("addGhostVarsX") }) setMethod(f="addGhostVarsX", signature=c(obj="sdcMicroObj", keyVar="character", ghostVars="character"), definition = function(obj, keyVar, ghostVars) { obj <- nextSdcObj(obj) cn <- colnames(get.sdcMicroObj(obj, type="origData")) kv <- cn[get.sdcMicroObj(obj, type="keyVars")] if (length(keyVar)!=1) { stop("length of argument 'keyVar' must be 1 in addGhostVars!\n") } if (!keyVar %in% kv) { stop("variable specified in 'keyVar' in not a categorical key variable!\n") } nv <- cn[get.sdcMicroObj(obj, type="numVars")] pv <- cn[get.sdcMicroObj(obj, type="pramVars")] wv <- cn[get.sdcMicroObj(obj, type="weightVar")] hhid <- cn[get.sdcMicroObj(obj, type="hhId")] sv <- cn[get.sdcMicroObj(obj, type="strataVar")] non_poss <- c(kv, nv, pv, wv, hhid, sv) gv <- get.sdcMicroObj(obj, type="ghostVars") if (!is.null(gv)) { ex_gv <- cn[unlist(sapply(gv, function(x) { x[[2]] }))] non_poss <- c(non_poss, ex_gv) } non_poss <- unique(non_poss) if (any(ghostVars %in% non_poss)) { stop("variables listed in 'ghostVars' were either specified as important (key) variables or were already specified as ghost-variables!\n") } new_kv <- standardizeInput(obj=obj, v=keyVar) new_gv <- standardizeInput(obj=obj, v=ghostVars) if (is.null(gv)) { tmp <- list() tmp[[1]] <- new_kv tmp[[2]] <- new_gv inp <- list() inp[[1]] <- tmp } else { inp <- gv ii <- which(unlist(sapply(gv, function(x) { x[[1]] })) == new_kv) if (length(ii)==1) { inp[[ii]][[2]] <- c(inp[[ii]][[2]], new_gv) } else { tmp <- list() tmp[[1]] <- new_kv tmp[[2]] <- new_gv inp[[length(inp)+1]] <- tmp } } manipGhostVars <- get.sdcMicroObj(obj, type = "manipGhostVars") if (is.null(manipGhostVars)) { manipGhostVars <- get.sdcMicroObj(obj, "origData")[, new_gv, drop = FALSE] } else { df <- get.sdcMicroObj(obj, "origData")[, new_gv, drop = FALSE] new <- setdiff(colnames(df), colnames(manipGhostVars)) if (length(new) > 0) { df <- df[, new, drop = FALSE] manipGhostVars <- cbind(manipGhostVars, df) } } obj <- set.sdcMicroObj(obj, type="manipGhostVars", input=list(manipGhostVars)) obj <- set.sdcMicroObj(obj, type="ghostVars", input=list(inp)) obj })
factorPlot <- function(v, partial, band, rug, w, top, line.par, fill.par, points.par, ...) { if (band) fp_bands(v, w, fill.par) if (!partial) { fp_lines(v, w, line.par) } else { if (top=='line') { fp_points(v, w, points.par) fp_lines(v, w, line.par) } else { fp_lines(v, w, line.par) fp_points(v, w, points.par) } } fp_rug(v, w, rug, line.par) } fp_lines <- function(v, w, line.par) { xx <- v$fit[, v$meta$x] K <- length(levels(xx)) len <- K*(1-w)+(K-1)*w yy <- v$fit$visregFit for(k in 1:K) { x1 <- (k-1)/len x2 <- (k-1)/len + (1-w)/len xx <- c(x1, x2) line.args <- list(x=c(x1, x2), y=rep(yy[k], 2), lwd=3, col=" if (length(line.par)) line.args[names(line.par)] <- line.par do.call("lines", line.args) } } fp_bands <- function(v, w, fill.par) { xx <- v$fit[, v$meta$x] K <- length(levels(xx)) len <- K*(1-w)+(K-1)*w lwr <- v$fit$visregLwr upr <- v$fit$visregUpr for(k in 1:K) { x1 <- (k-1)/len x2 <- (k-1)/len + (1-w)/len xx <- c(x1, x2) fill.args <- list(x=c(xx, rev(xx)), y=c(rep(lwr[k], 2), rev(rep(upr[k], 2))), col="gray85", border=F) if (length(fill.par)) fill.args[names(fill.par)] <- fill.par do.call("polygon", fill.args) } } fp_points <- function(v, w, points.par) { x <- v$res[, v$meta$x] y <- v$res$visregRes K <- length(levels(x)) len <- K*(1-w)+(K-1)*w for(k in 1:K) { x1 <- (k-1)/len x2 <- (k-1)/len + (1-w)/len ind <- x==levels(x)[k] rx <- seq(x1, x2, len=sum(ind)+2)[c(-1, -(sum(ind)+2))] points.args <- list(x=rx, y=y[ind], pch=19, cex=0.4, col="gray50") if (length(points.par)) points.args[names(points.par)] <- points.par do.call("points", points.args) } } fp_rug <- function(v, w, rug, line.args) { x <- v$res[, v$meta$x] y <- v$res$visregRes K <- length(levels(x)) len <- K*(1-w)+(K-1)*w for(k in 1:K) { x1 <- (k-1)/len x2 <- (k-1)/len + (1-w)/len ind <- x==levels(x)[k] rx <- seq(x1, x2, len=sum(ind)+2)[c(-1, -(sum(ind)+2))] if (!all(is.na(v$res$visregPos))) { if (rug==1) rug(rx, col=line.args$col) if (rug==2) { ind1 <- ind & !v$res$visregPos ind2 <- ind & v$res$visregPos rx1 <- seq(x1, x2, len=sum(ind1)+2)[c(-1,-(sum(ind1)+2))] rx2 <- seq(x1, x2, len=sum(ind2)+2)[c(-1,-(sum(ind2)+2))] rug(rx1, col=line.args$col) rug(rx2, side=3, col=line.args$col) } } } }
cv.glmtlp <- function(X, y, ..., seed=NULL, nfolds=10, obs.fold=NULL, ncores=1) { cv.call <- match.call(expand.dots = TRUE) fit <- glmtlp(X = X, y = y, ...) nobs <- nrow(X) family <- fit$family penalty <- fit$penalty lambda <- fit$lambda kappa <- fit$kappa if (family == "binomial" & !identical(sort(unique(y)), 0:1)) { y <- as.double(y == max(y)) } if (!is.null(seed)) set.seed(seed) if (nfolds > nobs) stop(paste("nfolds (", nfolds, ") cannot be larger than the number of observations (", nobs, ")", sep = "")) if (is.null(obs.fold)) { if (family == "binomial") { n0 <- sum(y == 0) obs.fold[y == 0] <- sample(rep(1:nfolds, length.out = n0)) obs.fold[y == 1] <- sample(rep(1:nfolds, length.out = nobs - n0)) } else { obs.fold <- sample(rep(1:nfolds, length.out = nobs)) } } else { nfolds <- max(obs.fold) } if (ncores > 1) { doParallel::registerDoParallel(cores = ncores) cv.res <- foreach(fold = 1:nfolds, .combine = "rbind", .packages = c("glmtlp")) %dopar% { fit.fold <- glmtlp(X, y, weights = 1 * (obs.fold != fold), lambda = lambda, kappa = kappa, family = family, penalty = penalty) yhat <- predict.glmtlp(fit.fold, X=X[obs.fold == fold, , drop=FALSE], type="response") loss <- loss.glmtlp(y[obs.fold == fold], yhat, family) loss } } else { cv.res <- c() for (fold in 1:nfolds) { fit.fold <- glmtlp(X, y, weights = 1 * (obs.fold != fold), lambda = lambda, kappa = kappa, family = family, penalty = penalty) yhat <- predict.glmtlp(fit.fold, X=X[obs.fold == fold, , drop = FALSE], type="response") loss <- loss.glmtlp(y[obs.fold == fold], yhat, family) cv.res <- rbind(cv.res, loss) } } cv.mean <- apply(cv.res, 2, mean) cv.se <- apply(cv.res, 2, sd) idx.min <- which.min(cv.mean)[1] out <- structure(list(call = cv.call, fit = fit, obs.fold = obs.fold, cv.mean = cv.mean, cv.se = cv.se, idx.min = idx.min, null.dev = loss.glmtlp(y, rep(mean(y), nobs), family) ), class = "cv.glmtlp") if (penalty == "l0") { out$lambda <- lambda out$kappa <- kappa out$kappa.min <- kappa[idx.min] } else { out$lambda <- lambda out$lambda.min <- lambda[idx.min] } out }
context("connections - gateway") sc <- testthat_spark_connection() test_that("gateway connection fails with invalid session", { expect_error( spark_connect(master = "sparklyr://localhost:8880/0") ) }) test_that("can connect to an existing session via gateway", { gw <- spark_connect( master = paste0("sparklyr://localhost:8880/", sc$sessionId) ) expect_equal(spark_context(gw)$backend, spark_context(sc)$backend) })
general.carryover.old <- function(design, model, t0=1, rho=0.5){ if ("CrossoverSearchResult" %in% class(design)) { if(missing(model)) { model <- design@model } else { if (model!=design@model) warning("Model from object does not equal specified model") } design <- design@design } if ("CrossoverDesign" %in% class(design)) { if(missing(model)) { model <- design@model } else { if (model!=design@model) warning("Model from object does not equal specified model") } design <- design@design } model <- getModelNr(model) design <- t(design) n.subj<-length(design[,1]) n.per<-length(design[1,]) n.dat<-n.subj*n.per n.trt<-length(table(design)) unique.seq<-unique(data.frame(design)) n.seq<-dim(unique.seq)[1] n.per.seq<-rep(0,n.seq) group.id<-numeric(length=n.dat) for(i in 1:n.subj){ for(k in 1:n.seq){ if(sum(abs(design[i,]-unique.seq[k,]))==0){ n.per.seq[k]<-n.per.seq[k]+1 low<-(i-1)*n.per+1 upp<-low+(n.per-1) group.id[low:upp]<-k } } } subject<-rep(1:n.subj, rep(n.per,n.subj)) per<-rep(1:n.per, n.subj) Xmat.mean<-matrix(1,n.dat,1) Xmat.subj<-matrix(0,n.dat,n.subj) for(i in 1:n.dat){ Xmat.subj[i,subject[i]]<-1 } Xmat.per<-matrix(0,n.dat,n.per) for(i in 1:n.dat){ Xmat.per[i,per[i]]<-1 } if(model==9){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} return(list(Var.trt.pair=Var.trt.pair,model=model)) } if(model==1){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } car<-NULL for(i in 1:n.subj){ car<-c(car,1,design[i,1:(n.per-1)]) } Xmat.car<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car[i]>0){Xmat.car[i,car[i]]<-1} } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] } } Var.car<-XtX.inv[(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt),(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt)] Var.car.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair[i,j]<-Var.car[i,i]+Var.car[j,j]-2*Var.car[i,j] Var.car.pair[j,i]<-Var.car.pair[i,j] } } return(list(Var.trt.pair=Var.trt.pair,Var.car.pair=Var.car.pair,model=model)) } if(model==2){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } carry.mat.1<-matrix(0,n.subj,n.per) for(i in 1:n.subj){ for(j in 2:n.per){ if(design[i,j]!=design[i,(j-1)]){carry.mat.1[i,j]<-design[i,(j-1)]} }} car.1<-NULL for(i in 1:n.subj){ car.1<-c(car.1,carry.mat.1[i,]) } Xmat.car.1<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car.1[i]>0){Xmat.car.1[i,car.1[i]]<-1} } carry.mat.2<-matrix(0,n.subj,n.per) for(i in 1:n.subj){ for(j in 2:n.per){ if(design[i,j]==design[i,(j-1)]){carry.mat.2[i,j]<-design[i,(j-1)]} }} car.2<-NULL for(i in 1:n.subj){ car.2<-c(car.2,carry.mat.2[i,]) } Xmat.car.2<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car.2[i]>0){Xmat.car.2[i,car.2[i]]<-1} } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car.1,Xmat.car.2) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} Var.car.1<-XtX.inv[(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt),(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt)] Var.car.pair.1<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair.1[i,j]<-Var.car.1[i,i]+Var.car.1[j,j]-2*Var.car.1[i,j] Var.car.pair.1[j,i]<-Var.car.pair.1[i,j] }} Var.car.2<-XtX.inv[(1+n.subj+n.per+n.trt+n.trt+1):(1+n.subj+n.per+n.trt+n.trt+n.trt),(1+n.subj+n.per+n.trt+n.trt+1):(1+n.subj+n.per+n.trt+n.trt+n.trt)] Var.car.pair.2<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair.2[i,j]<-Var.car.2[i,i]+Var.car.2[j,j]-2*Var.car.2[i,j] Var.car.pair.2[j,i]<-Var.car.pair.2[i,j] }} return(list(Var.trt.pair=Var.trt.pair,Var.car.pair.1=Var.car.pair.1,Var.car.pair.2=Var.car.pair.2,model=model)) } if(model==3){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } car<-NULL for(i in 1:n.subj){ car<-c(car,0,design[i,1:(n.per-1)]) } Xmat.car<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car[i]>0){Xmat.car[i,car[i]]<-rho} } Xmat.trt<-Xmat.trt+Xmat.car Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} return(list(Var.trt.pair=Var.trt.pair,model=model,rho=rho)) } if(model==4){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } carry.mat<-matrix(0,n.subj,n.per) for(i in 1:n.subj){ for(j in 2:n.per){ if(design[i,(j-1)]>t0){carry.mat[i,j]<-design[i,(j-1)]} }} car<-NULL for(i in 1:n.subj){ car<-c(car,carry.mat[i,]) } Xmat.car<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car[i]>0){Xmat.car[i,car[i]]<-1} } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} Var.car<-XtX.inv[(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt),(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt)] Var.car.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair[i,j]<-Var.car[i,i]+Var.car[j,j]-2*Var.car[i,j] Var.car.pair[j,i]<-Var.car.pair[i,j] }} return(list(Var.trt.pair=Var.trt.pair,Var.car.pair=Var.car.pair,model=model,t0=t0)) } if(model==5){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } carry.mat<-matrix(0,n.subj,n.per) for(i in 1:n.subj){ for(j in 2:n.per){ if(design[i,j]!=design[i,(j-1)]){carry.mat[i,j]<-design[i,(j-1)]} }} car<-NULL for(i in 1:n.subj){ car<-c(car,carry.mat[i,]) } Xmat.car<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car[i]>0){Xmat.car[i,car[i]]<-1} } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} Var.car<-XtX.inv[(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt),(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt)] Var.car.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair[i,j]<-Var.car[i,i]+Var.car[j,j]-2*Var.car[i,j] Var.car.pair[j,i]<-Var.car.pair[i,j] }} return(list(Var.trt.pair=Var.trt.pair,Var.car.pair=Var.car.pair,model=model)) } if(model==6){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } carry.mat<-matrix(0,n.subj,n.per) for(i in 1:n.subj){ for(j in 2:n.per){ if(design[i,j]==design[i,(j-1)]){carry.mat[i,j]<-design[i,(j-1)]} }} car<-NULL for(i in 1:n.subj){ car<-c(car,carry.mat[i,]) } Xmat.car<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car[i]>0){Xmat.car[i,car[i]]<--1} } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} Var.car<-XtX.inv[(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt),(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt)] Var.car.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair[i,j]<-Var.car[i,i]+Var.car[j,j]-2*Var.car[i,j] Var.car.pair[j,i]<-Var.car.pair[i,j] }} return(list(Var.trt.pair=Var.trt.pair,Var.car.pair=Var.car.pair,model=model)) } if(model==7){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } car<-NULL for(i in 1:n.subj){ car<-c(car,0,design[i,1:(n.per-1)]) } Xmat.car<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car[i]>0){Xmat.car[i,car[i]]<-1} } Xmat.int<-matrix(0,n.dat,n.trt*n.trt) count<-0 for(i in 1:n.trt){ for(j in 1:n.trt){ count<-count+1 Xmat.int[,count]<-Xmat.trt[,i]*Xmat.car[,j] } } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car,Xmat.int) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} return(list(Var.trt.pair=Var.trt.pair,model=model)) } if(model==8){ trt<-NULL for(i in 1:n.subj){ trt<-c(trt,design[i,]) } Xmat.trt<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ Xmat.trt[i,trt[i]]<-1 } car.1<-NULL for(i in 1:n.subj){ car.1<-c(car.1,1,design[i,1:(n.per-1)]) } Xmat.car.1<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car.1[i]>0){Xmat.car.1[i,car.1[i]]<-1} } car.2<-NULL for(i in 1:n.subj){ car.2<-c(car.2,1,1,design[i,1:(n.per-2)]) } Xmat.car.2<-matrix(0,n.dat,n.trt) for(i in 1:n.dat){ if(car.2[i]>0){Xmat.car.2[i,car.2[i]]<-1} } Xmat<-cbind(Xmat.mean,Xmat.subj,Xmat.per,Xmat.trt,Xmat.car.1,Xmat.car.2) XtX<-t(Xmat)%*%Xmat XtX.inv<-ginv(XtX) Var.trt<-XtX.inv[(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt),(1+n.subj+n.per+1):(1+n.subj+n.per+n.trt)] Var.trt.pair<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.trt.pair[i,j]<-Var.trt[i,i]+Var.trt[j,j]-2*Var.trt[i,j] Var.trt.pair[j,i]<-Var.trt.pair[i,j] }} Var.car.1<-XtX.inv[(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt),(1+n.subj+n.per+n.trt+1):(1+n.subj+n.per+n.trt+n.trt)] Var.car.pair.1<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair.1[i,j]<-Var.car.1[i,i]+Var.car.1[j,j]-2*Var.car.1[i,j] Var.car.pair.1[j,i]<-Var.car.pair.1[i,j] }} Var.car.2<-XtX.inv[(1+n.subj+n.per+n.trt+n.trt+1):(1+n.subj+n.per+n.trt+n.trt+n.trt),(1+n.subj+n.per+n.trt+n.trt+1):(1+n.subj+n.per+n.trt+n.trt+n.trt)] Var.car.pair.2<-matrix(0,n.trt,n.trt) for(i in 1:(n.trt-1)){ for(j in 1:n.trt){ Var.car.pair.2[i,j]<-Var.car.2[i,i]+Var.car.2[j,j]-2*Var.car.2[i,j] Var.car.pair.2[j,i]<-Var.car.pair.2[i,j] }} return(list(Var.trt.pair=Var.trt.pair,Var.car.pair.1=Var.car.pair.1,Var.car.pair.2=Var.car.pair.2,model=model)) } } test.ge <- function() { if (!"extended" %in% strsplit(Sys.getenv("CROSSOVER_UNIT_TESTS"),",")[[1]]) { cat("Skipping comparison of old and new general.carryover function.\n") return() } f <- stop f <- cat path <- system.file("data", package="Crossover") for (file in dir(path=path)) { if (file %in% c("clatworthy1.rda", "clatworthyC.rda", "pbib2combine.rda")) next designs <- load(paste(path, file, sep="/")) for (designS in designs) { design <- get(designS) v <- length(table(design)) for (model in 1:7) { r1 <- general.carryover(design, model=model) r2 <- general.carryover.old(design, model=model) if (estimable(design, v, model)) { if(!isTRUE(all.equal(r1$Var.trt.pair, r2$Var.trt.pair))) { f(paste("Unequal treatment variances for",designS," in model ", model," (",max(abs(r1$Var.trt.pair - r2$Var.trt.pair)),")!\n")) } } if (model==1) { if(!isTRUE(all.equal(r1$Var.car.pair, r2$Var.car.pair))) { f(paste("Unequal carry-over variances for",designS," in model ", model," (",max(abs(r1$Var.car.pair - r2$Var.car.pair))," - ",getCounts(design),")!\n")) } } } cat("Everything okay for design ", designS, ".\n") } } } test.ge()
max_length <- function(.stack) { attr(.stack, "max_length") } "max_length<-" <- function(x, value) { attr(x, "max_length") <- value x }
source('../gsDesign_independent_code.R') testthat::test_that("Test: alpha - incorrect variable type", { tx <- (0:100) / 100 param <- list(trange = c(.2, .8), sf = gsDesign::sfHSD, param = 1) testthat::expect_error(gsDesign::spendingFunction(alpha = "abc", t = c(.1, .4), param), info = "Checking for incorrect variable type" ) testthat::expect_error(gsDesign::spendingFunction(alpha = 0, t = c(.1, .4), param), info = "Checking for out-of-range variable value" ) testthat::expect_error(gsDesign::spendingFunction(alpha = -1, t = c(.1, .4), param), info = "Checking for out-of-range variable value" ) }) testthat::test_that("Test: t - Checking Variable Type, Out-of-Range, Order-of-List", { param <- list(trange = c(.2, .8), sf = gsDesign::sfHSD, param = 1) testthat::expect_error(gsDesign::spendingFunction(alpha = .025, t = "a", param), info = "Checking for incorrect variable type" ) testthat::expect_error(gsDesign::spendingFunction(alpha = .025, t = c("a", "b"), param), info = "Checking for incorrect variable type" ) testthat::expect_error(gsDesign::spendingFunction(alpha = .025, t = c(-.5, .75), param), info = "Checking for out-of-range variable value" ) testthat::expect_error(gsDesign::spendingFunction(alpha = .025, t = c(.5, -.75), param), info = "Checking for out-of-range variable value" ) testthat::expect_error(gsDesign::spendingFunction(alpha = .025, t = c(1, -5), param), info = "Checking for out-of-range variable value" ) testthat::expect_error(gsDesign::spendingFunction(alpha = .025, t = c(-1, 5), param), info = "Checking for out-of-range variable value" ) }) testthat::test_that("Test: output validation for alpha - 0.025, Source: gsDesign_independent_code.R )", { tx <- c(.025, .05, .25, .75, 1) alpha <- 0.025 param <- 1 spend <- gsDesign::spendingFunction(alpha, tx, param)$spend expected_spend <- validate_spendingFunction(alpha, tx, param) expect_equal(spend, expected_spend) }) testthat::test_that("Test: output validation for alpha - 0.02, Source: gsDesign_independent_code.R )", { tx <- c(.2, .15, 1) alpha <- 0.02 param <- NULL spend <- gsDesign::spendingFunction(alpha, tx, param)$spend expected_spend <- validate_spendingFunction(alpha, tx, param) expect_equal(spend, expected_spend) }) testthat::test_that("Test: output validation for param - 0, Source: gsDesign_independent_code.R )", { tx <- c(0.9, .5) alpha <- .01 param <- 0 spend <- gsDesign::spendingFunction(alpha, tx, param)$spend expected_spend <- validate_spendingFunction(alpha, tx, param) expect_equal(spend, expected_spend) }) testthat::test_that("Test: output validation for param - 5, Source: gsDesign_independent_code.R )", { tx <- c(.25, 0.5, 0.75, 1) alpha <- .025 param <- 5 spend <- gsDesign::spendingFunction(alpha, tx, param)$spend expected_spend <- validate_spendingFunction(alpha, tx, param) expect_equal(spend, expected_spend) })
test_that("can handle NA `from` and `to` values", { na <- new_date(NA_real_) expect_error(alma_seq(na, Sys.Date(), daily()), "cannot be `NA`") expect_error(alma_seq(Sys.Date(), na, daily()), "cannot be `NA`") }) test_that("behavior is like rlang::seq2() when `from` is after `to`", { expect_identical(alma_seq("1999-01-01", "1998-01-01", runion()), almanac_global_empty_date) }) test_that("empty runion means no dates are removed", { expect_identical( alma_seq(new_date(0), new_date(1), runion()), new_date(c(0, 1)) ) }) test_that("events are removed", { rule <- monthly() %>% recur_on_mday(2) expect_identical( alma_seq("2000-01-01", "2000-01-03", rule), as.Date(c("2000-01-01", "2000-01-03")) ) }) test_that("inclusiveness of from/to is respected", { rrule <- daily(since = "1970-01-01", until = "1970-01-03") %>% recur_on_mday(c(1, 3)) from <- "1970-01-01" to <- "1970-01-03" expect_identical( alma_seq(from, to, rrule, inclusive = TRUE), new_date(1) ) expect_identical( alma_seq(from, to, rrule, inclusive = FALSE), new_date(c(0, 1, 2)) ) })
nullspace<-function(A) { if(! is.matrix(A)) stop("A not matrix") n<-nrow(A) p<-ncol(A) if(n >= p) stop("no. of rows greater or equal to the no. of columns") s<-svd(A, nu=n, nv=p) k<-0 for(i in 1:n) { if (s$d[i] >1e-6) k<-k+1 } v2<-NULL for(i in (k+1):p) v2<-cbind(v2,s$v[,i]) return(v2) }
library("graphsim") library("igraph") context("Make Adjacency Matrix") test_that("Generate adjacency matrix from graph structure", { graph_test1_edges <- rbind(c("A", "B"), c("B", "C"), c("B", "D")) graph_test1 <- graph.edgelist(graph_test1_edges, directed = TRUE) adjacency_matrix1 <- make_adjmatrix_graph(graph_test1) expect_equal(isSymmetric(adjacency_matrix1), TRUE) expect_equal(sum(diag(adjacency_matrix1)), 0) expect_equal(nrow(adjacency_matrix1), length(V(graph_test1))) expect_equal(ncol(adjacency_matrix1), length(V(graph_test1))) expect_equal(sum(adjacency_matrix1), length(E(graph_test1))*2) expect_equal(all(is.matrix(adjacency_matrix1)), TRUE) expect_true(all(adjacency_matrix1 == cbind(c(0, 1, 0, 0), c(1, 0, 1, 1), c(0, 1, 0, 0), c(0, 1, 0, 0)))) })
library(tidyverse) locales <- readr::read_rds(file = "data-raw/locales.RDS")
fmi_spectra <- function ( parameters, n_cores = 1 ) { f <- function(parameters) { p_turbulence <- eseis::model_turbulence(d_s = parameters$d_s, s_s = parameters$s_s, r_s = parameters$r_s, h_w = parameters$h_w, w_w = parameters$w_w, a_w = parameters$a_w, f = c(parameters$f_min, parameters$f_max), r_0 = parameters$r_0, f_0 = parameters$f_0, q_0 = parameters$q_0, v_0 = parameters$v_0, p_0 = parameters$p_0, n_0 = c(parameters$n_0_a, parameters$n_0_b), res = parameters$res, eseis = FALSE) p_bedload <- eseis::model_bedload(d_s = parameters$d_s, s_s = parameters$s_s, r_s = parameters$r_s, q_s = parameters$q_s, h_w = parameters$h_w, w_w = parameters$w_w, a_w = parameters$a_w, f = c(parameters$f_min, parameters$f_max), r_0 = parameters$r_0, f_0 = parameters$f_0, q_0 = parameters$q_0, e_0 = parameters$e_0, v_0 = parameters$v_0, x_0 = parameters$p_0, n_0 = parameters$n_0_a, res = parameters$res, eseis = FALSE) p_combined <- p_turbulence p_combined$spectrum <- p_turbulence$spectrum + p_bedload$spectrum p_turbulence_log <- p_turbulence p_bedload_log <-p_bedload p_combined_log <- p_combined p_turbulence_log$spectrum <- 10 * log10(p_turbulence$spectrum) p_bedload_log$spectrum <- 10 * log10(p_bedload$spectrum) p_combined_log$spectrum <- 10 * log10(p_combined$spectrum) return(list(pars = parameters, frequency = p_combined_log$frequency, spectrum = p_combined_log$spectrum)) } if(n_cores > 1) { n_cores_system <- parallel::detectCores() n_cores <- ifelse(test = n_cores > n_cores_system, yes = n_cores_system, no = n_cores) cl <- parallel::makeCluster(n_cores) spectra <- parallel::parLapply(cl = cl, X = parameters, fun = f) parallel::stopCluster(cl = cl) } else { spectra <- lapply(X = parameters, FUN = f) } return(spectra) }
suppressWarnings(RNGversion("3.5.2")) library("partykit") stopifnot(require("party")) set.seed(29) airq <- airquality[complete.cases(airquality),] mtry <- ncol(airq) - 1L ntree <- 25 cf_partykit <- partykit::cforest(Ozone ~ ., data = airq, ntree = ntree, mtry = mtry) w <- do.call("cbind", cf_partykit$weights) cf_party <- party::cforest(Ozone ~ ., data = airq, control = party::cforest_unbiased(ntree = ntree, mtry = mtry), weights = w) p_partykit <- predict(cf_partykit) p_party <- predict(cf_party) stopifnot(max(abs(p_partykit - p_party)) < sqrt(.Machine$double.eps)) prettytree(cf_party@ensemble[[1]], inames = names(airq)[-1]) party(cf_partykit$nodes[[1]], data = model.frame(cf_partykit)) v_party <- do.call("rbind", lapply(1:5, function(i) party::varimp(cf_party))) v_partykit <- do.call("rbind", lapply(1:5, function(i) partykit::varimp(cf_partykit))) summary(v_party) summary(v_partykit) party::varimp(cf_party, conditional = TRUE) partykit::varimp(cf_partykit, conditional = TRUE) set.seed(29) mtry <- ncol(iris) - 1L ntree <- 25 cf_partykit <- partykit::cforest(Species ~ ., data = iris, ntree = ntree, mtry = mtry) w <- do.call("cbind", cf_partykit$weights) cf_party <- party::cforest(Species ~ ., data = iris, control = party::cforest_unbiased(ntree = ntree, mtry = mtry), weights = w) p_partykit <- predict(cf_partykit, type = "prob") p_party <- do.call("rbind", treeresponse(cf_party)) stopifnot(max(abs(unclass(p_partykit) - unclass(p_party))) < sqrt(.Machine$double.eps)) prettytree(cf_party@ensemble[[1]], inames = names(iris)[-5]) party(cf_partykit$nodes[[1]], data = model.frame(cf_partykit)) v_party <- do.call("rbind", lapply(1:5, function(i) party::varimp(cf_party))) v_partykit <- do.call("rbind", lapply(1:5, function(i) partykit::varimp(cf_partykit, risk = "mis"))) summary(v_party) summary(v_partykit) party::varimp(cf_party, conditional = TRUE) partykit::varimp(cf_partykit, risk = "misclass", conditional = TRUE) set.seed(29) cf <- partykit::cforest(dist ~ speed, data = cars, ntree = 100) pr <- predict(cf, newdata = cars[1,,drop = FALSE], type = "response", scale = TRUE) w <- predict(cf, newdata = cars[1,,drop = FALSE], type = "weights") stopifnot(isTRUE(all.equal(pr, sum(w * cars$dist) / sum(w), check.attributes = FALSE))) nd1 <- predict(cf, newdata = cars[1,,drop = FALSE], type = "node") nd <- predict(cf, newdata = cars, type = "node") lw <- cf$weights np <- vector(mode = "list", length = length(lw)) m <- numeric(length(lw)) for (i in 1:length(lw)) { np[[i]] <- tapply(lw[[i]] * cars$dist, nd[[i]], sum) / tapply(lw[[i]], nd[[i]], sum) m[i] <- np[[i]][as.character(nd1[i])] } stopifnot(isTRUE(all.equal(mean(m), sum(w * cars$dist) / sum(w)))) if(.Platform$OS.type == "unix") { RNGkind("L'Ecuyer-CMRG") v1 <- partykit::varimp(cf_partykit, risk = "misclass", conditional = TRUE, cores = 2) v2 <- partykit::varimp(cf_partykit, risk = "misclass", conditional = TRUE, cores = 2) stopifnot(all.equal(v1, v2)) } cf_partykit <- partykit::cforest(Species ~ ., data = iris, ntree = ntree, mtry = 4) w <- do.call("cbind", cf_partykit$weights) cf_2 <- partykit::cforest(Species ~ ., data = iris, ntree = ntree, mtry = 4, weights = w) stopifnot(max(abs(predict(cf_2, type = "prob") - predict(cf_partykit, type = "prob"))) < sqrt(.Machine$double.eps))
HELPrct %>% select(contains("risk")) %>% head(2)
fadalara_no_paral <- function(data, seed, N, m, numArchoid, numRep, huge, prob, type_alg = "fada", compare = FALSE, verbose = TRUE, PM, vect_tol = c(0.95, 0.9, 0.85), alpha = 0.05, outl_degree = c("outl_strong", "outl_semi_strong", "outl_moderate"), method = "adjbox", multiv, frame){ nbasis <- dim(data)[2] nvars <- dim(data)[3] n <- nrow(data) rss_aux <- Inf rand_obs_iter <- c() for (i in 1:N) { if (verbose) { print("Iteration:") print(i) } if (is.null(rand_obs_iter)) { set.seed(seed) rand_obs_si <- sample(1:n, size = m) }else{ set.seed(seed) rand_obs_si <- sample(setdiff(1:n, rand_obs_iter), size = m - numArchoid) rand_obs_si <- c(rand_obs_si, k_aux) } rand_obs_iter <- c(rand_obs_iter, rand_obs_si) if (multiv) { si <- apply(data, 2:3, function(x) x[rand_obs_si]) }else{ si <- data[rand_obs_si,] } if (type_alg == "fada") { fada_si <- do_fada(si, numArchoid, numRep, huge, compare, PM, vect_tol, alpha, outl_degree, method, prob) }else if (type_alg == "fada_rob") { if (multiv) { if (frame) { g1 <- t(si[,,1]) G <- dim(si)[3] for (i in 2:G) { g12 <- t(si[,,i]) g1 <- rbind(g1, g12) } X <- t(g1) si_frame <- frame_in_r(X) si <- apply(si, 2:3, function(x) x[si_frame]) rand_obs_si <- rand_obs_si[si_frame] } fada_si <- do_fada_multiv_robust(si, numArchoid, numRep, huge, prob, compare, PM, method) }else{ if (frame) { si_frame <- frame_in_r(si) si <- si[si_frame,] rand_obs_si <- rand_obs_si[si_frame] } fada_si <- do_fada_robust(si, numArchoid, numRep, huge, prob, compare, PM, vect_tol, alpha, outl_degree, method) } }else{ stop("Algorithms available are 'fada' or 'fada_rob'.") } k_si <- fada_si$cases alphas_si <- fada_si$alphas colnames(alphas_si) <- rownames(si) if (multiv) { rss_si <- do_alphas_rss_multiv(data, si, huge, k_si, rand_obs_si, alphas_si, type_alg, PM, prob, nbasis, nvars) }else{ rss_si <- do_alphas_rss(data, si, huge, k_si, rand_obs_si, alphas_si, type_alg, PM, prob) } if (verbose) { print("Previous rss value:") print(rss_aux) print("Current rss value:") print(rss_si[[1]]) } if (rss_si[[1]] < rss_aux) { rss_aux <- rss_si[[1]] k_aux <- which(rownames(data) %in% rownames(si)[k_si]) alphas_aux <- rss_si[[3]] resid_aux <- rss_si[[2]] } } if (method == "adjbox") { if (multiv) { seq_pts <- sort(c(seq(1, nbasis*nvars, by = nbasis), rev(nbasis*nvars - nbasis *(1:(nvars-1))), nbasis*nvars)) odd_pos <- seq(1, length(seq_pts), 2) r_list <- list() for (i in odd_pos) { r_list[[i]] <- apply(resid_aux[seq_pts[i]:seq_pts[i+1],], 2, int_prod_mat_funct, PM = PM) } r_list1 <- r_list[odd_pos] aux <- Reduce(`+`, r_list1) resid_vect <- sqrt(aux) }else{ resid_vect <- apply(resid_aux, 2, int_prod_mat_sq_funct, PM = PM) } outl_boxb <- boxB(x = resid_vect, k = 1.5, method = method) outl <- which(resid_vect > outl_boxb$fences[2]) if (multiv) { local_rel_imp <- sapply(1:nvars, function(i, j, x, y) round((x[[i]][j]/y[j]) * 100, 2), outl, r_list1, aux) if (length(outl) > 0) { if (length(outl) == 1) { local_rel_imp <- t(local_rel_imp) } dimnames(local_rel_imp) <- list(as.character(outl), paste("V", 1:nvars, sep = "")) } margi_rel_imp <- sapply(1:nvars, function(i, j, x) round((x[[i]][j]/sum(x[[i]])) * 100, 2), outl, r_list1) if (length(outl) > 0) { if (length(outl) == 1) { margi_rel_imp <- t(margi_rel_imp) } dimnames(margi_rel_imp) <- list(as.character(outl), paste("V", 1:nvars, sep = "")) } }else{ local_rel_imp <- NULL margi_rel_imp <- NULL } }else if (method == "toler" & multiv == FALSE) { resid_vect <- apply(resid_aux, 2, int_prod_mat_funct, PM = PM) outl <- do_outl_degree(vect_tol, resid_vect, alpha, paste(outl_degree, "_non_rob", sep = "")) } return(list(cases = k_aux, rss = rss_aux, outliers = outl, alphas = alphas_aux, local_rel_imp = local_rel_imp, margi_rel_imp = margi_rel_imp)) }
test_that("simFossilRecord doesn't return extant taxa in extinct-only simulations", { testthat::skip_on_cran() testthat::skip_on_travis() library(paleotree) set.seed(1) res <- simFossilRecord( p = 0.1, q = 0.1, r = 0.1, nTotalTaxa = 10, nExtant = 0, nruns = 1000, plot = TRUE ) anyLive <- any(sapply(res, function(z) any(sapply(z,function(x) x[[1]][5] == 1))) ) if(anyLive){ stop("Runs have extant taxa under conditioning for none?") } expect_false(anyLive) })
tm1_api_request <- function(tm1_connection, url, body ="", type = "GET") { tm1_auth_key <- tm1_connection$key url <- gsub(" ", "%20", url, fixed=TRUE) tm1_process_return <- do.call(get(type, asNamespace("httr")), list(url, httr::add_headers("Authorization" = tm1_auth_key), httr::add_headers("Content-Type" = "application/json"), body = body)) tm1_return <- jsonlite::fromJSON(httr::content(tm1_process_return, "text")) return(tm1_return) }
download.MERRA <- function(outfolder, start_date, end_date, lat.in, lon.in, overwrite = FALSE, verbose = FALSE, ...) { dates <- seq.Date(as.Date(start_date), as.Date(end_date), "1 day") dir.create(outfolder, showWarnings = FALSE, recursive = TRUE) for (i in seq_along(dates)) { date <- dates[[i]] PEcAn.logger::logger.debug(paste0( "Downloading ", as.character(date), " (", i, " of ", length(dates), ")" )) get_merra_date(date, lat.in, lon.in, outfolder, overwrite = overwrite) } start_year <- lubridate::year(start_date) end_year <- lubridate::year(end_date) ylist <- seq(start_year, end_year) nyear <- length(ylist) results <- data.frame( file = character(nyear), host = "", mimetype = "", formatname = "", startdate = "", enddate = "", dbfile.name = "MERRA", stringsAsFactors = FALSE ) for (i in seq_len(nyear)) { year <- ylist[i] baseday <- paste0(year, "-01-01T00:00:00Z") y_startdate <- pmax(ISOdate(year, 01, 01, 0, tz = "UTC"), lubridate::as_datetime(start_date)) y_enddate <- pmin(ISOdate(year, 12, 31, 23, 59, 59, tz = "UTC"), lubridate::as_datetime(paste(end_date, "23:59:59Z"))) timeseq <- as.numeric(difftime( seq(y_startdate, y_enddate, "hours"), baseday, tz = "UTC", units = "days" )) ntime <- length(timeseq) loc.file <- file.path(outfolder, paste("MERRA", year, "nc", sep = ".")) results$file[i] <- loc.file results$host[i] <- PEcAn.remote::fqdn() results$startdate[i] <- paste0(year, "-01-01 00:00:00") results$enddate[i] <- paste0(year, "-12-31 23:59:59") results$mimetype[i] <- "application/x-netcdf" results$formatname[i] <- "CF Meteorology" lat <- ncdf4::ncdim_def(name = "latitude", units = "degree_north", vals = lat.in, create_dimvar = TRUE) lon <- ncdf4::ncdim_def(name = "longitude", units = "degree_east", vals = lon.in, create_dimvar = TRUE) time <- ncdf4::ncdim_def(name = "time", units = paste("Days since ", baseday), vals = timeseq, create_dimvar = TRUE, unlim = TRUE) dim <- list(lat, lon, time) var_list <- list() for (dat in list(merra_vars, merra_pres_vars, merra_flux_vars, merra_lfo_vars)) { for (j in seq_len(nrow(dat))) { var_list <- c(var_list, list(ncdf4::ncvar_def( name = dat[j, ][["CF_name"]], units = dat[j, ][["units"]], dim = dim, missval = -999 ))) } } var_list <- c(var_list, list( ncdf4::ncvar_def( name = "surface_direct_downwelling_shortwave_flux_in_air", units = "W/m2", dim = dim, missval = -999 ), ncdf4::ncvar_def( name = "surface_diffuse_downwelling_shortwave_flux_in_air", units = "W/m2", dim = dim, missval = -999 ) )) if (file.exists(loc.file)) { PEcAn.logger::logger.warn( "Target file ", loc.file, " already exists.", "It will be overwritten." ) } loc <- ncdf4::nc_create(loc.file, var_list) on.exit(ncdf4::nc_close(loc), add = TRUE) dates_yr <- dates[lubridate::year(dates) == year] for (d in seq_along(dates_yr)) { date <- dates_yr[[d]] end <- d * 24 start <- end - 23 mostfile <- file.path(outfolder, sprintf("merra-most-%s.nc", as.character(date))) nc <- ncdf4::nc_open(mostfile) for (r in seq_len(nrow(merra_vars))) { x <- ncdf4::ncvar_get(nc, merra_vars[r,][["MERRA_name"]]) ncdf4::ncvar_put(loc, merra_vars[r,][["CF_name"]], x, start = c(1, 1, start), count = c(1, 1, 24)) } ncdf4::nc_close(nc) presfile <- file.path(outfolder, sprintf("merra-pres-%s.nc", as.character(date))) nc <- ncdf4::nc_open(presfile) for (r in seq_len(nrow(merra_pres_vars))) { x <- ncdf4::ncvar_get(nc, merra_pres_vars[r,][["MERRA_name"]]) ncdf4::ncvar_put(loc, merra_pres_vars[r,][["CF_name"]], x, start = c(1, 1, start), count = c(1, 1, 24)) } ncdf4::nc_close(nc) fluxfile <- file.path(outfolder, sprintf("merra-flux-%s.nc", as.character(date))) nc <- ncdf4::nc_open(fluxfile) for (r in seq_len(nrow(merra_flux_vars))) { x <- ncdf4::ncvar_get(nc, merra_flux_vars[r,][["MERRA_name"]]) ncdf4::ncvar_put(loc, merra_flux_vars[r,][["CF_name"]], x, start = c(1, 1, start), count = c(1, 1, 24)) } lfofile <- file.path(outfolder, sprintf("merra-lfo-%s.nc", as.character(date))) nc <- ncdf4::nc_open(lfofile) for (r in seq_len(nrow(merra_lfo_vars))) { x <- ncdf4::ncvar_get(nc, merra_lfo_vars[r,][["MERRA_name"]]) ncdf4::ncvar_put(loc, merra_lfo_vars[r,][["CF_name"]], x, start = c(1, 1, start), count = c(1, 1, 24)) } ncdf4::nc_close(nc) } sw_diffuse <- ncdf4::ncvar_get(loc, "surface_diffuse_downwelling_photosynthetic_radiative_flux_in_air") + ncdf4::ncvar_get(loc, "surface_diffuse_downwelling_nearinfrared_radiative_flux_in_air") ncdf4::ncvar_put(loc, "surface_diffuse_downwelling_shortwave_flux_in_air", sw_diffuse, start = c(1, 1, 1), count = c(1, 1, -1)) sw_direct <- ncdf4::ncvar_get(loc, "surface_direct_downwelling_photosynthetic_radiative_flux_in_air") + ncdf4::ncvar_get(loc, "surface_direct_downwelling_nearinfrared_radiative_flux_in_air") ncdf4::ncvar_put(loc, "surface_direct_downwelling_shortwave_flux_in_air", sw_direct, start = c(1, 1, 1), count = c(1, 1, -1)) } return(results) } get_merra_date <- function(date, latitude, longitude, outdir, overwrite = FALSE) { date <- as.character(date) dpat <- "([[:digit:]]{4})-([[:digit:]]{2})-([[:digit:]]{2})" year <- as.numeric(gsub(dpat, "\\1", date)) month <- as.numeric(gsub(dpat, "\\2", date)) day <- as.numeric(gsub(dpat, "\\3", date)) dir.create(outdir, showWarnings = FALSE, recursive = TRUE) version <- if (year >= 2011) { 400 } else if (year >= 2001) { 300 } else { 200 } base_url <- "https://goldsmr4.gesdisc.eosdis.nasa.gov/opendap/MERRA2" lat_grid <- seq(-90, 90, 0.5) lon_grid <- seq(-180, 180, 0.625) ilat <- which.min(abs(lat_grid - latitude)) ilon <- which.min(abs(lon_grid - longitude)) idxstring <- sprintf("[0:1:23][%d][%d]", ilat, ilon) url <- glue::glue( "{base_url}/{merra_prod}/{year}/{sprintf('%02d', month)}/", "MERRA2_{version}.{merra_file}.", "{year}{sprintf('%02d', month)}{sprintf('%02d', day)}.nc4.nc4" ) qvars <- sprintf("%s%s", merra_vars$MERRA_name, idxstring) qstring <- paste(qvars, collapse = ",") outfile <- file.path(outdir, sprintf("merra-most-%d-%02d-%02d.nc", year, month, day)) if (overwrite || !file.exists(outfile)) { req <- httr::GET( paste(url, qstring, sep = "?"), httr::authenticate(user = "pecanproject", password = "Data4pecan3"), httr::write_disk(outfile, overwrite = TRUE) ) } url <- glue::glue( "{base_url}/{merra_pres_prod}/{year}/{sprintf('%02d', month)}/", "MERRA2_{version}.{merra_pres_file}.", "{year}{sprintf('%02d', month)}{sprintf('%02d', day)}.nc4.nc4" ) qvars <- sprintf("%s%s", merra_pres_vars$MERRA_name, idxstring) qstring <- paste(qvars, collapse = ",") outfile <- file.path(outdir, sprintf("merra-pres-%d-%02d-%02d.nc", year, month, day)) if (overwrite || !file.exists(outfile)) { req <- httr::GET( paste(url, qstring, sep = "?"), httr::authenticate(user = "pecanproject", password = "Data4pecan3"), httr::write_disk(outfile, overwrite = TRUE) ) } url <- glue::glue( "{base_url}/{merra_flux_prod}/{year}/{sprintf('%02d', month)}/", "MERRA2_{version}.{merra_flux_file}.", "{year}{sprintf('%02d', month)}{sprintf('%02d', day)}.nc4.nc4" ) qvars <- sprintf("%s%s", merra_flux_vars$MERRA_name, idxstring) qstring <- paste(qvars, collapse = ",") outfile <- file.path(outdir, sprintf("merra-flux-%d-%02d-%02d.nc", year, month, day)) if (overwrite || !file.exists(outfile)) { req <- robustly(httr::GET, n = 10)( paste(url, qstring, sep = "?"), httr::authenticate(user = "pecanproject", password = "Data4pecan3"), httr::write_disk(outfile, overwrite = TRUE) ) } url <- glue::glue( "{base_url}/{merra_lfo_prod}/{year}/{sprintf('%02d', month)}/", "MERRA2_{version}.{merra_lfo_file}.", "{year}{sprintf('%02d', month)}{sprintf('%02d', day)}.nc4.nc4" ) qvars <- sprintf("%s%s", merra_lfo_vars$MERRA_name, idxstring) qstring <- paste(qvars, collapse = ",") outfile <- file.path(outdir, sprintf("merra-lfo-%d-%02d-%02d.nc", year, month, day)) if (overwrite || !file.exists(outfile)) { req <- robustly(httr::GET, n = 10)( paste(url, qstring, sep = "?"), httr::authenticate(user = "pecanproject", password = "Data4pecan3"), httr::write_disk(outfile, overwrite = TRUE) ) } } merra_prod <- "M2T1NXFLX.5.12.4" merra_file <- "tavg1_2d_flx_Nx" merra_vars <- tibble::tribble( ~CF_name, ~MERRA_name, ~units, "air_temperature", "TLML", "Kelvin", "eastward_wind", "ULML", "m/s", "northward_wind", "VLML", "m/s", "specific_humidity", "QSH", "g/g", "precipitation_flux", "PRECTOT", "kg/m2/s", "surface_diffuse_downwelling_nearinfrared_radiative_flux_in_air", "NIRDF", "W/m2", "surface_direct_downwelling_nearinfrared_radiative_flux_in_air", "NIRDR", "W/m2" ) merra_pres_prod <- "M2I1NXASM.5.12.4" merra_pres_file <- "inst1_2d_asm_Nx" merra_pres_vars <- tibble::tribble( ~CF_name, ~MERRA_name, ~units, "air_pressure", "PS", "Pascal", ) merra_flux_prod <- "M2T1NXRAD.5.12.4" merra_flux_file <- "tavg1_2d_rad_Nx" merra_flux_vars <- tibble::tribble( ~CF_name, ~MERRA_name, ~units, "surface_downwelling_longwave_flux_in_air", "LWGAB", "W/m2", "surface_downwelling_shortwave_flux_in_air", "SWGDN", "W/m2" ) merra_lfo_prod <- "M2T1NXLFO.5.12.4" merra_lfo_file <- "tavg1_2d_lfo_Nx" merra_lfo_vars <- tibble::tribble( ~CF_name, ~MERRA_name, ~units, "surface_diffuse_downwelling_photosynthetic_radiative_flux_in_air", "PARDF", "W/m2", "surface_direct_downwelling_photosynthetic_radiative_flux_in_air", "PARDR", "W/m2" )
clvarselhlfwd <- function(X, G = 1:9, emModels1 = c("E","V"), emModels2 = mclust.options("emModelNames"), samp = FALSE, sampsize = 2000, hcModel = "VVV", allow.EEE = TRUE, forcetwo = TRUE, BIC.upper = 0, BIC.lower = -10, itermax = 100, verbose = interactive()) { X <- as.matrix(X) n <- nrow(X) d <- ncol(X) G <- setdiff(G, 1) if(samp) { sub <- sample(1:n, min(sampsize,n), replace = FALSE) } else { sub <- seq.int(1,n) } if(verbose) cat(paste("iter 1\n+ adding step\n")) maxBIC <- BICdiff <- oneBIC <- rep(NA,d) ModelG <- vector(mode = "list", length = d) for(i in 1:d) { xBIC <- NULL try(xBIC <- Mclust(X[,i], G = G, modelNames = emModels1, initialization = list(subset = sub), verbose = FALSE), silent = TRUE) if(is.null(xBIC)) try(xBIC <- Mclust(X[,i], G = G, modelNames = emModels1), silent = TRUE) if((allow.EEE) & sum(is.finite(xBIC$BIC))==0) try(xBIC <- Mclust(X[,i], G = G, modelNames = emModels1, initialization = list(hcPairs = hcE(X[sub,i]), subset = sub), verbose = FALSE), silent = TRUE) if(sum(is.finite(xBIC$BIC))==0) maxBIC[i] <- NA else maxBIC[i] <- max(xBIC$BIC[is.finite(xBIC$BIC)]) try(oneBIC[i] <- Mclust(X[,i], G = 1, modelNames = emModels1, initialization = list(subset = sub), verbose = FALSE)$BIC[1], silent = TRUE) BICdiff[i] <- c(maxBIC[i] - oneBIC[i]) ModelG[[i]] <- c(xBIC$modelName, xBIC$G) } m <- max(BICdiff[is.finite(BICdiff)]) arg <- which(BICdiff==m,arr.ind=TRUE)[1] S <- X[,arg,drop=FALSE] BICS <- maxBIC[arg] temp <- order(BICdiff[-arg], decreasing = TRUE) NS <- as.matrix(X[,-arg]) NS <- NS[,temp,drop=FALSE] info <- data.frame(Var = colnames(S), BIC = BICS, BICdiff = BICdiff[arg], Step = "Add", Decision = "Accepted", Model = ModelG[[arg]][1], G = ModelG[[arg]][2], stringsAsFactors = FALSE) info$BIC <- as.numeric(info$BIC) info$BICdiff <- as.numeric(info$BICdiff) if(verbose) { print(info[,c(1,3:5),drop=FALSE]) cat(paste("iter 2\n+ adding step\n")) } depBIC <- cindepBIC <- cdiff <- rep(NA, ncol(NS)) ModelG <- vector(mode = "list", length = ncol(NS)) crit <- -Inf i <- 0 while( (crit <= BIC.upper) & (i < ncol(NS)) ) { i <- i+1 regBIC <- BICreg(y = NS[,i], x = S) sBIC <- NULL try(sBIC <- Mclust(cbind(S,NS[,i]), G = G, modelNames = emModels2, initialization = list(hcPairs = hc(hcModel, data = cbind(S,NS[,i])[sub,]), subset = sub), verbose = FALSE), silent = TRUE) if((allow.EEE) & sum(is.finite(sBIC$BIC))==0) try(sBIC <- Mclust(cbind(S,NS[,i]), G = G, modelNames = emModels2, initialization = list(hcPairs = hc("EEE", data = cbind(S,NS[,i])[sub,]), subset = sub), verbose = FALSE), silent = TRUE) if(sum(is.finite(sBIC$BIC))>0) depBIC[i] <- max(sBIC$BIC[is.finite(sBIC$BIC)]) cindepBIC[i] <- regBIC + BICS cdiff[i] <- depBIC[i] - cindepBIC[i] if(!is.finite(cdiff[i])) cdiff[i] <- BIC.upper crit <- cdiff[i] ModelG[[i]] <- c(sBIC$modelName, sBIC$G) } depBIC <- depBIC[1:i] cindepBIC <- cindepBIC[1:i] cdiff <- cdiff[1:i] if(cdiff[i] > BIC.upper) { k <- c(colnames(S),colnames(NS)[i]) S <- cbind(S,NS[,i]) colnames(S) <- k BICS <- depBIC[i] info <- rbind(info, c(colnames(NS)[i], BICS, cdiff[i], "Add", "Accepted", ModelG[[i]])) ns <- s <- NULL if(i < ncol(NS)) ns <- seq(i+1, ncol(NS)) if(i > 1) s <- seq(i-1)[which(cdiff[-i] > BIC.lower)] ind <- c(s,ns) if(!is.null(ind)) { nks <- c(colnames(NS)[ind]) NS <- as.matrix(NS[,ind]) colnames(NS) <- nks } else { NS <- NULL } } else { if((cdiff[i] < BIC.upper) & (forcetwo)) { m <- max(cdiff[is.finite(cdiff)]) i <- which(cdiff==m,arr.ind=TRUE)[1] k <- c(colnames(S),colnames(NS)[i]) S <- cbind(S,NS[,i]) colnames(S) <- k BICS <- depBIC[i] info <- rbind(info, c(colnames(NS)[i], BICS, cdiff[i], "Add", "Accepted", ModelG[[i]])) nks <- c(colnames(NS)[-i]) NS <- as.matrix(NS[,-i]) temp <- cdiff[-i] if(sum(temp > BIC.lower) != 0) { NS <- as.matrix(NS[,c(which(temp > BIC.lower))]) colnames(NS) <- nks[c(which(temp > BIC.lower))] } else { NS <- NULL } } else { m <- max(cdiff[is.finite(cdiff)]) i <- which(cdiff==m,arr.ind=TRUE)[1] info <- rbind(info, c(colnames(NS)[i], BICS, cdiff[i], "Add", "Rejected", ModelG[[i]])) } } info$BIC <- as.numeric(info$BIC) info$BICdiff <- as.numeric(info$BICdiff) if(verbose) print(info[2,c(1,3:5),drop=FALSE]) criterion <- 1 iter <- 0 while((criterion == 1) & (iter < itermax)) { iter <- iter+1 check1 <- colnames(S) if(verbose) cat(paste("iter", iter+2, "\n")) if(verbose) cat("+ adding step\n") if((NCOL(NS) != 0 & !is.null(ncol(NS))) & (ncol(S) == 0) || (is.null(ncol(S))) ) { depBIC <- 0 DepBIC <- NULL crit <- -10 cdiff <- 0 Cdiff <- NULL oneBIC <- rep(NA,d) ModelG <- vector(mode = "list", length = d) i <- 0 crit <- -10 while((crit <= BIC.upper) & (i < ncol(NS))) { xBIC <- NULL i <- i+1 try(xBIC <- Mclust(X[,i], G = G, modelNames = emModels1, initialization = list(subset = sub), verbose = FALSE), silent = TRUE) if((allow.EEE) & sum(is.finite(xBIC$BIC))==0) try(xBIC <- Mclust(X[,i], G = G, modelNames = emModels1, initialization = list(hcPairs = hcE(X[sub,i]), subset = sub), verbose = FALSE), silent = TRUE) if(sum(is.finite(xBIC$BIC)) == 0) depBIC <- NA else depBIC <- max(xBIC$BIC[is.finite(xBIC$BIC)]) DepBIC <- c(DepBIC,depBIC) try(oneBIC <- Mclust(X[,i], G = 1, modelNames = "V", verbose = FALSE)$BIC[1], silent = TRUE) cdiff <- c(depBIC - oneBIC) if(!is.finite(cdiff)) cdiff <- BIC.upper Cdiff <- c(Cdiff,cdiff) crit <- cdiff ModelG[[i]] <- c(xBIC$modelName, xBIC$G) } if(cdiff > BIC.upper) { k <- c(colnames(NS)[i]) S <- as.matrix(NS[,i]) colnames(S) <- k BICS <- depBIC info <- rbind(info, c(colnames(NS)[i], BICS, cdiff, "Add", "Accepted", ModelG[[i]])) ns <- s <- NULL if(i < ncol(NS)) ns <- seq(i+1, ncol(NS)) if(i > 1) s <- seq(i-1)[which(Cdiff[-i] > BIC.lower)] ind <- c(s,ns) if(!is.null(ind)) { nks <- c(colnames(NS)[ind]) NS <- as.matrix(NS[,ind]) colnames(NS)<-nks } else { NS <- NULL } } else { m <- max(Cdiff[is.finite(Cdiff)]) i <- which(Cdiff==m,arr.ind=TRUE)[1] info <- rbind(info, c(colnames(NS)[i], BICS, Cdiff[i], "Add", "Rejected", ModelG[[i]])) ind <- seq(ncol(NS))[which(Cdiff > BIC.lower)] if(!is.null(ind)) { k <- colnames(NS)[ind] NS <- as.matrix(NS[,ind]) colnames(NS) <- k } else { NS <- NULL } } } else { if((NCOL(NS) != 0) & !is.null(ncol(NS))) { depBIC <- cindepBIC <- cdiff <- rep(NA, ncol(NS)) ModelG <- vector(mode = "list", length = ncol(NS)) crit <- -Inf i <- 0 while(crit <= BIC.upper & i < ncol(NS)) { sBIC <- NULL i <- i+1 regBIC <- BICreg(y = NS[,i], x = S) try(sBIC <- Mclust(cbind(S,NS[,i]), G = G, modelNames = emModels2, initialization = list(hcPairs = hc(hcModel, data = cbind(S,NS[,i])[sub,]), subset = sub), verbose = FALSE), silent = TRUE) if((allow.EEE) & (sum(is.finite(sBIC$BIC))==0)) try(sBIC <- Mclust(cbind(S,NS[,i]), G = G, modelNames = emModels2, initialization = list(hcPairs = hc("EEE", data = cbind(S,NS[,i])[sub,]), subset = sub), verbose = FALSE), silent = TRUE) if(sum(is.finite(sBIC$BIC))>0) depBIC[i] <- max(sBIC$BIC[is.finite(sBIC$BIC)]) cindepBIC[i] <- regBIC + BICS cdiff[i] <- depBIC[i] - cindepBIC[i] if(!is.finite(cdiff[i])) cdiff[i] <- BIC.upper crit <- cdiff[i] ModelG[[i]] <- c(sBIC$modelName, sBIC$G) } depBIC <- depBIC[1:i] cindepBIC <- cindepBIC[1:i] cdiff <- cdiff[1:i] if(cdiff[i] > BIC.upper) { k <- c(colnames(S),colnames(NS)[i]) nks <- c(colnames(NS)[-i]) S <- cbind(S,NS[,i]) colnames(S) <- k BICS <- depBIC[i] info <- rbind(info, c(colnames(NS)[i], BICS, cdiff[i], "Add", "Accepted", ModelG[[i]])) ns <- s <- NULL if(i < ncol(NS)) ns <- seq(i+1,ncol(NS)) if(i > 1) s <- seq(i-1)[which(cdiff[-i] > BIC.lower)] ind <- c(s,ns) if(!is.null(ind)) { nks <- colnames(NS)[ind] NS <- as.matrix(NS[,ind]) colnames(NS) <- nks } else { NS <- NULL } } else { m <- max(cdiff[is.finite(cdiff)]) i <- which(cdiff==m,arr.ind=TRUE)[1] info <- rbind(info, c(colnames(NS)[i], depBIC[i], cdiff[i], "Add", "Rejected", ModelG[[i]])) ind <- seq(1,ncol(NS))[which(cdiff > BIC.lower)] if(!is.null(ind)) { k <- colnames(NS)[ind] NS <- as.matrix(NS[,ind]) colnames(NS) <- k } else { NS <- NULL } } } } if(verbose) cat("- removing step\n") if(ncol(S) == 1) { cdiff <- 0 oneBIC <- NA try(oneBIC <- Mclust(S, G = 1, modelNames = "V", initialization = list(subset = sub), verbose = FALSE)$BIC[1], silent = TRUE) cdiff <- BICS - oneBIC if(is.na(cdiff)) cdiff <- BIC.upper if(cdiff <= BIC.upper) { BICS <- NA info <- rbind(info, c(colnames(S), BICS, cdiff, "Remove", "Accepted", oneBIC$modelName, oneBIC$G)) if(cdiff > BIC.lower) { k <- c(colnames(NS),colnames(S)) NS <- cbind(NS,S) colnames(NS) <- k S <- NULL } else { S <- NULL } } else { info <- rbind(info, c(colnames(S), BICS, cdiff, "Remove", "Rejected", oneBIC$modelName, oneBIC$G)) } } else { if(ncol(S) >= 2) { depBIC <- BICS cindepBIC <- rdep <- cdiff <- rep(NA, ncol(S)) ModelG <- vector(mode = "list", length = ncol(S)) crit <- Inf i <- 0 name <- if(ncol(S) > 2) emModels2 else emModels1 while(crit > BIC.upper & (i<ncol(S))) { i <- i+1 regBIC <- BICreg(y = S[,i], x = S[,-i]) sBIC <- NULL try(sBIC <- Mclust(S[,-i], G = G, modelNames = name, initialization = list(hcPairs = hc(hcModel, data = S[sub,-i,drop=FALSE]), subset = sub), verbose = FALSE), silent = TRUE) if(allow.EEE & (ncol(S) >= 3) & sum(is.finite(sBIC$BIC))==0) { try(sBIC <- Mclust(S[,-i], G = G, modelNames = name, initialization = list(hcPairs = hc("EEE", data = S[sub,-i]), subset = sub), verbose = FALSE), silent = TRUE) } else { if((allow.EEE) & (ncol(S)==2) & sum(is.finite(sBIC$BIC))==0) { try(sBIC <- Mclust(as.matrix(S[,-i]), G = G, modelNames = name, initialization = list(hcPairs = hcE(S[sub,-i,drop=FALSE]), subset = sub), verbose = FALSE), silent = TRUE) } } if(sum(is.finite(sBIC$BIC))>0) rdep[i] <- max(sBIC$BIC[is.finite(sBIC$BIC)]) cindepBIC[i] <- regBIC + rdep[i] cdiff[i] <- depBIC - cindepBIC[i] if(!is.finite(cdiff[i])) cdiff[i] <- BIC.upper crit <- cdiff[i] ModelG[[i]] <- c(sBIC$modelName, sBIC$G) } if((cdiff[i] < BIC.upper) & (cdiff[i] > BIC.lower)) { BICS <- rdep[i] info <- rbind(info, c(colnames(S)[i], BICS, cdiff[i], "Remove", "Accepted", ModelG[[i]])) k <- c(colnames(NS),colnames(S)[i]) nk <- colnames(S)[-i] NS <- cbind(NS,S[,i]) S <- as.matrix(S[,-i]) colnames(NS) <- k colnames(S) <- nk } else { if(cdiff[i] < BIC.lower) { BICS <- rdep[i] info <- rbind(info, c(colnames(S)[i], BICS, cdiff[i], "Remove", "Accepted", ModelG[[i]])) nk <- colnames(S)[-i] S <- as.matrix(S[,-i]) colnames(S) <- nk } else { m <- min(cdiff[is.finite(cdiff)]) i <- which(cdiff==m,arr.ind=TRUE)[1] info <- rbind(info, c(colnames(S)[i], rdep[i], cdiff[i], "Remove", "Rejected", ModelG[[i]])) } } } } info$BIC <- as.numeric(info$BIC) info$BICdiff <- as.numeric(info$BICdiff) if(verbose) print(info[seq(nrow(info)-1,nrow(info)),c(1,3:5),drop=FALSE]) check2 <- colnames(S) if(is.null(check2)) { criterion <- 0 } else { if(length(check2) != length(check1)) { criterion <- 1 } else { criterion <- if(sum(check1==check2) != length(check1)) 1 else 0 } } } if(iter >= itermax) warning("Algorithm stopped because maximum number of iterations was reached") info$BIC <- as.numeric(info$BIC) info$BICdiff <- as.numeric(info$BICdiff) info <- info[,c(1,4,2,6,7,3,5),drop=FALSE] colnames(info) <- c("Variable proposed", "Type of step", "BICclust", "Model", "G", "BICdiff", "Decision") varnames <- colnames(X) subset <- sapply(colnames(S), function(x) which(x == varnames)) out <- list(variables = varnames, subset = subset, steps.info = info, search = "headlong", direction = "forward") return(out) }
findEquilibrium <- function(deriv, y0 = NULL, parameters = NULL, system = "two.dim", tol = 1e-16, max.iter = 50, h = 1e-6, plot.it = FALSE, summary = TRUE, state.names = if (system == "two.dim") c("x", "y") else "y") { if (is.null(y0)) { y0 <- locator(n = 1) if (system == "one.dim") { y0 <- y0$y } else { y0 <- c(y0$x, y0$y) } } if (all(!is.vector(y0), !is.matrix(y0))) { stop("y0 is not a vector or matrix, as is required") } if (is.vector(y0)) { y0 <- as.matrix(y0) } if (!(system %in% c("one.dim", "two.dim"))) { stop("system must be set to either \"one.dim\" or \"two.dim\"") } if (all(system == "one.dim", nrow(y0)*ncol(y0) != 1)) { stop("For system = \"one.dim\", y0 should be a matrix where ", "nrow(y0)*ncol(y0) = 1 or a vector of length one") } if (all(system == "two.dim", nrow(y0)*ncol(y0) != 2)) { stop("For system = \"two.dim\", y0 should be a matrix where ", "nrow(y0)*ncol(y0) = 2 or a vector of length two") } if (nrow(y0) < ncol(y0)) { y0 <- t(y0) } if (tol <= 0) { stop("tol is less than or equal to zero") } if (max.iter <= 0) { stop("max.iter is less than or equal to zero") } if (h <= 0) { stop("h is less than or equal to zero") } if (!is.logical(plot.it)) { stop("plot.it must be set to either TRUE or FALSE") } if (!is.logical(summary)){ stop("summary must be set to either TRUE or FALSE") } y <- y0 dim <- nrow(y) for (i in 1:max.iter) { dy <- deriv(0, stats::setNames(y, utils::head(state.names, n = dim)), parameters)[[1]] jacobian <- matrix(0, dim, dim) for (j in 1:dim) { h.vec <- numeric(dim) h.vec[j] <- h jacobian[, j] <- (deriv(0, stats::setNames(y + h.vec, state.names), parameters)[[1]] - deriv(0, stats::setNames(y - h.vec, state.names), parameters)[[1]])/(2*h) } if (sum(dy^2) < tol) { if (system == "one.dim") { discriminant <- jacobian if (discriminant > 0) { classification <- "Unstable" } else if (discriminant < 0) { classification <- "Stable" } else { classification <- "Indeterminate" } } else { A <- jacobian[1, 1] B <- jacobian[1, 2] C <- jacobian[2, 1] D <- jacobian[2, 2] Delta <- A*D - B*C tr <- A + D discriminant <- tr^2 - 4*Delta if (Delta == 0) { classification <- "Indeterminate" } else if (discriminant == 0) { if (tr < 0) { classification <- "Stable node" } else { classification <- "Unstable node" } } else if (Delta < 0) { classification <- "Saddle" } else { if (discriminant > 0) { if (tr < 0) { classification <- "Stable node" } else { classification <- "Unstable node" } } else { if (tr < 0) { classification <- "Stable focus" } else if (tr > 0) { classification <- "Unstable focus" } else { classification <- "Centre" } } } } if (plot.it) { eigenvalues <- eigen(jacobian)$values pchs <- matrix(c(17, 5, 2, 16, 1, 1), 2, 3, byrow = T) pch1 <- 1 + as.numeric(Im(eigenvalues[1]) != 0) pch2 <- 1 + sum(Re(eigenvalues) > 0) old.par <- graphics::par(no.readonly = T) on.exit(graphics::par(old.par)) graphics::par(xpd = T) if (system == "one.dim") { graphics::points(0, y[1], type = "p", pch = pchs[pch1, pch2], cex = 1.5, lwd = 2) } else { graphics::points(y[1], y[2], type = "p", pch = pchs[pch1, pch2], cex = 1.5, lwd = 2) } } if (summary) { if (system == "one.dim") { message("Fixed point at ", state.names," = ", round(y, 5)) message("discriminant = ", round(discriminant, 5), ", classification = ", classification) } else { message("Fixed point at (", paste0(state.names, collapse = ','), ") = ", round(y, 5)) message("tr = ", round(tr, 5), ", Delta = ", round(Delta, 5), ", discriminant = ", round(discriminant, 5), ", classification = ", classification) } } if (system == "one.dim") { return(list(classification = classification, deriv = deriv, discriminant = discriminant, h = h, max.iter = max.iter, parameters = parameters, plot.it = plot.it, summary = summary, system = system, tol = tol, y0 = y0, ystar = y)) } else { return(list(classification = classification, Delta = Delta, deriv = deriv, discriminant = discriminant, eigenvalues = eigen(jacobian)$values, eigenvectors = eigen(jacobian)$vectors, h = h, jacobian = jacobian, max.iter = max.iter, parameters = parameters, plot.it = plot.it, summary = summary, system = system, tol = tol, tr = tr, y0 = y0, ystar = y)) } } y <- y - solve(jacobian, dy) if (summary) { message(i, y) } } if (summary) { message("Convergence failed") } }
getDE_DC_OptimalThreshold = function(t_result, MaxGene, d_r, minSupport) { optimal=data.frame(chi2Value=double(), pValue=double(), tCutOff=double(), rCutOff=double(), obsA=double(), obsB=double(), obsC=double(), obsD=double(), expA=double(), expB=double(), expC=double(), expD=double()) rank_abs_t = rank(t_result$absTScore, ties.method= "min") for (i in 1:MaxGene) { optimal[i,"pValue"]=1 optimal[i,"chi2Value"]=0 optimal[i,"tCutOff"]=0 optimal[i,"rCutOff"]=0 optimal[i,"obsA"]=0 optimal[i,"obsB"]=0 optimal[i,"obsC"]=0 optimal[i,"obsD"]=0 optimal[i,"expA"]=0 optimal[i,"expB"]=0 optimal[i,"expC"]=0 optimal[i,"expD"]=0 rank_one_d_r = rank(d_r[i,], ties.method= "min") for (j in 1:MaxGene) { currentTcutoff = t_result$absTScore[j] currentRcutoff = d_r[i,j] tempA = sum(rank_abs_t >=rank_abs_t[j] & rank_one_d_r >=rank_one_d_r[j]) tempB = MaxGene-rank_one_d_r[j]+1-tempA tempC = MaxGene-rank_abs_t[j]+1-tempA tempD = MaxGene-tempA -tempB-tempC expectedA = (tempA+tempB)*(tempA+tempC)/ MaxGene; expectedB = (tempA+tempB)*(tempB+tempD)/ MaxGene; expectedC = (tempA+tempC)*(tempC+tempD)/ MaxGene; expectedD = (tempD+tempB)*(tempD+tempC)/ MaxGene; if (expectedA<minSupport || expectedB<minSupport|| expectedC<minSupport|| expectedD<minSupport) { next } expectedValues = c(expectedA, expectedB, expectedC, expectedD) observedValues = matrix(c(tempA, tempB, tempC, tempD),nrow=2,ncol=2) chi2stat = sum((observedValues-expectedValues)^2 / expectedValues) if (chi2stat> optimal[i,"chi2Value"]) { pValue = pchisq(chi2stat,1,lower.tail=FALSE) optimal[i,"pValue"]=pValue optimal[i,"chi2Value"]=chi2stat optimal[i,"tCutOff"]=currentTcutoff optimal[i,"rCutOff"]=currentRcutoff optimal[i,"obsA"]=tempA optimal[i,"obsB"]=tempB optimal[i,"obsC"]=tempC optimal[i,"obsD"]=tempD optimal[i,"expA"]=expectedA optimal[i,"expB"]=expectedB optimal[i,"expC"]=expectedC optimal[i,"expD"]=expectedD } } if (i %%1==0) { print(sprintf("Gene id: %d",i)) } } adjustedPValues = getBonferroniPValue(optimal$pValue) adjustedPValues = getFDR(adjustedPValues) optimal$pValue =adjustedPValues return(optimal) }
kmeans.centers.update=function(out,group ,dfunc=func.trim.FM,draw=TRUE ,par.dfunc=list(trim=0.05) ,...){ if (class(out)!="kmeans.fd") stop("Error: incorrect input data") z = out$fdataobj[["data"]] tt = out$fdataobj[["argvals"]] rtt <- out$fdataobj[["rangeval"]] names = out$fdataobj[["names"]] mdist = out$z.dist centers = out$centers xm = centers[["data"]] nr = nrow(z) nc = ncol(z) grupo = group ngroups = length(unique(group)) d = out$d ncl = nrow(xm) for (j in 1:ngroups){ jgrupo <- grupo==j dm=z[jgrupo,] ind=which(jgrupo) if (is.vector(dm) || nrow(dm)<3) {k=j} else { par.dfunc$fdataobj<-centers par.dfunc$fdataobj$data<-dm stat=do.call(dfunc,par.dfunc) } if (is.fdata(stat)) xm[j,]=stat[["data"]] else xm[j,]=stat } centers$data=xm rownames(centers$data) <- paste("center ",1:ngroups,sep="") if (draw){ if (nr==2){ plot(out$fdataobj,main="Center update") for (i in 1:ngroups){points(xm[i,1],xm[i,2],col=i+1,pch=8,cex=1.5)}} else{ plot(out$fdataobj,col="grey",lty=grupo+1,lwd=0.15,cex=0.2,main="Update centers") lines(centers,col=2:(length(grupo+1)),lwd=3,lty=1) }} return(list("centers"=centers,"cluster"=grupo)) }
sim.weightsplot <- function(weights, nei, nx, ny, thresh=0.05, ...) { require(spatstat) if(is.matrix(weights)!=TRUE) stop("weights needs to be a matrix!") if(dim(nei)[2]!=dim(weights)[1]) stop("The row dimension of weights needs to be the same size as the column dimension of nei!") nrow <- nx ncol <- ny w <- apply(weights,1,median) if(ncol(nei)!=((ncol-1)*nrow + (nrow-1)*ncol)) stop("Wrong matrix dimension!") getcoor <- function(image, valbool) { if(is.logical(valbool)) ind <- which(valbool) else ind <- which(image$v==valbool) nx <- ncol(image$v) ny <- nrow(image$v) xind <- ceiling(ind/ny) X <- image$xcol[xind] Y <- image$yrow[ind - (xind-1)*ny] data.frame(X,Y) } nrowim <- 2*nrow - 1 ncolim <- 2*ncol - 1 Z <- matrix(nrow=nrowim, ncol=ncolim) Zim <- im(Z, xcol=1:ncolim, yrow=1:nrowim) inds <- rep(seq(1,ncolim,by=2), times=nrow) + rep((0:(nrow-1))*(2*ncolim), each=ncol) pixelinds <- rep(0, nrowim*ncolim) pixelinds[inds] <- 1:(nrow*ncol) Zim$v <- matrix(ncol=ncolim, nrow=nrowim, data=pixelinds, byrow=TRUE) coorweights <- sapply(as.data.frame(nei), function(x) colMeans(getcoor(Zim, Zim$v %in% x))) coorweights <- coorweights[,w<thresh] Zim[list(x=coorweights[1,], y=coorweights[2,])] <- 1.5 coorzero <- getcoor(Zim, Zim$v==0) Zim[list(x=coorzero$X, y=coorzero$Y)] <- NA coornonweights <- getcoor(Zim, Zim$v!=1.5) Zim[list(x=coornonweights$X, y=coornonweights$Y)] <- 1 coorweights <- getcoor(Zim, Zim$v==1.5) Zim[list(x=coorweights$X, y=coorweights$Y)] <- 2 Zim$v <- Zim$v[1:nrow(Zim$v),1:ncol(Zim$v)] image(Zim$v, x=1:nrow(Zim$v), y=1:ncol(Zim$v), axes=FALSE, xlab="", ylab="", ...) }
getUsedFactorLevels = function(x) { intersect(levels(x), unique(x)) }
PairwiseDistances1 <- function(X, distfun, ...) { if (is.matrix(X)) { n <- dim(X)[1] } if (is.list(X)) { n <- length(X) } distances <- matrix(0, n, n) for (i in 1:(n - 1)) { for (j in (i + 1):n) { d <- distfun(X, Y=NULL, i, j, ...) distances[i,j] <- d distances[j,i] <- d } } return(distances) } PairwiseDistances2 <- function(X, Y, distfun, ...) { if (is.matrix(X)) { n <- dim(X)[1] m <- dim(Y)[1] } if (is.list(X)) { n <- length(X) m <- length(Y) } distances <- matrix(0, n, m) for (i in 1:n) { for (j in 1:m) { d <- distfun(X, Y, i, j, ...) distances[i,j] <- d } } return(distances) } MatrixToList <- function(X) { aux <- X X <- list() for (i in 1:nrow(aux)) { X[[i]] <- aux[i,] } names(X) <- rownames(aux) return(X) } PairwiseARPicDistance <- function(X, Y=NULL, i, j, order.x=NULL, order.y=NULL, permissive=TRUE) { if (! is.list(X)) {X <- MatrixToList(X)} options(show.error.messages = TRUE) if (! is.null(order.x) && dim(order.x)[1] != length(X)) { stop("The length of order.x must be equal to the number of series in the database.")} if (is.null(Y)) { options(show.error.messages = FALSE) d <- diss.AR.PIC(X[[i]], X[[j]], order.x[i, ], order.x[j, ], permissive) } else { if (! is.list(Y)) {Y <- MatrixToList(Y)} if (! is.null(order.y) && dim(order.y)[1] != length(Y)) { stop("The length of order.y must be equal to the number of series in the database Y.")} options(show.error.messages = FALSE) d <- diss.AR.PIC(X[[i]], Y[[j]], order.x[i, ], order.y[j, ], permissive) } options(show.error.messages = TRUE) return(d) } PairwiseARLPCCepsDistance <- function(X, Y=NULL, i, j, k=50, order.x=NULL, order.y=NULL, seasonal.x=NULL, seasonal.y=NULL, permissive=TRUE) { if (! is.list(X)) {X <- MatrixToList(X)} options(show.error.messages = TRUE) if (! is.null(order.x) && dim(order.x)[1] != length(X)) stop("The number of rows of order.x must be equal to the number of series in the database X.") if (is.null(Y)) { if (is.null(seasonal.x)) { seasonal.x[[i]] <- list(order=c(0, 0, 0), period=NA) seasonal.x[[j]] <- list(order=c(0, 0, 0), period=NA) } options(show.error.messages = FALSE) d <- diss.AR.LPC.CEPS(X[[i]], X[[j]], k, order.x[i, ], order.x[j, ], seasonal.x[[i]], seasonal.x[[j]], permissive) } else { if (! is.list(Y)) {Y <- MatrixToList(Y)} if (! is.null(order.y) && dim(order.y)[1] != length(Y)) { stop("The length of order.y must be equal to the number of series in the database Y.") } if (is.null(seasonal.x)) { seasonal.x[[i]] <- list(order=c(0, 0, 0), period=NA) } if (is.null(seasonal.y)) { seasonal.y[[j]] <- list(order=c(0, 0, 0), period=NA) } options(show.error.messages = FALSE) d <- diss.AR.LPC.CEPS(X[[i]], Y[[i]], k, order.x[i, ], order.y[j, ], seasonal.x[[i]], seasonal.y[[j]],permissive) } options(show.error.messages = TRUE) return(d) } PairwisePredDistance <- function(X, Y=NULL, h, B=500, logarithms.x=NULL, logarithms.y=NULL, differences.x=NULL, differences.y=NULL, plot=FALSE) { if (! is.list(X)) {X <- MatrixToList(X)} n1 <- length(X) if (! is.null(logarithms.x) && length(logarithms.x) != n1) { stop("The length of logarithms.x must be equal to the number of series in X.")} if (! is.null(differences.x) && length(differences.x) != n1) { stop("The length of differences.x must be equal to the number of series in X.")} if (is.null(logarithms.x)) { logarithms.x <- rep(FALSE, n1) } if (is.null(differences.x)) { differences.x <- rep(0, n1) } if (is.null(Y)) { individual.dens1 <- list() ii <- 1 while (ii < n1) { dP <- diss.PRED(X[[ii]], X[[ii + 1]], h , B, logarithms.x[ii], logarithms.x[ii + 1], differences.x[ii], differences.x[ii+1], FALSE ) individual.dens1[[ii]] <- list(dens=dP$dens.x, bw=dP$bw.x) individual.dens1[[ii + 1]] <- list(dens=dP$dens.y, bw=dP$bw.y) ii = ii + 2 if (ii == n1) {ii <- ii -1} } densities <- list() distances <- matrix(0, n1, n1) rownames(distances) <- names(X) for (i in 1:(n1 - 1) ) { for (j in (i + 1):n1 ) { distance <- L1dist(individual.dens1[[i]]$dens, individual.dens1[[j]]$dens, individual.dens1[[i]]$bw, individual.dens1[[j]]$bw ) distances[i, j] <- distance distances[j, i] <- distance } } } else { if (! is.list(Y)) {Y <- MatrixToList(Y)} n2 <- length(Y) if (! is.null(logarithms.y) && length(logarithms.y) != n2) { stop("The length of logarithms.y must be equal to the number of series in Y.")} if (! is.null(differences.y) && length(differences.y) != n2) { stop("The length of differences.y must be equal to the number of series in Y.")} if (is.null(logarithms.y)) { logarithms.y <- rep(FALSE, n2) } if (is.null(differences.y)) { differences.y <- rep(0, n2) } densities <- list() individual.dens1 <- list() individual.dens2 <- list() ii <- 1 XY <- append(X, Y) logarithms.xy <- append(logarithms.x, logarithms.y) differences.xy <- append(differences.x, differences.y) while (ii < n1+n2) { dP <- diss.PRED(XY[[ii]], XY[[ii + 1]], h , B, logarithms.xy[ii], logarithms.xy[ii+1] , differences.xy[ii], differences.xy[ii + 1], FALSE ) individual.dens1[[ii]] <- list(dens=dP$dens.x, bw=dP$bw.x) individual.dens1[[ii + 1]] <- list(dens=dP$dens.y, bw=dP$bw.y) ii <- ii + 2 if (ii == n1+n2) {ii <- ii - 1} } densities <- list() distances <- matrix(0, n1, n2) rownames(distances) <- names(X) colnames(distances) <- names(Y) for (i in 1:n1 ) { for (j in 1:n2 ) { distance <- L1dist(individual.dens1[[i]]$dens, individual.dens1[[n1+j]]$dens, individual.dens1[[i]]$bw, individual.dens1[[n1+j]]$bw ) distances[i, j] <- distance } } } return(distances) } PairwiseSpecLLRDistance <- function(X, Y=NULL, method="DLS", alpha=0.5, plot=FALSE, n=NULL) { if (! is.list(X)) {X <- MatrixToList(X)} if (! is.null(Y) && ! is.list(Y)) {Y <- MatrixToList(Y)} if (is.null(n)) { n <- length(X[[1]]) } if (n > 0) { interpfun <- NULL type <- (pmatch(method, c("DLS", "LK" ))) if (is.na(type)) { stop(paste("Unknown method", method)) } else if (type == 1) { interpfun <- interp.SPEC.LS } else if (type == 2) { interpfun <- interp.W.LK } d <- PairwiseInterpSpecDistance(X, Y, n, interpfun, integrate.divergenceW, alpha) } else { if (is.null(Y)) { d <- dist(X, method="TSDistances", distance="spec.llr", alpha=alpha, plot=FALSE, n=n) } else { d <- dist(X, Y, method="TSDistances", distance="spec.llr", alpha=alpha, plot=FALSE, n=n) } } options(show.error.messages = TRUE) return(d) } PairwiseSpecGLKDistance <- function(X, Y=NULL, plot=FALSE) { if (! is.list(X)) {X <- MatrixToList(X)} if (! is.null(Y) && ! is.list(Y)) {Y <- MatrixToList(Y)} PairwiseInterpSpecDistance(X, Y, floor(length(X[[1]])/2), interp.SPEC.GLK, integrate.GLK) } PairwiseSpecISDDistance<- function(X, Y=NULL, plot=FALSE, n=NULL) { if (! is.list(X)) {X <- MatrixToList(X)} if (! is.null(Y) && ! is.list(Y)) {Y <- MatrixToList(Y)} if (is.null(n)) { n <- length(X[[1]]) } if (n > 0) { d <- PairwiseInterpSpecDistance(X, Y, n, interp.SPEC.LOGLIKELIHOOD , integrate.ISD) }else { if (is.null(Y)) { d <- dist(X, method="TSDistances", distance= "spec.isd", plot=FALSE, n=n) } else { d <- dist(X, Y, method="TSDistances", distance= "spec.isd", plot=FALSE, n=n) } } return(d) } PairwiseInterpSpecDistance <- function(X, Y=NULL, n, interpfun, integrationfun, ...) { l1 <- length(X) interps1 <- lapply(X, interpfun, n) base <- interps1[[1]]$x if (is.null(Y)) { dists <- matrix(0, l1, l1) for (i in 1:(l1-1)) { for (j in (i+1):l1) { d <- integrationfun(base, interps1[[i]]$y , interps1[[j]]$y, ...) dists[i,j] <- d dists[j,i] <- d } } } else { l2 <- length(Y) dists <- matrix(0, l1, l2) interps2 <- lapply(Y, interpfun, n) for (i in 1:l1) { for (j in 1:l2) { d <- integrationfun(base, interps1[[i]]$y , interps2[[j]]$y, ...) dists[i,j] <- d } } } dists } PairwiseCDMDistance <- function(X, Y=NULL, i, j, ...) { if (! is.list(X)) {X <- MatrixToList(X)} if (! is.null(Y) && ! is.list(Y)) {Y <- MatrixToList(Y)} if (is.null(Y)) { as.numeric(diss.CDM(X[[i]], X[[j]], ...)) } else { as.numeric(diss.CDM(X[[i]], Y[[j]], ...)) } } PairwiseNCDDistance <- function(X, Y=NULL, i, j, ...) { if (! is.list(X)) {X <- MatrixToList(X)} if (! is.null(Y) && ! is.list(Y)) {Y <- MatrixToList(Y)} if (is.null(Y)) { as.numeric(diss.NCD(X[[i]], X[[j]], ...)) } else { as.numeric(diss.NCD(X[[i]], Y[[j]], ...)) } } PairwiseFrechetDistance <- function(X, Y=NULL, i, j, ...) { if (! is.list(X)) { X <- MatrixToList(X) } if (! is.null(Y) && ! is.list(Y)) { Y <- MatrixToList(Y) } if (is.null(Y)) { as.numeric(FrechetDistance(X[[i]], X[[j]], ...)) } else { as.numeric(FrechetDistance(X[[i]], Y[[j]], ...)) } } divergenceMatrix2 <- function(codebooks1, codebooks2, divergence) { l1 <- dim(codebooks1)[1] l2 <- dim(codebooks2)[1] mt <- matrix(rep(0, l1 * l2), l1, ) for (i in 1:l1) { for (j in 1:l2) { mt[i, j] <- divergence(codebooks1[i, ], codebooks2[j, ]) } } return(mt); } PDCDist2 <- function(X, Y, m=NULL, t=NULL, divergence=symmetricAlphaDivergence) { if (is.null(t) | is.null(m)) { ent <- entropyHeuristic(cbind(X,Y)) if (is.null(m)) { m <- ent$m; } if (is.null(t)) { t <- ent$t; } } codebooks1 <- ConvertMatrix(X,m,t); codebooks2 <- ConvertMatrix(Y,m,t); D <- divergenceMatrix2( codebooks1, codebooks2, divergence ); return(D); } ConvertMatrix <-function(X, m, td){ return( t(apply(X, 2, codebook, m=m, t=td)) ) }
test_that("classif_ada", { requirePackagesOrSkip("ada", default.method = "load") parset.list = list( list(), list(iter = 5L) ) old.predicts.list = list() old.probs.list = list() for (i in seq_along(parset.list)) { parset = parset.list[[i]] pars = list(binaryclass.formula, data = binaryclass.train) pars = c(pars, parset) set.seed(getOption("mlr.debug.seed")) m = do.call(ada::ada, pars) set.seed(getOption("mlr.debug.seed")) p = predict(m, newdata = binaryclass.test, type = "probs") old.probs.list[[i]] = p[, 1] old.predicts.list[[i]] = as.factor(binaryclass.class.levs[ifelse(p[, 2] > 0.5, 2, 1)]) } testSimpleParsets("classif.ada", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.predicts.list, parset.list) testProbParsets("classif.ada", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.probs.list, parset.list) }) test_that("classif_ada passes parameters correctly to rpart.control ( cp.vals = c(0.022, 0.023) loss.vals = c("exponential", "logistic") for (cp in cp.vals) { for (loss in loss.vals) { lrn = makeLearner("classif.ada", cp = cp, loss = loss) mod = getLearnerModel(train(lrn, pid.task)) expect_equal(mod$model$trees[[1]]$control$cp, cp) expect_equal(mod$model$lossObj$loss, loss) } } })
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(FAMoS) true.p2 <- 3 true.p5 <- 2 sim.data <- cbind.data.frame(range = 1:10, y = true.p2^2 * (1:10)^2 - exp(true.p5 * (1:10))) inits <- c(p1 = 3, p2 = 4, p3 = -2, p4 = 2, p5 = 0) cost_function <- function(parms, binary, data){ if(max(abs(parms)) > 5){ return(NA) } with(as.list(c(parms)), { res <- p1*4 + p2^2*data$range^2 + p3*sin(data$range) + p4*data$range - exp(p5*data$range) diff <- sum((res - data$y)^2) nr.par <- length(which(binary == 1)) nr.data <- nrow(data) AICC <- diff + 2*nr.par + 2*nr.par*(nr.par + 1)/(nr.data - nr.par -1) return(AICC) }) } swaps <- list(c("p1", "p5")) res <- famos(init.par = inits, fit.fn = cost_function, homedir = tempdir(), method = "swap", swap.parameters = swaps, init.model.type = c("p1", "p3"), optim.runs = 1, data = sim.data) famos.performance(input = res$mrun, path = tempdir()) fig.sc <- sc.order(input = tempdir(), mrun = res$mrun) par(mfrow = c(1,2)) fig.sc1 <- sc.order(input = tempdir(), mrun = res$mrun, colour.par = "p1") fig.sc2 <- sc.order(input = tempdir(), mrun = res$mrun, colour.par = "p5") fig.aicc <- aicc.weights(input = tempdir(), mrun = res$mrun)
StomatalClosure <- function(data, sample = "sample", time.since.start = "time.since.start", conductance = "conductance", RWD = "RWD.interval", threshold = FALSE, graph = TRUE, show.legend = TRUE) { data_in <- ValidityCheck( data, sample = sample, time.since.start = time.since.start, conductance = conductance, RWD = RWD ) OrderCheck(data_in, sample = sample, time.since.start = time.since.start) sc.model <- list() for (i in 1:length(unique(data_in[[sample]]))) { sub.sample <- unique(data_in[[sample]])[i] data_in_subset <- data_in[data_in[[sample]] == sub.sample, ] data_in_subset <- data_in_subset[!is.na(data_in_subset[[conductance]]), ] data_in_subset <- data_in_subset[!is.na(data_in_subset[[RWD]]), ] try({ all.fine <- FALSE data_in_subset$norm.x <- data_in_subset[[time.since.start]] - min(data_in_subset[[time.since.start]]) m <- ApplyCombMod(data_in_subset, y = conductance, x = "norm.x") a <- as.numeric(coef(m)[1]) b <- as.numeric(coef(m)[2]) c <- as.numeric(coef(m)[3]) d <- as.numeric(coef(m)[4]) coef <- coef(m) try({ conf_int <- suppressMessages(confint(m)) }, silent = TRUE) xnew <- 1:max(data_in_subset[[time.since.start]]) xnew_plot <- (1:max(data_in_subset[[time.since.start]]) + min(data_in_subset[[time.since.start]])) all_fit_plot <- a * exp(b * xnew) + c * xnew + d exp_fit_plot <- a * exp(b * xnew) + d lin_fit_plot <- c * xnew + d exp_slope <- c(diff(exp_fit_plot)) if (threshold == FALSE) { sens = -(b ^ 2 * 60) }else{ sens = -(b ^2 * threshold) } time.sc <- (which(exp_slope > sens)[[1]]) + min(data_in_subset[[time.since.start]]) gmin.sc <- a * exp(b * (time.sc - min(data_in_subset[[time.since.start]]))) + c * (time.sc - min(data_in_subset[[time.since.start]])) + d time.linear <- data_in_subset[[time.since.start]][data_in_subset[[time.since.start]] > time.sc] RWD.linear <- data_in_subset[[RWD]][data_in_subset[[time.since.start]] > time.sc] if (length(RWD.linear) < 3) { warning( paste0("sample ", sub.sample), ": not enough data points (< 3) in the linear region of the leaf drying curve" ) } else{ li <- lm(RWD.linear ~ time.linear) RWD.sc <- coef(li)[2] * time.sc + coef(li)[1] if (graph == TRUE) { suppressMessages(suppressWarnings( PlotOutput( sub.sample = sub.sample, x = data_in_subset[[time.since.start]], y = data_in_subset[[conductance]], legend.y = "leaf conductance", x.axis = "time since start (min)", y.axis = expression('g ' * ('mmol ' * m ^ -2 * s ^ -1)), x.intercept = time.sc, legend.x.intercept = "stomatal closure", line.y = all_fit_plot, line.y2 = lin_fit_plot, line.y3 = exp_fit_plot, line.x = xnew_plot, legend.line.y = "entire fit", legend.line.y2 = "linear part of fit", legend.line.y3 = "exp. part of fit", show.legend = show.legend ) )) } sc.model[[paste0("sample ", sub.sample)]] <- list( stomatal.closure = list( time.since.start = time.sc, RWD = as.numeric(RWD.sc), conductance = gmin.sc ), formula = list(linear = "conductance ~ (c * time.since.start + d)", exponential = "conductance ~ (a * exp(b * time.since.start) + d)"), coef = coef, conf.int = list("2.5 %" = conf_int[, 1], "97.5 %" = conf_int[, 2]) ) } all.fine <- TRUE }, silent = TRUE) if (all.fine == FALSE) { warning(paste0("sample ", sub.sample), ": fitting of data to a combined model didn't work") } } return(sc.model) }
match.index <- function(lattice.note, ggplot.note) { tmp.lattice.list <- strsplit(lattice.note, "lattice") tmp.ggplot.list <- strsplit(ggplot.note, "ggplot2") tmp.lattice <- unlist(tmp.lattice.list) rm.index <- which(tmp.lattice==")") tmp.lattice <- tmp.lattice[-rm.index] tmp.ggplot <- unlist(tmp.ggplot.list) rm.index <- which(tmp.ggplot==")") tmp.ggplot <- tmp.ggplot[-rm.index] ggplot.index <- match(tmp.lattice, tmp.ggplot) return(ggplot.index) } writeHTML <- function(htmldir, save.format) { html.start <- "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" html.start <- paste(html.start, "<html><header><link rel=\"stylesheet\" type=\"text/css\" href=\"", "http://129.186.62.12/PKreport.css", "\"/>", sep="") html.start <- paste(html.start, "<title>PKoutput", htmldir, "Figures</title></header><body>", sep=" ") html.start <- paste(html.start, "<hr><h3><p class=\"subtitle\">", htmldir, "Figures</p></h3>", sep=" ") html.content <- NULL fig.files <- dir(htmldir, pattern=save.format) fig.files <- paste(htmldir, fig.files, sep="/") txt <- paste("<img src=", fig.files, sep="") txt <- paste(txt, ">", sep="") if (.pkplot$getConfig("package")==0) { lattice.txt <- txt[grep("lattice", txt)] lattice.no <- sapply(1:length(lattice.txt), function(i) strsplit(lattice.txt[i], "_")[[1]][2]) lattice.note <- .pkplot$getAllPKCodeNote()[c(as.numeric(lattice.no))] lattice.note <- unlist(lattice.note) html.tmp <- paste("<a href=\" html.tmp <- paste("<td>", html.tmp, "</td>", sep="") tr.index <- which((((1:length(lattice.note))-1)%%4) == 0) html.tmp[tr.index] <- paste("<tr>", html.tmp[tr.index], sep="") tr.index <- which(((1:length(lattice.note))%%4) == 0) html.tmp[tr.index] <- paste(html.tmp[tr.index], "</tr>", sep="") html.content <- paste(html.content, html.tmp, collapse="") html.content <- paste("<a name=\"top\"><h3><table cellpadding=5 align=center>", html.content, "</table></h3></a>", sep="") title.body <- "<p><center><h2>Lattice package</h2></center></p>" fig.tmp <- paste("<a name=\"", lattice.no, "\">", lattice.no, "</a>", sep="") fig.body <- paste("<p>Figure ID: ", fig.tmp, "</p><a href=\" fig.body <- paste(fig.body, "<p> Note: ", lattice.note, "</p>", sep="") fig.body <- paste(fig.body, lattice.txt, collapse="") html.body <- paste(title.body, fig.body, sep="") } if (.pkplot$getConfig("package")==1) { ggplot.txt <- txt[grep("ggplot", txt)] if (length(ggplot.txt) > 0) { ggplot.no <- sapply(1:length(ggplot.txt), function(i) strsplit(ggplot.txt[i], "_")[[1]][2]) ggplot.note <- .pkplot$getAllPKCodeNote()[c(as.numeric(ggplot.no))] ggplot.note <- unlist(ggplot.note) html.tmp <- paste("<a href=\" html.tmp <- paste("<td>", html.tmp, "</td>", sep="") tr.index <- which((((1:length(ggplot.note))-1)%%4) == 0) html.tmp[tr.index] <- paste("<tr>", html.tmp[tr.index], sep="") tr.index <- which(((1:length(ggplot.note))%%4) == 0) html.tmp[tr.index] <- paste(html.tmp[tr.index], "</tr>", sep="") html.content <- paste(html.content, html.tmp, collapse="") html.content <- paste("<a name=\"top\"><h3><table cellpadding=5 align=center>", html.content, "</table></h3></a>", sep="") title.body <- "<p><center><h2>ggplot package</h2></center></p>" fig.tmp <- paste("<a name=\"", ggplot.no, "\">", ggplot.no, "</a>", sep="") fig.body <- paste("<p>Figure ID: ", fig.tmp, "</p><a href=\" fig.body <- paste(fig.body, "<p> Note: ", ggplot.note, "</p>", sep="") fig.body <- paste(fig.body, ggplot.txt, collapse="") html.body <- paste(title.body, fig.body, sep="") } } if (.pkplot$getConfig("package")==2) { lattice.txt <- txt[grep("lattice", txt)] ggplot.txt <- txt[grep("ggplot", txt)] if (length(lattice.txt)==0) stop("There is no lattice figure!") if (length(ggplot.txt)==0) stop("There is no ggplot figure!") lattice.no <- sapply(1:length(lattice.txt), function(i) strsplit(lattice.txt[i], "_")[[1]][2]) lattice.note <- .pkplot$getAllPKCodeNote()[c(as.numeric(lattice.no))] lattice.note <- unlist(lattice.note) ggplot.no <- sapply(1:length(ggplot.txt), function(i) strsplit(ggplot.txt[i], "_")[[1]][2]) ggplot.note <- .pkplot$getAllPKCodeNote()[c(as.numeric(ggplot.no))] ggplot.note <- unlist(ggplot.note) ggplot.index <- match.index(lattice.note, ggplot.note) ggplot.txt <- ggplot.txt[ggplot.index] ggplot.note <- ggplot.note[ggplot.index] ggplot.no <- ggplot.no[ggplot.index] lattice.note.1 <- strsplit(lattice.note, " \\(") lattice.note.2 <- unlist(lattice.note.1) tmp.index <- which(lattice.note.2 == "lattice)") lattice.note.3 <- lattice.note.2[-tmp.index] html.tmp <- paste("<a href=\" html.tmp <- paste("<td>", html.tmp, "</td>", sep="") trs.index <- which((((1:length(lattice.note))-1)%%4) == 0) html.tmp[trs.index] <- paste("<tr>", html.tmp[trs.index], sep="") tre.index <- which(((1:length(lattice.note))%%4) == 0) html.tmp[tre.index] <- paste(html.tmp[tre.index], "</tr>", sep="") html.content <- paste(html.content, html.tmp, collapse="") if (length(trs.index) != length(tre.index)) html.content <- paste(html.content, "</tr>", sep="") html.content <- paste("<a name=\"top\"><h3><table class=\"figcenter\">", html.content, "</table></h3></a>", sep="") fig.tmp.lattice <- paste("<a name=\"", lattice.no, "\">", lattice.no, "</a>", sep="") fig.id.lattice <- paste("<td>Figure ID: ", fig.tmp.lattice, "<a href=\" fig.id.ggplot <- paste("<td>Figure ID: ", ggplot.no, "</td>", sep="") fig.id <- paste("<tr>", fig.id.lattice, fig.id.ggplot, "</tr>", sep="") fig.note.lattice <- paste("<td> Note: ", lattice.note, "</td>", sep="") fig.note.ggplot <- paste("<td> Note: ", ggplot.note, "</td>", sep="") fig.note <- paste("<tr>", fig.note.lattice, fig.note.ggplot, "</tr>", sep="") fig.fig.lattice <- paste("<td>", lattice.txt, "</td>", sep="") fig.fig.ggplot <- paste("<td>", ggplot.txt, "</td>", sep="") fig.fig <- paste("<tr>", fig.fig.lattice, fig.fig.ggplot, "</tr>", sep="") fig.body <- paste(fig.id, fig.note, fig.fig, sep="") fig.body <- paste(fig.body, collapse="") fig.body <- paste("<table class=\"center\">", fig.body, "</table>", sep="") title.body <- "<p><center><h2>lattice and ggplot package</h2></center></p>" html.body <- paste(title.body, fig.body, sep="") } html.end <- paste("<p></p><p></p><hr><p align=\"right\" class=\"bottomFont\">PKreport", packageDescription("PKreport")$Version, date(), "</p></body></html>", sep=" ") filename <- paste("PK", htmldir, ".html", sep="") PK.html <- file(filename, "w") html.all <- paste(html.start, html.content, html.body, html.end, sep="\n") writeLines(html.all, con = PK.html, sep = "\n") close(PK.html) } writeTable <- function(filename, mytitle, mydata) { html.start <- "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" html.start <- paste(html.start, "<html><header><link rel=\"stylesheet\" type=\"text/css\" href=\"", "http://129.186.62.12/PKreport.css", "\"/>", sep="") html.end <- paste("<p></p><p></p><hr><p align=\"right\" class=\"bottomFont\">PKreport", packageDescription("PKreport")$Version, date(), "</p></body></html>", sep=" ") html.start<- paste(html.start, "<title>", mytitle, "</title></header><body>", sep=" ") html.start <- paste(html.start, "<hr><h3><p class=\"subtitle\">", mytitle, "Table</p></h3>", sep=" ") html.content <- paste("<h4>Color Description (scaled in column direction)</h4>", sep="") html.content <- paste(html.content, "<table><tr><td BGCOLOR= html.content <- paste(html.content, "<h4>Data</h4><table>", sep="") html.colname <- paste("<td BGCOLOR= html.content <- paste(html.content, "<tr>", html.colname, "</tr>", sep="") html.data <- NULL for (i in 1:ncol(mydata)) { tmp <- mydata[,i] if (length(unique(tmp))>=5 && is.numeric(tmp)) { order.index <- order(as.numeric(tmp)) quantile.index <- round(quantile(1:length(order.index), c(0.25,0.5,0.75))) q25.index <- c(1:quantile.index[1]) if (quantile.index[1]!=quantile.index[2]) q50.index <- c((quantile.index[1]+1):quantile.index[2]) if (quantile.index[2]!=quantile.index[3]) q75.index <- c((quantile.index[2]+1):quantile.index[3]) if (quantile.index[3] < length(order.index)) q100.index <- c((quantile.index[3]+1):(length(order.index))) tmp[order.index[q25.index]] <- paste("<td BGCOLOR= tmp[order.index[q50.index]] <- paste("<td BGCOLOR= tmp[order.index[q75.index]] <- paste("<td BGCOLOR= tmp[order.index[q100.index]] <- paste("<td BGCOLOR= } else { if (length(unique(tmp)) >=3 && is.numeric(tmp)) { min.index <- which(tmp==min(tmp)) max.index <- which(tmp==max(tmp)) tmp[min.index] <- paste("<td BGCOLOR= tmp[max.index] <- paste("<td BGCOLOR= tmp[-c(min.index, max.index)] <- paste("<td>", tmp[-c(min.index, max.index)], "</td>", sep="") } else { tmp <- paste("<td>", tmp, "</td>", sep="") } } mydata[,i] <- tmp } for (i in 1:nrow(mydata)) { html.data <- paste(mydata[i,], sep="", collapse="") html.content <- paste(html.content, "<tr>", html.data, "</tr>", sep="") } html.content <- paste(html.content, "</table>", sep="") PK.html <- file(filename, "w") html.all <- paste(html.start, html.content, html.end, sep="\n") writeLines(html.all, con = PK.html, sep = "\n") close(PK.html) } writeLst <- function(filename, lstString) { html.start <- "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" html.start <- paste(html.start, "<html><header><link rel=\"stylesheet\" type=\"text/css\" href=\"", "http://129.186.62.12/PKreport.css", "\"/>", sep="") html.end <- paste("<p></p><p></p><hr><p align=\"right\" class=\"bottomFont\">PKreport", packageDescription("PKreport")$Version, date(), "</p></body></html>", sep=" ") html.start<- paste(html.start, "<title>lst file", "</title></header><body>", sep=" ") html.start <- paste(html.start, "<hr><h3><p class=\"subtitle\">lst file</p></h3>", sep=" ") html.content <- paste(lstString, "<br>", sep="") html.content <- paste(html.content, collapse="") html.content <- paste("<p><pre>", html.content, "</pre></p>", sep="") PK.html <- file(filename, "w") html.all <- paste(html.start, html.content, html.end, sep="\n") writeLines(html.all, con = PK.html, sep = "\n") close(PK.html) } writeLst.tab <- function(filename, lstString) { html.start <- "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" html.start <- paste(html.start, "<html><header><link rel=\"stylesheet\" type=\"text/css\" href=\"", "http://129.186.62.12/PKreport.css", "\"/>", sep="") html.end <- paste("<p></p><p></p><hr><p align=\"right\" class=\"bottomFont\">PKreport", packageDescription("PKreport")$Version, date(), "</p></body></html>", sep=" ") html.start<- paste(html.start, "<title>lst file", "</title></header><body>", sep=" ") html.content <- "<table>" for (i in 1:length(lstString)) { tmp <- strsplit(lstString[i], " ")[[1]] tmp.html <- paste(tmp, collapse="</td><td>") html.content <- paste(html.content, "<tr><td>", tmp.html, "</td></tr>", sep="") } html.content <- paste(html.content, "</table>", sep="") PK.html <- file(filename, "w") html.all <- paste(html.start, html.content, html.end, sep="\n") writeLines(html.all, con = PK.html, sep = "\n") close(PK.html) } PKoutput <- function(nonmemObj=NULL, table.Rowv=FALSE, table.Colv=FALSE) { general.list <- .pkplot$getGlobalConfig() html.start <- "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" html.start <- paste(html.start, "<html><header><link rel=\"stylesheet\" type=\"text/css\" href=\"", "http://129.186.62.12/PKreport.css", "\"/>", sep="") html.index <- paste(html.start, "<title>PKreport</title></header><body>", sep="") html.index <- paste(html.index, "<h1><p class=\"title\">PKreport</p></h1>", sep="") if ((!is.null(nonmemObj)) && class(nonmemObj) == "nonmem") { html.index <- paste(html.index, "<h3><p class=\"subtitle\">NONMEM results</p></h3><table class=\"center\" border=0>", sep="") if (length([email protected]) != 0) { writeLst("lst.html", [email protected]) html.index <- paste(html.index, "<tr><td><a href=lst.html>lst file</a></td></tr>", sep="") } if (nrow(nonmemObj@tabdata) != 0) { order.data <- nonmemObj@tabdata if (table.Colv || table.Rowv) { tmp.data <- order.data[,sapply(order.data, is.numeric)] tmp.heat <- heatmap(as.matrix(tmp.data)) if (table.Rowv) order.data <- order.data[rev(tmp.heat$rowInd),] if (table.Colv) order.data <- order.data[, tmp.heat$colInd] } writeTable("tab.html", "tab file", order.data) html.index <- paste(html.index, "<tr><td><a href=tab.html>Tab file</a></td></tr>", sep="") } if (nrow([email protected]$data) != 0) { order.data <- [email protected]$data if (table.Colv || table.Rowv) { tmp.data <- order.data[,sapply(order.data, is.numeric)] tmp.heat <- heatmap(as.matrix(tmp.data)) if (table.Rowv) order.data <- order.data[rev(tmp.heat$rowInd),] if (table.Colv) order.data <- order.data[, tmp.heat$colInd] } writeTable("cov.html", "cov file",order.data) html.index <- paste(html.index, "<tr><td><a href=cov.html>Cov file</a></td></tr>", sep="") } if (nrow([email protected]$data) != 0) { order.data <- [email protected]$data if (table.Colv || table.Rowv) { tmp.data <- order.data[,sapply(order.data, is.numeric)] tmp.heat <- heatmap(as.matrix(tmp.data)) if (table.Rowv) order.data <- order.data[rev(tmp.heat$rowInd),] if (table.Colv) order.data <- order.data[, tmp.heat$colInd] } writeTable("cor.html", "cor file",order.data) html.index <- paste(html.index, "<tr><td><a href=cor.html>Cor file</a></td></tr>", sep="") } if (nrow([email protected]$data) != 0) { order.data <- [email protected]$data if (table.Colv || table.Rowv) { tmp.data <- order.data[,sapply(order.data, is.numeric)] tmp.heat <- heatmap(as.matrix(tmp.data)) if (table.Rowv) order.data <- order.data[rev(tmp.heat$rowInd),] if (table.Colv) order.data <- order.data[, tmp.heat$colInd] } writeTable("coi.html", "coi file",order.data) html.index <- paste(html.index, "<tr><td><a href=coi.html>Coi file</a></td></tr>", sep="") } if (nrow([email protected]$data) != 0) { order.data <- [email protected]$data if (table.Colv || table.Rowv) { tmp.data <- order.data[,sapply(order.data, is.numeric)] tmp.heat <- heatmap(as.matrix(tmp.data)) if (table.Rowv) order.data <- order.data[rev(tmp.heat$rowInd),] if (table.Colv) order.data <- order.data[, tmp.heat$colInd] } writeTable("phi.html", "phi file",order.data) html.index <- paste(html.index, "<tr><td><a href=phi.html>phi file</a></td></tr>", sep="") } } html.index <- paste(html.index, "</table><hr><h3><p class=\"subtitle\">Diagnostics</p></h3><table class=\"center\" border=0>", sep="") if (file.exists(general.list$univar.dir)) { writeHTML(general.list$univar.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKunivar.html>Univariate Figures</a></td></tr>", sep="") } if (file.exists(general.list$bivar.dir)) { writeHTML(general.list$bivar.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKbivar.html>Bivariate Figures</a></td></tr>", sep="") } if (file.exists(general.list$ind.dir)) { writeHTML(general.list$ind.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKind.html>Individual Figures</a></td></tr>", sep="") } if (file.exists(general.list$gof.dir)) { writeHTML(general.list$gof.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKgof.html>Figures for Goodness of Fit</a></td></tr>", sep="") } if (file.exists(general.list$struct.dir)) { writeHTML(general.list$struct.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKstruct.html>Figures for Structural Model Dagnostics</a></td></tr>", sep="") } if (file.exists(general.list$resid.dir)) { writeHTML(general.list$resid.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKresid.html>Figures for Residual Model Dagnostics</a></td></tr>", sep="") } if (file.exists(general.list$para.dir)) { writeHTML(general.list$para.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKpara.html>Figures for Parameters Dagnostics</a></td></tr>", sep="") } if (file.exists(general.list$cov.dir)) { writeHTML(general.list$cov.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKcov.html>Figures for Covariate Model Dagnostics</a></td></tr>", sep="") } if (file.exists(general.list$eta.dir)) { writeHTML(general.list$eta.dir,general.list$save.format) html.index <- paste(html.index, "<tr><td><a href=PKeta.html>Figures for Random Effects Dagnostics</a></td></tr>", sep="") } if (file.exists("PKcode.txt")) { html.index <- paste(html.index, "<tr><td><a href=PKcode.txt>R Code for Figures</a></td></tr>", sep="") } html.index <- paste(html.index, "</table>", sep="") html.end <- paste("<p></p><p></p><hr><p align=\"right\" class=\"bottomFont\">PKreport", packageDescription("PKreport")$Version, date(), "</p></body></html>", sep=" ") html.index <- paste(html.index, html.end, sep="") PK.html <- file("PKindex.html", "w") writeLines(html.index, con = PK.html, sep = "\n") close(PK.html) }
dwiRiceBias <- function(object, ...) cat("No Rice Bias correction defined for this class:",class(object),"\n") setGeneric("dwiRiceBias", function(object, ...) standardGeneric("dwiRiceBias")) setMethod("dwiRiceBias", "dtiData", function(object, sigma = NULL, ncoils = 1) { if (is.null(sigma) || sigma < 1) { cat("Please provide a value for sigma ... returning the original object!\n") return(object) } args <- object@call corrected <- FALSE for (i in 1:length(args)) { if (length(grep("dwiRiceBias", args[i][[1]])) > 0) { corrected <- TRUE cat("Rice bias correction already performed by\n") print(args[i][[1]]) cat("\n ... returning the original object!\n") } } if (!corrected) { object@si <- array(ricebiascorr(object@si, sigma, ncoils), dim(object@si)) object@call <- c(args, sys.call(-1)) } invisible(object) }) ricebiascorr <- function(x, s = 1, ncoils = 1){ varstats <- aws::sofmchi(ncoils, 50, .002) xt <- x/s xt <- pmax(varstats$minlev, xt) ind <- findInterval(xt, varstats$mu, rightmost.closed = FALSE, all.inside = FALSE) varstats$ncp[ind] * s }
library(httk) signif(head(solve_gas_pbtk(chem.name="pyrene")),3) signif(head(solve_gas_pbtk(chem.cas="129-00-0")),3) signif(head(solve_gas_pbtk(parameters=parameterize_gas_pbtk(chem.cas="129-00-0"))),3) quit("no")
spec_energy_trap <- function(Q = NULL, b = NULL, m = NULL, y = NULL, scale = 3, units = c("SI", "Eng")) { if(!requireNamespace("ggplot2", quietly = TRUE)) { stop("xc_trap diagram plot requires ggplot2 to be installed.", call. = FALSE) } if(!requireNamespace("grid", quietly = TRUE)) { stop("xc_trap diagram plot requires grid to be installed.", call. = FALSE) } if (length(c(Q, b, m)) != 3) { stop("One of required inputs is missing: Q, b or m may be zero") } if (any(c(Q, b, m) < 0)) { stop("Either Q, b, or m is < 0. All of these variables must be non-negative") } if ( ( b == 0 ) & ( m == 0 ) ) { stop("m (side slope) and b (bottom width) are zero. Channel has no area") } if( class(Q) == "units" ) Q <- units::drop_units(Q) if( class(b) == "units" ) b <- units::drop_units(b) if( class(m) == "units" ) m <- units::drop_units(m) scalefact <- scale units <- units if (units == "SI") { g <- 9.80665 txtx <- sprintf("Specific Energy, E (m)") txty <- sprintf("Depth, y (m)") } else if (units == "Eng") { g <- 32.2 txtx <- sprintf("Specific Energy, E (ft)") txty <- sprintf("Depth, y (ft)") } else if (all(c("SI", "Eng") %in% units == FALSE) == FALSE) { stop("Incorrect unit system. Must be SI or Eng") } ycfun <- function(yc) { (Q^2 / g) - ((b * yc + m * yc^2)^3)/(b + 2 * m * yc)} yc <- uniroot(ycfun, interval = c(0.0000001, 200), extendInt = "yes")$root Ac <- yc * (b + m * yc) Emin <- yc + ((Q ^ 2) / (2 * g * Ac ^ 2)) ylim <- yc*scalefact yalt <- E1 <- NULL if ( ! missing (y) ) { E1 <- y + (Q ^ 2) / (2 * g * (y * (b + m * y))^2) if ( y > yc ) interv <- c(0.0000001, yc) if ( y < yc ) interv <- c(yc, 200) yaltfun <- function(ya) { E1 - (ya + (Q ^ 2) / (2 * g * (ya * (b + m * ya))^2)) } yalt <- uniroot(yaltfun, interval = interv, extendInt = "yes")$root ylim <- max(ylim, y, yalt) } ordr <- floor(log10(ylim)) ymax <- round(ylim + 0.5*10^(ordr-1), -(ordr-1)) ys <- seq(0.1*yc,ymax,length=1000) As <- ys * (b + m * ys) Es <- ys + ((Q ^ 2) / (2 * g * As ^ 2)) xx <- yy <- NULL eycurve <- data.frame( xx = Es , yy = ys ) eycurve <- subset(eycurve, xx <= ymax,select=c(xx, yy)) seg1 <- data.frame(xx = c(Emin, Emin),yy = c(0, yc)) seg2 <- data.frame(xx = c(0, Emin),yy = c(yc, yc)) txt1 <- sprintf("Emin=%.3f",Emin) txt2 <- sprintf("yc=%.3f",yc) offst <- ymax*0.0275 p <- ggplot2::ggplot() + ggplot2::geom_path(data=eycurve,ggplot2::aes(x=xx, y=yy),color="black", size=1.5) + ggplot2::scale_x_continuous(txtx, limits = c(0, ymax), expand = c(0,0)) + ggplot2::scale_y_continuous(txty, limits = c(0, ymax), expand = c(0,0)) + ggplot2::geom_abline(slope = 1, intercept = 0 ,color="black",linetype = "dashed") + ggplot2::geom_segment(ggplot2::aes(x=Emin, xend=Emin, y=0, yend=yc)) + ggplot2::geom_segment(ggplot2::aes(x=0, xend=Emin, y=yc, yend=yc)) + ggplot2::annotate(geom="text", x=Emin-offst, y=yc/2, label=txt1, angle = 90, size = 3) + ggplot2::annotate(geom="text", x=Emin/2, y=yc+offst, label=txt2, angle = 0, size = 3) + ggplot2::coord_fixed(ratio = 1) + ggplot2::theme_bw() if ( ! missing (y) ) { txt3 <- sprintf("y=%.3f",y) txt4 <- sprintf("y=%.3f",yalt) txt5 <- sprintf("E=%.3f",E1) p <- p + ggplot2::geom_segment(ggplot2::aes(x=E1, xend=E1, y=0, yend=max(y,yalt)),linetype=3) + ggplot2::geom_segment(ggplot2::aes(x=0, xend=E1, y=yalt, yend=yalt), linetype=3) + ggplot2::geom_segment(ggplot2::aes(x=0, xend=E1, y=y, yend=y), linetype=3) + ggplot2::annotate(geom="text", x=min(Emin/2,E1/2), y=y+offst, label=txt3, angle = 0, size = 3,hjust = "left") + ggplot2::annotate(geom="text", x=min(Emin/2,E1/2), y=yalt+offst, label=txt4, angle = 0, size = 3,hjust = "left") + ggplot2::annotate(geom="text", x=E1+offst, y=(y+yalt)/2, label=txt5, angle = 90, size = 3) } return(p) }
MVoptbd.maeA<-function(trt.N,blk.N,theta,nrep,itr.cvrgval) { arrays=t(combn(trt.N,2)) na=dim(arrays)[1] ii=2 trco=cbind(matrix(1,trt.N-1),-diag(1,trt.N-1,trt.N-1)) while(ii<=trt.N-1){ if (ii==trt.N-1){ trco1=cbind(matrix(0,1,trt.N-2),matrix(1,trt.N-ii),-diag(1,trt.N-ii,trt.N-ii))} else {trco1=cbind(matrix(0,trt.N-ii,trt.N-(trt.N-ii+1)),matrix(1,trt.N-ii),-diag(1,trt.N-ii,trt.N-ii))} trco=rbind(trco,trco1) ii=ii+1 } del.1<-matrix(10^20,na,3) desbest.1<-matrix(0,nrep*2,blk.N) MVoptbest.1<-matrix(0,nrep,2) for(irep in 1:nrep){ des<-intcbd.mae(trt.N, blk.N) if(trt.N==blk.N&trt.N>3&irep<(trt.N-1)) {in.desns=matrix(0,(trt.N-3)*2,blk.N) in.desns0=rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1)) for(i in 1:(trt.N-3)) {in.desns01=cbind(rbind(seq(1,(trt.N-i)),c(seq(1,(trt.N-i))[2:(trt.N-i)],1)), rbind(rep(1,i),((trt.N-i+1):trt.N))); in.desns[c((i-1)*2+1,i*2),]=in.desns01} in.desns=rbind(rbind(seq(1,trt.N),c(seq(1,trt.N)[2:trt.N],1)),in.desns) des=in.desns[c((irep-1)*2+1,irep*2),]} cmat<-cmatbd.mae(trt.N,blk.N,theta,des) invc=ginv(cmat) invcp=trco%*%invc%*%t(trco); MVopt =max(diag(invcp)); MVcold=MVopt descold=t(des) cdel=100 ivalMVcold={} for (i in 1:blk.N){ j=1; for (j in 1:na){ temp=descold[i,] if(all(descold[i,]==arrays[j,])) {MVopt=MVcold; del.1[j,]<-c(j,(MVcold-MVopt),MVopt); next} descold[i,]=arrays[j,] trtin<-contrasts(as.factor(t(descold)),contrasts=FALSE)[as.factor(t(descold)),] R.trt<-t(trtin)%*%trtin if (rankMatrix(R.trt)[1]<trt.N) {MVopt=10^20; del.1[j,]<-c(j,(MVcold-MVopt),MVopt); next} cmato=cmatbd.mae(trt.N,blk.N, 0,t(descold)) egv<-sort(eigen(cmato)$values) if(egv[2]<0.000001) {MVopt=10^20; del.1[j,]<-c(j,(MVcold-MVopt),MVopt); next} cmat=cmatbd.mae(trt.N,blk.N,theta,t(descold)) invc=ginv(cmat) invcp=trco%*%invc%*%t(trco); MVopt =max(diag(invcp)); del.n<-del.1[j,]<-c(j,(MVcold-MVopt),MVopt) descold[i,]=temp } del.1<-del.1[order(del.1[,3]),] delbest=t(del.1[1,]) descold[i,]=arrays[delbest[1],] MVcold=delbest[3] cdel=delbest[2] ivalMVcold=rbind(ivalMVcold, c(i,MVcold)) if(i>itr.cvrgval) if(all(ivalMVcold[c(i-(itr.cvrgval-2),i),2]==ivalMVcold[i-(itr.cvrgval-1),2])) break } if (irep==1) {desbest.1=t(descold)} else {desbest.1=rbind(desbest.1,t(descold))} MVoptbest.1[irep,]=c(irep,MVcold) } best=MVoptbest.1[order(MVoptbest.1[,2]),] nb=best[1,1] MVscore<-best[1,2] MVoptde<- desbest.1[c((nb-1)*2+1,nb*2),] tkmessageBox(title="Search completed",message=paste("Search completed",sep="")) cnames=paste0("Ary",1:blk.N) dimnames(MVoptde)=list(NULL,cnames) MVopt_sum2<-list("v"=trt.N,"b"=blk.N,theta=theta,nrep=nrep,itr.cvrgval=itr.cvrgval, "OptdesF"=MVoptde,"Optcrtsv" =MVscore) return(MVopt_sum2) }
see.mixedII <- function(){ old.par <- par(no.readonly = TRUE) if(dev.capabilities("locator")$locator == FALSE) stop("Device cannot implement function") setup.mixed <- function(){ if(as.numeric(dev.cur())!=1)dev.off() dev.new(width=9, height = 4) make.table <- function(nr, nc) { savepar <- par(mar=rep(0, 4),pty = "m") plot(c(0, nc + 6.9), c(1, -(nr + 1)), type="n", xlab="", ylab="", axes=FALSE) savepar } draw.cell<-function(text, r, c, cex = .9){ rect(c, -r, c+1, -r+1) text(c+.5, -r+.5, text, cex = cex) } make.table(4,19) cn <- c("",paste("R",1:18,sep="")) c1 <- c(7,6,5,7,6,5,4,4,4,1,2,3,4,4,4,1,2,3) c2 <- c(4,4,4,1,2,3,7,6,5,7,6,5,1,2,3,4,4,4) c3 <- c(1,2,3,4,4,4,1,2,3,4,4,4,7,6,5,7,6,5) data <- t(cbind(c1,c2,c3)) for(i in 1:19){ draw.cell(cn[i], 1, i) } draw.cell("F1",2,1) for(i in 2:19){ draw.cell(c1[i-1], 2, i) } draw.cell("F2",3,1) for(i in 2:19){ draw.cell(c2[i-1], 3, i) } draw.cell("F3",4,1) for(i in 2:19){ draw.cell(c3[i-1], 4, i) } text(11, 0.6, "Random", cex=1.2, font = 2) text(-0.2, -2, "Fixed", cex=1.2, font = 2, srt = 90) text(23.25, 0, "Mean", cex=1.1, font = 2) text(21.5, -0.5, expression(underline("All levels"))) text(25, -0.5, expression(underline("Selected levels"))) mn <- apply(data, 1, mean) for(i in 2:4)text(21.5,-i+.5,round(mn[i-1],0)) rect(8.2, -5.1, 11.8, -4.2) text(10, -4.65, "SAMPLE", font = 2, col = 1) fl <- function(){ ans <- locator(1) yv <- ans$y xv <- ans$x if((yv>=-5.1)&(yv<=-4.2)&(xv >= 8.2)&(xv <= 11.8)) {rect(8.2, -5.1, 11.8, -4.2, col = rgb(red=0.5,blue=0.5,green=0.5,alpha=.6));sample.mixed()} else fl1() } fl1 <- function(){ ans <- locator(1) yv <- ans$y xv <- ans$x if((yv>=-5.1)&(yv<=-4.2)&(xv >= 8.2)&(xv <= 11.8)) {rect(8.2, -5.1, 11.8, -4.2, col = rgb(red=0.5,blue=0.5,green=0.5,alpha=.6));sample.mixed()} else fl() } fl() } sample.mixed <- function(r = 4, c = 19, n = 3){ col.row<- function(col=rgb(red=0.5, blue=0.5, green=0.5, alpha=.6), r, c) { rect(c, -r-3, c+1, -r+1, col = col) } sn <- sample(seq(2, 19), size = n) for(i in 1:length(sn)) col.row(c = sn[i], r=1) rect(8.2, -5.1, 11.8, -4.2) text(10, -4.65, "SAMPLE", font = 2, col = 1) c1 <- c(7,6,5,7,6,5,4,4,4,1,2,3,4,4,4,1,2,3) c2 <- c(4,4,4,1,2,3,7,6,5,7,6,5,1,2,3,4,4,4) c3 <- c(1,2,3,4,4,4,1,2,3,4,4,4,7,6,5,7,6,5) data <- t(cbind(c1,c2,c3)) mn <- apply(data[,sn-1], 1, mean) for(i in 2:4)text(25,-i+.5,round(mn[i-1],1)) fl <- function(){ ans <- locator(1) yv <- ans$y xv <- ans$x if((yv>=-5.1)&(yv<=-4.2)&(xv >= 8.2)&(xv <= 11.8)) {dev.off(); setup.mixed()} else fl1() } fl1 <- function(){ ans <- locator(1) yv <- ans$y xv <- ans$x if((yv>=-5.1)&(yv<=-4.2)&(xv >= 8.2)&(xv <= 11.8)) {dev.off(); setup.mixed()} else fl() } fl() } setup.mixed() on.exit(par(old.par)) }
DoMohrFig1 <- function(Stensor=matrix(c(5,1, 1, 3), ncol=2), rot1=NULL) { if(missing(Stensor)) {Stensor=matrix(c(5,1, 1, 3), ncol=2) } if(missing(rot1)) { s1 = Stensor } else { s1 = Stensor %*% rot1 } ES = eigen(s1) Rmohr = sqrt( ((s1[1,1]-s1[2,2])^2)/4 + s1[1,2]^2 ) Save = (ES$values[1]+ES$values[2])/2 ps1 = ES$values[1] ps2 = ES$values[2] ex = Save why = 0 cmohr = GEOmap::darc( rad=Rmohr, ang1=0, ang2=360, x1=ex, y1=why, n=1) RNGM = range( cmohr$x) Prange = c(0 , RNGM[2]+0.05*diff(RNGM)) plot(range( Prange ) , range(cmohr$y), type='n', asp=1, axes=FALSE, ann=FALSE) abline(v=0, h=0, lty=2) lines(cmohr, lwd=2) points(ex, why) u = par("usr") segments(ex, 0, ex, 0.9*u[3]) segments(ps1, 0.95*u[4] , ps1, 0) arrows( 0, 0.90*u[4] ,ps1, 0.90*u[4], length=0.1, code=2) text(mean(c( 0, ps1 ) ), 0.90*u[4], labels=expression(sigma[1]), pos=3, xpd=TRUE) segments(ps2, 0, ps2, 0.6*u[3]) arrows( 0, 0.58*u[3] ,ps2, 0.58*u[3], length=0.1, code=2) text(mean(c( 0, ps2 ) ), 0.58*u[3], labels=expression(sigma[2]), pos=3, xpd=TRUE) segments(ex, 0, ex, 0.9*u[3]) arrows( 0, 0.88*u[3] ,ex, 0.88*u[3], length=0.1, code=2) text(mean(c( 0, ex ) ), 0.88*u[3], labels=expression(sigma[ave]), pos=3, xpd=TRUE) points(s1[1,1], -s1[2,1]) points(s1[2,2], s1[2,1]) segments(s1[1,1], -s1[2,1], s1[2,2], s1[2,1]) text(s1[1,1], -s1[2,1], labels="X", adj =c(-1,1), font=2, xpd=TRUE) text(s1[2,2], s1[2,1], labels="Y", adj =c(1.2,-.7), font=2, xpd=TRUE) points(ps1, 0) points(ps2, 0) text(ps1, 0, labels="A", xpd=TRUE, adj =c(-.5,0) , font=2) text(ps2, 0, labels="B", xpd=TRUE, adj =c(1.5, 0) , font=2) segments(s1[1,1], -s1[2,1], s1[1,1], u[3]) arrows( 0, 0.98*u[3] , s1[1,1], 0.98*u[3], length=0.1, code=3) text(mean(c( 0, s1[1,1] ) ), 0.98*u[3] , labels=expression(sigma[x]), pos=3, xpd=TRUE) segments(s1[2,2], s1[2,1], s1[2,2], 0.8*u[4]) arrows( 0, 0.78*u[4] , s1[2,2], 0.78*u[4], length=0.1, code=3) sigylabx = mean(c( 0, s1[2,2] ) ) text(sigylabx, 0.78*u[4] , labels=expression(sigma[y]), pos=1, xpd=TRUE) segments(s1[1,1], -s1[2,1], u[2] , -s1[2,1]) arrows( (u[2]+ps1)/2 , 0, (u[2]+ps1)/2,-s1[2,1], code=3, length=0.1) text( (u[2]+ps1)/2, mean(c(0, -s1[2,1])), xpd=TRUE, labels=expression(tau[xy]), pos=4, xpd=TRUE) g1x = mean(c( 0, sigylabx)) segments(s1[2,2], s1[2,1], g1x, s1[2,1]) arrows( mean(c( g1x, sigylabx)), 0, mean(c( g1x, sigylabx)) , s1[2,1], code=3, length=0.1) text( mean(c( g1x, sigylabx)), mean(c(0, s1[2,1])), labels=expression(tau[xy]), pos=2, xpd=TRUE) }
library(knotR) filename <- "8_11.svg" a <- reader(filename) sym811 <- symmetry_object(a,Mver=NULL,xver=4) a <- symmetrize(a,sym811) ou811 <- matrix(c( 22,09, 10,21, 20,11, 07,19, 17,06, 12,16, 15,02, 03,13 ),ncol=2,byrow=TRUE) jj <- knotoptim(filename, symobj = sym811, ou = ou811, prob = 0, iterlim=3000,print.level=2,hessian=FALSE ) write_svg(jj, filename,safe=FALSE) dput(jj,file=sub('.svg','.S',filename))
check_can_create_screenlog_file <- function( beast2_options ) { testthat::expect_true(file.exists(beast2_options$input_filename)) text <- readr::read_lines(beast2_options$input_filename, progress = FALSE) screenlog_line <- stringr::str_subset( string = text, pattern = "<logger id=\"screenlog\"" ) testthat::expect_equal(length(screenlog_line), 1) matches <- stringr::str_match( string = screenlog_line, pattern = "fileName=\\\"([:graph:]+)\\\" " ) testthat::expect_equal(ncol(matches), 2) screenlog_filename <- matches[1, 2] if (is.na(screenlog_filename)) return() if (file.exists(screenlog_filename)) { file.remove(screenlog_filename) return() } tryCatch( beastier::check_can_create_file( filename = screenlog_filename, overwrite = FALSE ), error = function(e) { stop("Cannot create screenlog file '", screenlog_filename, "'") } ) invisible(beast2_options) }
rm(list=ls()) setwd("C:/Users/Tom/Documents/Kaggle/Santander") library(data.table) library(bit64) library(xgboost) library(stringr) submissionDate <- "30-11-2016" loadFile <- "" submissionFile <- "xgboost weighted trainAll 8, linear increase jun15 times6 back 13-0 no zeroing, exponential normalisation conditional" targetDate <- "12-11-2016" trainModelsFolder <- "trainTrainAll" trainAll <- grepl("TrainAll", trainModelsFolder) testFeaturesFolder <- "test" loadPredictions <- FALSE loadBaseModelPredictions <- FALSE savePredictions <- TRUE saveBaseModelPredictions <- TRUE savePredictionsBeforeNormalisation <- TRUE normalizeProdProbs <- TRUE normalizeMode <- c("additive", "linear", "exponential")[3] additiveNormalizeProds <- NULL fractionPosFlankUsers <- 0.035 expectedCountPerPosFlank <- 1.25 marginalNormalisation <- c("linear", "exponential")[2] monthsBackModels <- 0:13 monthsBackWeightDates <- rev(as.Date(paste(c(rep(2015, 9), rep(2016, 5)), str_pad(c(4:12, 1:5), 2, pad='0'), 28, sep="-"))) monthsBackModelsWeights <- rev(c(1.2, 1.3, 13, 0.1*(15:25))) weightSum <- sum(monthsBackModelsWeights) monthsBackLags <- 16:3 nominaNomPensSoftAveraging <- FALSE predictSubset <- FALSE nbLags <- length(monthsBackModelsWeights) if(nbLags != length(monthsBackModels) || nbLags != length(monthsBackLags) || nbLags != length(monthsBackWeightDates)) browser() predictionsFolder <- "Predictions" ccoNoPurchase <- FALSE zeroTargets <- NULL source("Common/exponentialNormaliser.R") monthProductWeightOverride <- NULL monthProductWeightOverride <- rbind(monthProductWeightOverride, data.frame(product = "ind_cco_fin_ult1", month = as.Date(c("2015-12-28" )), weight = 13) ) monthProductWeightOverride <- rbind(monthProductWeightOverride, data.frame(product = "ind_cco_fin_ult1", month = as.Date(c("2015-04-28", "2015-05-28", "2015-07-28", "2015-08-28", "2015-09-28", "2015-10-28", "2015-11-28", "2016-01-28", "2016-02-28", "2016-03-28", "2016-04-28", "2016-05-28" )), weight = 0) ) predictionsPath <- file.path(getwd(), "Submission", submissionDate, predictionsFolder) dir.create(predictionsPath, showWarnings = FALSE) if(saveBaseModelPredictions && !loadBaseModelPredictions){ baseModelPredictionsPath <- file.path(predictionsPath, submissionFile) dir.create(baseModelPredictionsPath, showWarnings = FALSE) } else{ if(loadBaseModelPredictions){ baseModelPredictionsPath <- file.path(predictionsPath, loadFile) } } if(loadPredictions){ rawPredictionsPath <- file.path(predictionsPath, paste0("prevNorm", loadFile, ".rds")) } else{ rawPredictionsPath <- file.path(predictionsPath, paste0("prevNorm", submissionFile, ".rds")) } posFlankClientsFn <- file.path(getwd(), "Feature engineering", targetDate, "positive flank clients.rds") posFlankClients <- readRDS(posFlankClientsFn) modelsBasePath <- file.path(getwd(), "First level learners", targetDate, trainModelsFolder) modelGroups <- list.dirs(modelsBasePath)[-1] nbModelGroups <- length(modelGroups) baseModelInfo <- NULL baseModels <- list() for(i in 1:nbModelGroups){ modelGroup <- modelGroups[i] slashPositions <- gregexpr("\\/", modelGroup)[[1]] modelGroupExtension <- substring(modelGroup, 1 + slashPositions[length(slashPositions)]) modelGroupFiles <- list.files(modelGroup) nbModels <- length(modelGroupFiles) monthsBack <- as.numeric(substring(gsub("Lag.*$", "", modelGroupExtension), 5)) lag <- as.numeric(gsub("^.*Lag", "", modelGroupExtension)) relativeWeightOrig <- monthsBackModelsWeights[match(monthsBack, monthsBackModels)] weightDate <- monthsBackWeightDates[match(monthsBack, monthsBackModels)] for(j in 1:nbModels){ modelInfo <- readRDS(file.path(modelGroup, modelGroupFiles[j])) targetProduct <- modelInfo$targetVar overrideId <- which(monthProductWeightOverride$product == targetProduct & monthProductWeightOverride$month == weightDate) if(length(overrideId)>0){ relativeWeight <- monthProductWeightOverride$weight[overrideId] } else{ relativeWeight <- relativeWeightOrig } baseModelInfo <- rbind(baseModelInfo, data.table( modelGroupExtension = modelGroupExtension, targetProduct = targetProduct, monthsBack = monthsBack, modelLag = lag, relativeWeight = relativeWeight) ) baseModels <- c(baseModels, list(modelInfo)) } } baseModelInfo[, modelId := 1:nrow(baseModelInfo)] uniqueBaseModels <- sort(unique(baseModelInfo$targetProduct)) for(i in 1:length(uniqueBaseModels)){ productIds <- baseModelInfo$targetProduct==uniqueBaseModels[i] productWeightSum <- baseModelInfo[productIds, sum(relativeWeight)] normalizeWeightRatio <- weightSum/productWeightSum baseModelInfo[productIds, relativeWeight := relativeWeight* normalizeWeightRatio] } if(all(is.na(baseModelInfo$modelLag))){ nbGroups <- length(unique(baseModelInfo$modelGroupExtension)) baseModelInfo$monthsBack <- 0 baseModelInfo$modelLag <- 17 baseModelInfo$relativeWeight <- 1 monthsBackLags <- rep(17, nbGroups) nbLags <- length(monthsBackLags) monthsBackModelsWeights <- rep(1, nbGroups) weightSum <- sum(monthsBackModelsWeights) } baseModelInfo <- baseModelInfo[order(monthsBack), ] baseModelNames <- unique(baseModelInfo[monthsBack==0, targetProduct]) testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate, testFeaturesFolder, "Lag3 features.rds")) if(predictSubset){ testDataLag <- testDataLag[1:predictFirst] } testDataPosFlank <- testDataLag$ncodpers %in% posFlankClients trainFn <- "train/Back13Lag3 features.rds" colOrderData <- readRDS(file.path(getwd(), "Feature engineering", targetDate, trainFn)) targetCols <- grep("^ind_.*_ult1$", names(colOrderData), value=TRUE) nbBaseModels <- length(targetCols) countContributions <- readRDS(file.path(getwd(), "Feature engineering", targetDate, "monthlyRelativeProductCounts.rds")) if(!trainAll){ posFlankModelInfo <- baseModelInfo[targetProduct=="hasNewProduct"] newProdPredictions <- rep(0, nrow(testDataLag)) if(nrow(posFlankModelInfo) != nbLags) browser() for(i in 1:nbLags){ cat("Generating new product predictions for lag", i, "of", nbLags, "\n") lag <- posFlankModelInfo[i, lag] weight <- posFlankModelInfo[i, relativeWeight] newProdModel <- baseModels[[posFlankModelInfo[i, modelId]]] testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate, testFeaturesFolder, paste0("Lag", lag, " features.rds"))) if(predictSubset){ testDataLag <- testDataLag[1:predictFirst] } predictorData <- testDataLag[, newProdModel$predictors, with=FALSE] predictorDataM <- data.matrix(predictorData) rm(predictorData) gc() newProdPredictionsLag <- predict(newProdModel$model, predictorDataM) newProdPredictions <- newProdPredictions + newProdPredictionsLag*weight } newProdPredictions <- newProdPredictions/weightSum meanGroupPredsMayFlag <- c(mean(newProdPredictions[testDataLag$hasMay15Data==0]), mean(newProdPredictions[testDataLag$hasMay15Data==1])) meanGroupPredsPosFlank <- c(mean(newProdPredictions[!testDataPosFlank]), mean(newProdPredictions[testDataPosFlank])) expectedPosFlanks <- sum(newProdPredictions) leaderboardPosFlanks <- fractionPosFlankUsers*nrow(testDataLag) normalisedProbRatio <- leaderboardPosFlanks/expectedPosFlanks cat("Expected/leaderboard positive flank ratio", round(1/normalisedProbRatio, 2), "\n") if(marginalNormalisation == "linear"){ newProdPredictions <- newProdPredictions * normalisedProbRatio } else{ newProdPredictions <- probExponentNormaliser(newProdPredictions, normalisedProbRatio) } } else{ newProdPredictions <- rep(1, nrow(testDataLag)) } if(loadPredictions && file.exists(rawPredictionsPath)){ allPredictions <- readRDS(rawPredictionsPath) } else{ allPredictions <- NULL for(lagId in 1:nbLags){ cat("\nGenerating positive flank predictions for lag", lagId, "of", nbLags, "@", as.character(Sys.time()), "\n\n") lag <- monthsBackLags[lagId] testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate, testFeaturesFolder, paste0("Lag", lag, " features.rds"))) if(predictSubset){ testDataLag <- testDataLag[1:predictFirst] } for(i in 1:nbBaseModels){ targetVar <- targetCols[i] targetModelId <- baseModelInfo[targetProduct==targetVar & modelLag==lag, modelId] if(length(targetModelId)>1){ targetModelId <- targetModelId[lagId] } targetModel <- baseModels[[targetModelId]] weight <- baseModelInfo[modelId == targetModelId, relativeWeight] if(targetModel$targetVar != targetVar) browser() cat("Generating test predictions for model", i, "of", nbBaseModels, "\n") baseModelPredPath <- file.path(baseModelPredictionsPath, paste0(targetVar, " Lag ", lag, ".rds")) if(loadBaseModelPredictions && file.exists(baseModelPredPath)){ predictionsDT <- readRDS(baseModelPredPath) } else{ if(targetVar %in% zeroTargets){ predictions <- rep(0, nrow(testDataLag)) } else{ predictorData <- testDataLag[, targetModel$predictors, with=FALSE] predictorDataM <- data.matrix(predictorData) rm(predictorData) gc() predictions <- predict(targetModel$model, predictorDataM) alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) | testDataLag[[paste0(targetVar, "Lag1")]] == 1 predictionsPrevNotOwned <- predictions[!alreadyOwned] } predictions[alreadyOwned] <- 0 predictionsDT <- data.table(ncodpers = testDataLag$ncodpers, predictions = predictions, product = targetVar) } predictionsDT[, weightedPrediction := predictionsDT$predictions*weight] if(targetVar %in% allPredictions$product){ allPredictions[product==targetVar, weightedPrediction:= weightedPrediction + predictionsDT$weightedPrediction] } else{ allPredictions <- rbind(allPredictions, predictionsDT) } if(saveBaseModelPredictions && !loadBaseModelPredictions){ predictionsDT[, weightedPrediction:=NULL] saveRDS(predictionsDT, baseModelPredPath) } } } allPredictions[, prediction := weightedPrediction / weightSum] allPredictions[, weightedPrediction := NULL] allPredictions[, predictions := NULL] if(savePredictionsBeforeNormalisation){ saveRDS(allPredictions, file=rawPredictionsPath) } } if(nominaNomPensSoftAveraging){ nominaProb <- allPredictions[product == "ind_nomina_ult1", prediction] * newProdPredictions nomPensProb <- allPredictions[product == "ind_nom_pens_ult1", prediction] * newProdPredictions avIds <- nominaProb>0 & nomPensProb>0 & (nomPensProb-nominaProb < 0.1) avVals <- (nominaProb[avIds] + nomPensProb[avIds])/2 ncodpers <- unique(allPredictions$ncodpers) avNcodPers <- ncodpers[avIds] allPredictions[ncodpers %in% avNcodPers & product == "ind_nomina_ult1", prediction := avVals] allPredictions[ncodpers %in% avNcodPers & product == "ind_nom_pens_ult1", prediction := avVals] } probMultipliers <- rep(NA, nbBaseModels) if(normalizeProdProbs){ for(i in 1:nbBaseModels){ cat("Normalizing product predictions", i, "of", nbBaseModels, "\n") targetVar <- targetCols[i] alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) | testDataLag[[paste0(targetVar, "Lag1")]] == 1 predictions <- allPredictions[product==targetVar, prediction] predictionsPrevNotOwned <- predictions[!alreadyOwned] if(suppressWarnings(max(predictions[alreadyOwned]))>0) browser() predictedPosFlankCount <- sum(predictionsPrevNotOwned * newProdPredictions[!alreadyOwned]) probMultiplier <- nrow(testDataLag) * fractionPosFlankUsers * expectedCountPerPosFlank * countContributions[17, i] / predictedPosFlankCount probMultipliers[i] <- probMultiplier if(i %in% c(3, 5, 7, 13, 18, 19, 22, 23, 24)) browser() if(is.finite(probMultiplier)){ if(normalizeMode == "additive" || targetVar %in% additiveNormalizeProds){ predictions[!alreadyOwned] <- predictions[!alreadyOwned] + (probMultiplier-1)*mean(predictions[!alreadyOwned]) } else{ if(normalizeMode == "linear"){ predictions[!alreadyOwned] <- predictions[!alreadyOwned] * probMultiplier } else{ predictions[!alreadyOwned] <- probExponentNormaliser( predictions[!alreadyOwned], probMultiplier, weights=newProdPredictions[!alreadyOwned]) } } allPredictions[product==targetVar, prediction:=predictions] } } } if(ccoNoPurchase){ allPredictions[!ncodpers %in% posFlankClients & ncodpers %in% testDataLag[ind_cco_fin_ult1Lag1==0, ncodpers] & product == "ind_cco_fin_ult1", prediction := 10] } setkey(allPredictions, ncodpers) allPredictions[,order_predict := match(1:length(prediction), order(-prediction)), by=ncodpers] allPredictions <- allPredictions[order(ncodpers, -prediction), ] orderCount <- allPredictions[, .N, .(ncodpers, order_predict)] if(max(orderCount$N)>1) browser() hist(allPredictions[order_predict==1, prediction]) topPredictions <- allPredictions[order_predict==1, .N, product] topPredictions <- topPredictions[order(-N)] topPredictionsPosFlanks <- allPredictions[order_predict==1 & ncodpers %in% posFlankClients, .N, product] topPredictionsPosFlanks <- topPredictionsPosFlanks[order(-N)] productRankDelaFin <- allPredictions[product=="ind_dela_fin_ult1", .N, order_predict] productRankDelaFin <- productRankDelaFin[order(order_predict),] productRankDecoFin <- allPredictions[product=="ind_deco_fin_ult1", .N, order_predict] productRankDecoFin <- productRankDecoFin[order(order_predict),] productRankTjcrFin <- allPredictions[product=="ind_tjcr_fin_ult1", .N, order_predict] productRankTjcrFin <- productRankTjcrFin[order(order_predict),] productRankRecaFin <- allPredictions[product=="ind_reca_fin_ult1", .N, order_predict] productRankRecaFin <- productRankRecaFin[order(order_predict),] allPredictions[, totalProb := prediction * rep(newProdPredictions, each = nbBaseModels)] meanProductProbs <- allPredictions[, .(meanCondProb = mean(prediction), meanProb = mean(totalProb), totalProb = sum(totalProb)), product] meanProductProbs <- meanProductProbs[order(-meanProb), ] productString <- paste(allPredictions[order_predict==1, product], allPredictions[order_predict==2, product], allPredictions[order_predict==3, product], allPredictions[order_predict==4, product], allPredictions[order_predict==5, product], allPredictions[order_predict==6, product], allPredictions[order_predict==7, product]) if(length(productString) != nrow(testDataLag)) browser() submission <- data.frame(ncodpers = testDataLag$ncodpers, added_products = productString) paddedSubmission <- fread("Data/sample_submission.csv") paddedSubmission[, added_products := ""] matchIds <- match(submission$ncodpers, paddedSubmission$ncodpers) paddedSubmission[matchIds, added_products := submission$added_products] write.csv(paddedSubmission, file.path(getwd(), "Submission", submissionDate, paste0(submissionFile, ".csv")), row.names = FALSE) if(savePredictions){ saveRDS(allPredictions, file=file.path(predictionsPath, paste0(submissionFile, ".rds"))) } cat("Submission file created successfully!\n", nrow(submission)," records were predicted (", round(nrow(submission)/nrow(paddedSubmission)*100,2), "%)\n", sep="")
test_that("Inner join example query skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_equal( query("SELECT * FROM toys JOIN makers ON toys.maker_id = makers.id"), toys %>% inner_join(makers, by = c(maker_id = "id"), suffix = c(".toys", ".makers")) %>% rename(toys.name = "name.toys", makers.name = "name.makers") ) }) test_that("Inner join example query skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_equal( query("SELECT * FROM toys t JOIN makers m ON toys.maker_id = makers.id"), toys %>% inner_join(makers, by = c(maker_id = "id"), suffix = c(".t", ".m")) %>% rename(t.name = "name.t", m.name = "name.m") ) }) test_that("Inner join example query skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_equal( query("SELECT * FROM toys t JOIN makers m ON t.maker_id = m.id"), toys %>% inner_join(makers, by = c(maker_id = "id"), suffix = c(".t", ".m")) %>% rename(t.name = "name.t", m.name = "name.m") ) }) test_that("Inner join example query skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_equal( query("SELECT toys.id AS id, toys.name AS toy, price, maker_id, makers.name AS maker, city FROM toys JOIN makers ON toys.maker_id = makers.id;"), toys %>% inner_join(makers, by = c(maker_id = "id"), suffix = c(".toys", ".makers")) %>% rename(toys.name = "name.toys", makers.name = "name.makers") %>% select(id, toy = toys.name, price, maker_id, maker = makers.name, city) ) }) test_that("Inner join example query skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_equal( query("SELECT t.id AS id, t.name AS toy, price, maker_id, m.name AS maker, city FROM toys t JOIN makers m ON t.maker_id = m.id;"), toys %>% inner_join(makers, by = c(maker_id = "id"), suffix = c(".t", ".m")) %>% rename(t.name = "name.t", m.name = "name.m") %>% select(id, toy = t.name, price, maker_id, maker = m.name, city) ) }) test_that("Inner join example query skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_equal( query("SELECT m.name AS maker, AVG(price) AS avg_price FROM toys t JOIN makers m ON t.maker_id = m.id GROUP BY maker ORDER BY avg_price;"), toys %>% inner_join(makers, by = c(maker_id = "id"), suffix = c(".toys", ".makers")) %>% rename(toys.name = "name.toys", makers.name = "name.makers") %>% rename(maker = makers.name) %>% group_by(maker) %>% summarise(avg_price = mean(price, na.rm = TRUE)) %>% ungroup() %>% arrange(avg_price) ) }) test_that("Inner join example query skip_if_not(exists("flights") && exists("airlines"), message = "Test data not loaded") expect_equal( query("SELECT concat_ws(' ', 'Now boarding', name, 'flight', CAST(flight AS string)) FROM flights f JOIN airlines a USING (carrier)"), flights %>% inner_join(airlines, by = "carrier") %>% transmute(stringr::str_c("Now boarding", name, "flight", as.character(flight), sep = " ")) ) }) test_that("Inner join example query skip_if_not(exists("flights") && exists("airlines"), message = "Test data not loaded") expect_equal( query("SELECT concat_ws(' ', 'Now boarding', airlines.name, 'flight', CAST(flight AS string)) FROM flights f JOIN airlines a USING (carrier)"), flights %>% inner_join(airlines, by = "carrier") %>% transmute(stringr::str_c("Now boarding", name, "flight", as.character(flight), sep = " ")) ) }) test_that("Inner join example query skip_if_not(exists("flights") && exists("airlines"), message = "Test data not loaded") expect_equal( query("SELECT concat_ws(' ', 'Now boarding', a.name, 'flight', CAST(f.flight AS string)) FROM flights f JOIN airlines a USING (carrier)"), flights %>% inner_join(airlines, by = "carrier") %>% transmute(stringr::str_c("Now boarding", name, "flight", as.character(flight), sep = " ")) ) }) test_that("Inner join example query skip_if_not(exists("flights") && exists("airlines"), message = "Test data not loaded") expect_equal( query("SELECT concat_ws(' ', 'Now boarding', airlines.name, 'flight', CAST(flights.flight AS string)) FROM flights f JOIN airlines a USING (carrier)"), flights %>% inner_join(airlines, by = "carrier") %>% transmute(stringr::str_c("Now boarding", name, "flight", as.character(flight), sep = " ")) ) }) test_that("Join fails on misqualified column reference example skip_if_not(exists("flights") && exists("airlines"), message = "Test data not loaded") expect_error( query("SELECT concat_ws(' ', 'Now boarding', a.name, 'flight', CAST(a.flight AS string)) FROM flights f JOIN airlines a USING (carrier)"), "a.flight" ) }) test_that("Join fails when column names have suffixes matching table names or aliases", { expect_error( query("select * FROM iris JOIN iris AS Length ON Species = Species"), "Names" ) }) test_that("Join fails on misqualified column reference example skip_if_not(exists("flights") && exists("airlines"), message = "Test data not loaded") expect_error( query("SELECT concat_ws(' ', 'Now boarding', airlines.name, 'flight', CAST(airlines.flight AS string)) FROM flights f JOIN airlines a USING (carrier)"), "airlines.flight" ) }) test_that("Join fails on ambiguous column reference example skip_if_not(exists("toys") && exists("makers"), message = "Test data not loaded") expect_error( query("SELECT name FROM toys t JOIN makers m ON toys.maker_id = makers.id"), "name" ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games ON game = name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON game = name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games ON name = game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON name = game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games ON inventory.game = games.name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games ON games.name = inventory.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON i.game = g.name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON g.name = i.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON inventory.game = g.name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON g.name = inventory.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON i.game = games.name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games g ON games.name = i.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games ON games.name = i.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games ON name = i.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i JOIN games ON i.game = name"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games g ON g.name = inventory.game"), inventory %>% inner_join(games, by = c(game = "name")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory JOIN games_with_col_renamed USING (game)") }, inventory %>% inner_join(games %>% rename(game = name), by = c("game")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g USING (game)") }, inventory %>% inner_join(games %>% rename(game = name), by = c("game")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON game = game") }, inventory %>% inner_join(games %>% rename(game = name), by = c("game")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games g ON game = g.name"), inventory %>% inner_join(games %>% rename(game = name), by = c("game")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON g.game = game") }, inventory %>% inner_join(games %>% rename(game = name), by = c("game")) ) }) test_that("Join alias/conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory JOIN games g ON games.name = game"), inventory %>% inner_join(games %>% rename(game = name), by = c("game")) ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON i.foo = i.bar"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory JOIN games g ON i.game = i.bar"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory JOIN games g ON i.foo = i.game"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON name = name"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON name = name") }, "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON g.name = name"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON g.foo = game"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON g.name = game") }, "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON q.game = game") }, "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON foo = bar"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON foo = g.bar"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON foo = z.bar"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON inventory.foo = bar"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON i.zzz = g.zzz"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON g.zzz = i.zzz"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON mmm.name = i.game"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON yyy.game = zzz.game") }, "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON foo = i.game"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON i.name = g.game"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON g.game = i.game"), "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( { games_with_col_renamed <<- games %>% rename(game = name) query("SELECT * FROM inventory i JOIN games_with_col_renamed g ON i.game = i.game") }, "Invalid" ) }) test_that("Bad join conditions example skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT * FROM inventory i JOIN games g ON g.game = i.name"), "Invalid" ) }) test_that("Inner join with two join conditions example query skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory INNER JOIN games ON inventory.game = games.name AND inventory.price = games.list_price"), inventory %>% inner_join(games, by = c(game = "name", price = "list_price")) ) }) test_that("Inner join with two join conditions example query skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT * FROM inventory i INNER JOIN games g ON i.game = g.name AND i.price = g.list_price"), inventory %>% inner_join(games, by = c(game = "name", price = "list_price")) ) }) test_that("Left semi-join example query skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT name, list_price FROM games g LEFT SEMI JOIN inventory i ON g.name = i.game"), games %>% semi_join(inventory, by = c(name = "game")) %>% select(name, list_price) ) }) test_that("Left anti-join example query skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_equal( query("SELECT name, list_price FROM games g LEFT ANTI JOIN inventory i ON g.name = i.game"), games %>% anti_join(inventory, by = c(name = "game")) %>% select(name, list_price) ) }) test_that("Left outer join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT empl_id, first_name, e.office_id AS office_id, city FROM employees e LEFT OUTER JOIN offices o ON e.office_id = o.office_id;"), employees %>% left_join(offices, by = "office_id") %>% select(empl_id, first_name, office_id, city) ) }) test_that("Left outer join fails when query includes qualified join key column from the right table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city FROM offices o LEFT OUTER JOIN employees e USING (office_id) WHERE e.office_id IS NULL"), "e.office_id" ) }) test_that("Full outer join fails when query includes qualified join key column from the right table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city FROM offices o FULL OUTER JOIN employees e USING (office_id) WHERE e.office_id IS NULL"), "e.office_id" ) }) test_that("Right outer join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT empl_id, first_name, o.office_id AS office_id, city FROM employees e RIGHT OUTER JOIN offices o ON e.office_id = o.office_id;"), employees %>% right_join(offices, by = "office_id") %>% select(empl_id, first_name, office_id, city) ) }) test_that("Right outer join fails when query includes qualified join key column from the left table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT first_name, last_name FROM offices o RIGHT OUTER JOIN employees e USING (office_id) WHERE o.office_id IS NULL"), "o.office_id" ) }) test_that("Full outer join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT empl_id, first_name, office_id, city FROM employees e FULL OUTER JOIN offices o ON e.office_id = o.office_id;"), employees %>% full_join(offices, by = "office_id") %>% select(empl_id, first_name, office_id, city) ) }) test_that("Full outer join fails when query includes qualified join key column from the left table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT first_name, last_name FROM offices o FULL OUTER JOIN employees e USING (office_id) WHERE o.office_id IS NULL"), "o.office_id" ) }) test_that("Full outer join with USING fails when query includes qualified join key columns from both tables", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city, first_name, last_name FROM offices o FULL OUTER JOIN employees e USING (office_id) WHERE e.office_id IS NULL OR o.office_id IS NULL"), "\\Qo.office_id, e.office_id\\E|\\Qe.office_id, o.office_id\\E" ) }) test_that("Full outer join with ON and table names fails when query includes qualified join key column from the right table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city FROM offices o FULL OUTER JOIN employees e ON o.office_id = e.office_id WHERE e.office_id IS NULL"), "e.office_id" ) }) test_that("Full outer join with ON and table aliases fails when query includes qualified join key column from the right table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city FROM offices o FULL OUTER JOIN employees e ON offices.office_id = employees.office_id WHERE e.office_id IS NULL"), "e.office_id" ) }) test_that("Full outer join with ON fails when query includes table-name-qualified join key column from the right table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city FROM offices o FULL OUTER JOIN employees e ON o.office_id = e.office_id WHERE employees.office_id IS NULL"), "employees.office_id" ) }) test_that("Full outer join with ON and unqualified conditions fails when query includes qualified join key column from the right table", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_error( query("SELECT city FROM offices o FULL OUTER JOIN employees e ON office_id = office_id WHERE e.office_id IS NULL"), "e.office_id" ) }) test_that("Left outer join example with all clauses returns expected result", { skip_if_not(exists("flights") && exists("planes"), message = "Test data not loaded") expect_equal( { my_query <- "SELECT origin, dest, round(AVG(distance)) AS dist, round(COUNT(*)/10) AS flights_per_year, round(SUM(seats)/10) AS seats_per_year, round(AVG(arr_delay)) AS avg_arr_delay FROM flights f LEFT JOIN planes p ON f.tailnum = p.tailnum WHERE distance BETWEEN 300 AND 400 GROUP BY origin, dest HAVING flights_per_year > 100 ORDER BY seats_per_year DESC LIMIT 6;" query(my_query) }, flights %>% left_join(planes, by = "tailnum", suffix = c(".f", ".p"), na_matches = "never") %>% rename(f.year = "year.f", p.year = "year.p") %>% filter(between(distance, 300, 400)) %>% group_by(origin, dest) %>% filter(round(n() / 10) > 100) %>% summarise( dist = round(mean(distance, na.rm = TRUE)), flights_per_year = round(n() / 10), seats_per_year = round(sum(seats, na.rm = TRUE) / 10), avg_arr_delay = round(mean(arr_delay, na.rm = TRUE)) ) %>% ungroup() %>% arrange(desc(seats_per_year)) %>% head(6) ) }) test_that("Natural inner join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT * FROM offices NATURAL JOIN employees"), offices %>% inner_join(employees) ) }) test_that("Natural left outer join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT * FROM offices NATURAL LEFT OUTER JOIN employees"), offices %>% left_join(employees) ) }) test_that("Natural right outer join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT * FROM offices NATURAL RIGHT OUTER JOIN employees"), offices %>% right_join(employees) ) }) test_that("Natural full outer join example query skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_equal( query("SELECT * FROM offices NATURAL FULL OUTER JOIN employees"), offices %>% full_join(employees) ) }) test_that("Natural join example query generates the expected message", { skip_if_not(exists("offices") && exists("employees"), message = "Test data not loaded") expect_message( query("SELECT * FROM offices NATURAL JOIN employees"), "office_id" ) }) test_that("Right anti-join fails", { skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT name, list_price FROM inventory i RIGHT ANTI JOIN games g ON i.game = g.name"), "Unsupported" ) }) test_that("Right semi-join fails", { skip_if_not(exists("inventory") && exists("games"), message = "Test data not loaded") expect_error( query("SELECT name, list_price FROM inventory i RIGHT SEMI JOIN games g ON i.game = g.name"), "Unsupported" ) }) test_that("Cross join fails", { skip_if_not(exists("card_rank") && exists("card_suit"), message = "Test data not loaded") expect_error( query("SELECT rank, suit FROM card_rank CROSS JOIN card_suit;"), "Unsupported" ) }) test_that("Join with three tables fails", { skip_if_not(exists("employees") && exists("offices") && exists("orders"), message = "Test data not loaded") expect_error( query("SELECT city, SUM(total) total FROM orders LEFT JOIN employees USING (empl_id) LEFT JOIN offices USING (office_id) GROUP BY city"), "unsupported" ) }) test_that("Join fails when data object does not exist", { expect_error( query("SELECT a FROM a435irawjesz9834are JOIN w3tzldvjsdfkgjwetro USING (b)"), "exist" ) }) test_that("Join fails when data object has unsupported type", { skip_if_not(exists("letters"), message = "Test data not loaded") expect_error( query("SELECT * FROM letters NATURAL JOIN state.name"), "supported" ) }) test_that("Inner join does not match NAs", { expect_equal( { join_test_na_match_data_x <<- data.frame(k1 = c(NA, NA, 3, 4, 5), k2 = c(1, NA, NA, 4, 5), data = 1:5) join_test_na_match_data_y <<- data.frame(k1 = c(NA, 2, NA, 4, 5), k2 = c(NA, NA, 3, 4, 5), data = 1:5) query("select COUNT(*) FROM join_test_na_match_data_x JOIN join_test_na_match_data_y USING (k1)") %>% pull(1) }, 2L ) })
addToTree.default <- function(tree, input){ stop("object \"",substitute(tree),"\" is not of the appropriate class \"tstTree\"") }
estimateSUR <- function(PPP, xi_PPP_X, integrated = TRUE, N_ppp, method = "discrete", SUR_pop, r = N.batch, optimcontrol = list(pop.size = 50*d, max.generations = 10*d), approx.pnorm, J = 0, N.batch = foreach::getDoParWorkers(), verbose = 0, ... ){ X <- NULL N <- length(PPP$final_U) d <- dim(PPP$final_X)[1] n <- dim(xi_PPP_X$Kinv_kn)[1] if(method=='discrete' && missing(SUR_pop)){ SUR_pop = cbind(PPP$X, PPP$final_X) u_SUR_pop <- c(PPP$U, PPP$final_U) N_pop = dim(SUR_pop)[2] xi_SUR_POP <- xi_PPP_X SUR_aug <- rbind(SUR_pop, matrix(xi_SUR_POP$mean, nrow = 1), matrix(xi_SUR_POP$sd, nrow = 1), xi_SUR_POP$kn, xi_SUR_POP$Kinv_kn) } if(!missing(N_ppp) && N_ppp<N) { ind <- sample(x = 1:N, size = N_ppp, replace = FALSE) sel1 <- names(PPP$U)%in%ind PPP$X <- PPP$X[,sel1] PPP$U <- PPP$U[sel1] sel2 <- names(PPP$final_U)%in%ind PPP$final_X <- PPP$final_X[,sel2] PPP$final_U <- PPP$final_U[sel2] xi_PPP_X$mean <- xi_PPP_X$mean[c(sel1, sel2)] xi_PPP_X$sd <- xi_PPP_X$sd[c(sel1, sel2)] xi_PPP_X$kn <- as.matrix(xi_PPP_X$kn[,c(sel1, sel2)]) xi_PPP_X$Kinv_kn <- as.matrix(xi_PPP_X$Kinv_kn[,c(sel1, sel2)]) N <- N_ppp } x = PPP$final_X u = PPP$final_U u_lpa <- NULL xi_x <- xi_PPP_X if(integrated == TRUE){ x = cbind(PPP$X, x) u = c(PPP$U, u) u_lpa <- rep(PPP$U, each = N) } else { xi_x$mean = tail(xi_PPP_X$mean, N) xi_x$sd = tail(xi_PPP_X$sd, N) xi_x$kn = t(tail(t(xi_PPP_X$kn), N)) xi_x$Kinv_kn = t(tail(t(xi_PPP_X$Kinv_kn), N)) } args = list(...) args$x = x args$u = u args$u_lpa = u_lpa args$xi_x = xi_x args$integrated = integrated args$N = N if(approx.pnorm) { x_pnorm <- seq(from = -4, to = 4, by = 0.2) args$pnorm = stats::approxfun(x_pnorm, pnorm(x_pnorm), yleft = 0, yright = 1) } args$Xnew <- Xnew <- NULL args$xi_Xnew <- xi_Xnew <- NULL cat(" * Evaluation of SUR criterion: integrated = ",integrated, ", r = ", ifelse(is.null(args$r), 1, args$r), ", approx = ",ifelse(is.null(args$approx), FALSE, args$approx),", approx.pnorm = ",approx.pnorm,", optim = ", method,", N_ppp = ", ifelse(missing(N_ppp),N, N_ppp)," \n", sep = "") sur = list(x = NULL, u = NULL, t = NULL) for(k in 1:r){ if(method=="discrete"){ SUR <- foreach::foreach(X = iterators::iter(SUR_aug, by ='col', chunksize = ceiling(N_pop/N.batch)), .combine = 'c', .export = 'fSUR', .options.multicore = list(set.seed = TRUE), .errorhandling = "pass") %dopar% { tmp <- c(apply(X, 2, function(xaug){ args$xnew <- xaug[1:d] args$xi_xnew <- list(mean = xaug[d+1], sd = xaug[d+2], kn = xaug[(d+3):(d+2+n)], Kinv_kn = tail(xaug, n)) do.call(fSUR, args) })) return(tmp) } if(class(SUR)!="numeric"){ message(' ! memory issue with parallel computing, approximated SUR used insteead !') args$approx = TRUE x_pnorm <- seq(from = -4, to = 4, by = 0.2) args$pnorm = stats::approxfun(x_pnorm, pnorm(x_pnorm), yleft = 0, yright = 1) SUR <- foreach::foreach(X = iterators::iter(SUR_aug, by ='col', chunksize = ceiling(N_pop/N.batch)), .combine = 'c', .export = 'fSUR', .options.multicore = list(set.seed = TRUE), .errorhandling = "pass") %dopar% { tmp <- c(apply(X, 2, function(xaug){ args$xnew <- xaug[1:d] args$xi_xnew <- list(mean = xaug[d+1], sd = xaug[d+2], kn = xaug[(d+3):(d+2+n)], Kinv_kn = tail(xaug, n)) do.call(fSUR, args) })) return(tmp) } } if(class(SUR)!="numeric"){ message(' ! memory issue with parallel computing, standard SUR used insteead !') args$integrated = FALSE SUR <- foreach::foreach(X = iterators::iter(SUR_aug, by ='col', chunksize = ceiling(N_pop/N.batch)), .combine = 'c', .export = 'fSUR', .options.multicore = list(set.seed = TRUE), .errorhandling = "pass") %dopar% { tmp <- c(apply(X, 2, function(xaug){ args$xnew <- xaug[1:d] args$xi_xnew <- list(mean = xaug[d+1], sd = xaug[d+2], kn = xaug[(d+3):(d+2+n)], Kinv_kn = tail(xaug, n)) do.call(fSUR, args) })) return(tmp) } } if(class(SUR)!="numeric"){ print(SUR) } ind_min = which.min(SUR) SUR_point <- SUR_pop[,ind_min] SUR_aug <- SUR_aug[,-ind_min] sur$u = c(sur$u, u_SUR_pop[ind_min]) sur$t = c(sur$t, ind_min/length(SUR)) } else { f_gen <- function(xnew) { args$xnew = xnew do.call(fSUR, args) } SUR_point <- do.call(rgenoud::genoud, c(optimcontrol, list(fn = f_gen, nvars = d, print.level = verbose)))$par } Xnew = cbind(Xnew, as.matrix(SUR_point)) sur$x = cbind(sur$x, SUR_point) } return(sur) } t.list <- function(l){ lapply(split(do.call("c", l), names(l[[1]])), unname) }
context("Cleaning") library(missCompare) data("clindata_miss") small <- clindata_miss[1:80, 1:4] small$string <- "string" test_that("error if strings present", { testthat::expect_error(clean(small)) }) small <- clindata_miss[1:80, 1:4] test_that("message for numeric conversion", { testthat::expect_message(clean(small)) }) small$sex <- as.numeric(small$sex) test_that("no message for numeric conversion", { expect_message(clean(small, var_removal_threshold = 0.7), NA) }) small$age[1:60] <- NA test_that("message for variable removal", { expect_message(clean(small, var_removal_threshold = 0.5)) }) small$age <- NULL small[c(1:10),] <- NA test_that("message for individual removal", { expect_message(clean(small, ind_removal_threshold = 1)) }) small <- clindata_miss[1:80, 1:4] cleaned <- clean(small) test_that("output dataset obs", { expect_output(str(cleaned), "80 obs") }) test_that("output dataset vars", { expect_output(str(cleaned), "4 variables") }) test_that("equal dims", { expect_equal(dim(small), dim(cleaned)) }) rm(list=ls())
`ROTY` <- function( deg ) { rad1 = deg * 0.0174532925199; r = diag(4) r[1, 1] = cos(rad1) r[3, 1] = sin(rad1) r[3, 3] = r[1, 1] r[1, 3] = -r[3, 1] return(r) }
summary_round_helper <- function( obji, digits, exclude=NULL, print=TRUE) { NC <- ncol(obji) ind <- 1:NC if ( ! is.null(exclude) ){ ind2 <- which( colnames(obji) %in% exclude ) ind <- setdiff( ind, ind2 ) } obji[,ind] <- round( obji[,ind], digits ) rownames(obji) <- NULL print(obji) invisible(obji) }
svr.gacv <- function(obj){ gacv <- rep(0, length(obj$lambda)) n <- length(obj$y) y <- obj$y svr.eps <- obj$eps for(i in 1:length(obj$lambda)){ fx <- ( 1/obj$lambda[i]) * (obj$theta[,i]%*%obj$Kscript + obj$theta0[i]) loss_gacv <- loss(t(fx), y, svr.eps) gacv[i] <- loss_gacv / ( n - (length(obj$Elbow.L[[i]]) + length(obj$Elbow.R[[i]])) ) } lambda3 <- obj$lambda[which.min(gacv)] theta3 <- obj$theta[,which.min(gacv)] theta3.0 <- obj$theta0[which.min(gacv)] elbow.l <- obj$Elbow.L[[which.min(gacv)]] elbow.r <- obj$Elbow.R[[which.min(gacv)]] return(list(GACV = gacv, optimal.lambda = lambda3, Elbow.L = elbow.l, Elbow.R = elbow.r, theta = theta3, theta0 = theta3.0)) }
add_group_item <- function (resource_details, ...) { json_arg <- toJSON(resource_details, auto_unbox=TRUE) res <- tubern_POST("groupItems", body = json_arg, encode='json', ...) res }
fs::file_copy("pkgdown/extra.css", new_path = "docs/extra.css", overwrite = TRUE) pkgdown::build_home() Sys.sleep(1) try(fs::file_delete("pkgdown/index.html")) Sys.sleep(1) rmarkdown::render("pkgdown/index.Rmd", envir = new.env()) library(tidyverse) index <- read_lines("docs/index.html", lazy = FALSE) ttle_indx <- which(str_detect(index, "HIGHCHARTER")) ttle <- index[[ttle_indx]] ttle <- str_replace(ttle, "HIGHCHARTER", "<span id=\"brand\"> h|1i|0g|3h|2c|1h|2a|1r|3t|2e|1r|2{rpackage}</span>") index[[ttle_indx]] <- ttle indx1 <- which(str_detect(index, "section level2")) indx1 <- indx1[[1]] indx1 <- indx1 - 1 index[(indx1 + -1:1)] %>% tibble() indx1 index_new <- read_lines("pkgdown/index.html") scripts <- str_subset(index_new, "index_files") scripts <- str_subset(scripts, "bootstrap|tabsets|highlightjs", negate = TRUE) index_new1 <- which(str_detect(index_new, "section level2")) index_new1 <- index_new1[[1]] index_new[(index_new1 + -1:1)] %>% tibble() index_new2 <- which(str_detect(index_new, "<span></span>")) index_new2 <- index_new2 + 1 index_new[(index_new2 + -1:1)] %>% tibble() index_final <- c( index[1:indx1], scripts, index_new[index_new1:index_new2], index[(indx1+1):length(index)] ) try(fs::file_delete("docs/index_files/")) write_lines(x = index_final, file = "docs/index.html") fs::file_move("pkgdown/index_files/", "docs/") pkgdown::preview_site()
UKgas <- stats::ts(c(160.1, 129.7, 84.8, 120.1, 160.1, 124.9, 84.8, 116.9, 169.7, 140.9, 89.7, 123.3, 187.3, 144.1, 92.9, 120.1, 176.1, 147.3, 89.7, 123.3, 185.7, 155.3, 99.3, 131.3, 200.1, 161.7, 102.5, 136.1, 204.9, 176.1, 112.1, 140.9, 227.3, 195.3, 115.3, 142.5, 244.9, 214.5, 118.5, 153.7, 244.9, 216.1, 188.9, 142.5, 301.0, 196.9, 136.1, 267.3, 317.0, 230.5, 152.1, 336.2, 371.4, 240.1, 158.5, 355.4, 449.9, 286.6, 179.3, 403.4, 491.5, 321.8, 177.7, 409.8, 593.9, 329.8, 176.1, 483.5, 584.3, 395.4, 187.3, 485.1, 669.2, 421.0, 216.1, 509.1, 827.7, 467.5, 209.7, 542.7, 840.5, 414.6, 217.7, 670.8, 848.5, 437.0, 209.7, 701.2, 925.3, 443.4, 214.5, 683.6, 917.3, 515.5, 224.1, 694.8, 989.4, 477.1, 233.7, 730.0, 1087.0, 534.7, 281.8, 787.6, 1163.9, 613.1, 347.4, 782.8), start = 1960, frequency = 4)
declareConsts = function() { testData = list() testData$N = 10^4 testData$x = rnorm( testData$N ) testData$n = 100 testData$data = list( "x" = testData$x ) testData$params = list( "theta" = rnorm( 1, mean = 0, sd = 10 ) ) testData$optStepsize = 1e-5 testData$nIters = 1100 testData$nItersOpt = 1000 testData$burnIn = 100 testData$alpha = 0.01 testData$width = 1 return( testData ) } logLik = function( params, data ) { sigma = tf$constant( 1, dtype = tf$float64 ) baseDist = tf$distributions$Normal(params$theta, sigma) return(tf$reduce_sum(baseDist$log_prob(data$x))) } logPrior = function( params ) { baseDist = tf$distributions$Normal(0, 5) return( baseDist$log_prob( params$theta ) ) } sgldTest = function( testData ) { stepsize = list( "theta" = 1e-4 ) storage = sgld( logLik, testData$data, testData$params, stepsize, logPrior = logPrior, minibatchSize = testData$n, nIters = testData$nIters, verbose = FALSE ) thetaOut = storage$theta[-c(1:testData$burnIn)] return( thetaOut ) } sgldcvTest = function( testData ) { stepsize = list( "theta" = 1e-4 ) storage = sgldcv( logLik, testData$data, testData$params, stepsize, testData$optStepsize, logPrior = logPrior, minibatchSize = testData$n, nIters = testData$nIters, nItersOpt = testData$nItersOpt, verbose = FALSE ) return( storage ) } sghmcTest = function( testData ) { eta = list( "theta" = 1e-5 ) alpha = list( "theta" = 1e-1 ) L = 3 storage = sghmc( logLik, testData$data, testData$params, eta, logPrior = logPrior, minibatchSize = testData$n, alpha = alpha, L = L, nIters = testData$nIters, verbose = FALSE ) thetaOut = storage$theta[-c(1:testData$burnIn)] return( thetaOut ) } sghmccvTest = function( testData ) { eta = list( "theta" = 1e-4 ) alpha = list( "theta" = 1e-1 ) L = 3 storage = sghmccv( logLik, testData$data, testData$params, eta, testData$optStepsize, logPrior = logPrior, minibatchSize = testData$n, alpha = alpha, L = L, nIters = testData$nIters, nItersOpt = testData$nItersOpt, verbose = FALSE ) return( storage ) } sgnhtTest = function( testData ) { eta = list( "theta" = 1e-6 ) a = list( "theta" = 1e-2 ) storage = sgnht( logLik, testData$data, testData$params, eta, logPrior = logPrior, minibatchSize = testData$n, a = a, nIters = testData$nIters, verbose = FALSE ) thetaOut = storage$theta[-c(1:testData$burnIn)] return( thetaOut ) } sgnhtcvTest = function( testData ) { eta = list( "theta" = 1e-5 ) a = list( "theta" = 1e-2 ) storage = sgnhtcv( logLik, testData$data, testData$params, eta, testData$optStepsize, logPrior = logPrior, minibatchSize = testData$n, a = a, nIters = testData$nIters, nItersOpt = testData$nItersOpt, verbose = FALSE ) return( storage ) } test_that( "sgld: Check Error thrown for float64 input", { tryCatch({ tf$constant(c(1, 1)) }, error = function (e) skip("tensorflow not fully built, skipping...")) testData = declareConsts() expect_error( sgldTest( testData ) ) } ) test_that( "sgldcv: Check Error thrown for float64 input", { tryCatch({ tf$constant(c(1, 1)) }, error = function (e) skip("tensorflow not fully built, skipping...")) testData = declareConsts() expect_error( sgldcvTest( testData ) ) } ) test_that( "sghmc: Check Error thrown for float64 input", { tryCatch({ tf$constant(c(1, 1)) }, error = function (e) skip("tensorflow not fully built, skipping...")) testData = declareConsts() expect_error( sghmcTest( testData ) ) } ) test_that( "sghmccv: Check Error thrown for float64 input", { tryCatch({ tf$constant(c(1, 1)) }, error = function (e) skip("tensorflow not fully built, skipping...")) testData = declareConsts() expect_error( sghmccvTest( testData ) ) } ) test_that( "sgnht: Check Error thrown for float64 input", { tryCatch({ tf$constant(c(1, 1)) }, error = function (e) skip("tensorflow not fully built, skipping...")) testData = declareConsts() expect_error( sgnhtTest( testData ) ) } ) test_that( "sgnhtcv: Check Error thrown for float64 input", { tryCatch({ tf$constant(c(1, 1)) }, error = function (e) skip("tensorflow not fully built, skipping...")) testData = declareConsts() expect_error( sgnhtcvTest( testData ) ) } )
expect_equal(NOW(),format(Sys.time(),"%Y-%m-%d %H:%M"))
norm.2008RJB <- function(x, C1=6, C2=24, method=c("asymptotic","MC"), nreps=2000){ check_1d(x) myrule = tolower(method) if (myrule=="a"){ myrule = "asymptotic" } else if (myrule=="m"){ myrule = "mc" } finrule = match.arg(myrule, c("asymptotic","mc")) nreps = as.integer(nreps) if ((C1<=0)||(length(C1)>1)){ stop("* norm.2008RJB : 'C1' must be a nonnegative constant number.") } if ((C2<=0)||(length(C2)>1)){ stop("* norm.2008RJB : 'C2' must be a nonnegative constant number.") } if (finrule=="asymptotic"){ thestat = norm_2008RJB_single(x, C1, C2) pvalue = pchisq(thestat, df=2, lower.tail = FALSE) } else { tmpout = norm_2008RJB_mcarlo(x, nreps, C1, C2) thestat = tmpout$statistic pvalue = tmpout$counts/nreps } hname = "Robust Jarque-Bera Test of Univariate Normality by Gel and Gastwirth (2008)" DNAME = deparse(substitute(x)) Ha = paste("Sample ", DNAME, " does not follow normal distribution.",sep="") names(thestat) = "RJB" res = list(statistic=thestat, p.value=pvalue, alternative = Ha, method=hname, data.name = DNAME) class(res) = "htest" return(res) }
NULL mobile <- function(config = list()) { svc <- .mobile$operations svc <- set_config(svc, config) return(svc) } .mobile <- list() .mobile$operations <- list() .mobile$metadata <- list( service_name = "mobile", endpoints = list("*" = list(endpoint = "mobile.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "mobile.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "mobile.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "mobile.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "Mobile", api_version = "2017-07-01", signing_name = "AWSMobileHubService", json_version = "1.1", target_prefix = "" ) .mobile$service <- function(config = list()) { handlers <- new_handlers("restjson", "v4") new_service(.mobile$metadata, handlers, config) }
\donttest{ library(MASS) X = model.matrix(~ Sex + Bwt, cats) beta_mu = c(-0.1, 0.3, 4) beta_sigma = c(-0.5, -0.1, 0.3) mu = X %*% beta_mu log_sigma = X %*% beta_sigma y = rnorm( nrow(X), mean = mu, sd = exp(log_sigma)) fit = lmvar(y, X_mu = X[,-1], X_sigma = X[,-1]) cv.lmvar(fit) \dontshow{ cv.lmvar(fit, max_cores = 1) cv.lmvar(fit, ks_test = TRUE, max_cores = 2) cv.lmvar(fit, k = 5, seed = 5483, max_cores = 1) cv.lmvar(fit, exclude = c(5, 11, 20), max_cores = 1) fourth = function(object, y, X_mu, X_sigma){ mu = predict(object, X_mu[,-1], X_sigma[,-1], sigma = FALSE) residuals = y - mu return(mean(residuals^4)) } cv.lmvar(fit, fun = fourth) rm(fourth) cv.lmvar(fit, slvr_options = list( method = "NR", control = list(iterlim = 500))) fit = lmvar(log(y), X_mu = X[,-1], X_sigma = X[,-1]) cv = cv.lmvar(fit, log = TRUE) cv print(cv, digits = 2) }
if(getRversion() >= "4.0.0") { sum.unit = function(..., na.rm = FALSE) { lt = list(...) u = NULL for(i in seq_along(lt)) { if(length(lt[[i]]) > 1) { for(k in seq_along(lt[[i]])) { if(is.null(u)) { u = lt[[i]][k] } else { u = u + lt[[i]][k] } } } else { if(is.null(u)) { u = lt[[i]] } else { u = u + lt[[i]] } } } return(u) } }
demo.dag6 <- function() { dag<-dag.init(covs=c(2,1,1,1,1), arcs=c(1,0, 1,2, 3,2, 3,-1, 4,3, 5,3)); dag$x<-c(0.000, 0.211, 0.492, 0.492, 0.236, 0.098, 1.000); dag$y<-c(0.000, 0.300, 0.300, 0.663, 0.550, 0.816, 0.000); return(dag); }
poetry_config <- function(required_module) { project <- poetry_project() projfile <- file.path(project, "pyproject.toml") if (!file.exists(projfile)) return(NULL) toml <- tryCatch( RcppTOML::parseTOML(projfile), error = identity ) if (inherits(toml, "error")) { warning("This project contains a 'pyproject.toml' file, but it could not be parsed") warning(toml) return(NULL) } info <- tryCatch(toml[[c("tool", "poetry")]], error = identity) if (inherits(info, "error")) return(NULL) poetry <- poetry_exe() if (!file.exists(poetry)) { msg <- heredoc(" This project appears to use Poetry for Python dependency maangement. However, the 'poetry' command line tool is not available. reticulate will be unable to activate this project. Please ensure that 'poetry' is available on the PATH. ") warning(msg) return(NULL) } python <- poetry_python(project) python_config(python, required_module, forced = "Poetry") } poetry_exe <- function() { poetry <- getOption("reticulate.poetry.exe") if (!is.null(poetry)) return(poetry) Sys.which("poetry") } poetry_project <- function() { project <- getOption("reticulate.poetry.project") if (!is.null(project)) return(project) projfile <- tryCatch( dirname(here::here("pyproject.toml")), error = function(e) "" ) } poetry_python <- function(project) { owd <- setwd(project) on.exit(setwd(owd), add = TRUE) envpath <- system2("poetry", c("env", "info", "--path"), stdout = TRUE) virtualenv_python(envpath) }
library(arules) library(arulesViz) itemlist = list(c('I1','I2','I5'), c('I2','I4'), c('I2','I3'),c('I1','I2','I4'),c('I1','I3'),c('I2','I3'),c('I1','I3'),c('I1','I2','I3','I5'),c('I1','I2','I3')) itemlist length(itemlist) names(itemlist) <- paste("Tr",c(1:9), sep = "") itemlist tdata3 <- as(itemlist, "transactions") tdata3 summary(tdata3) tdata=tdata3 summary(tdata) itemlist image(tdata) freqitems = eclat(tdata) freqitems = eclat(tdata, parameter = list(minlen=1, supp=.1, maxlen=2 )) freqitems inspect(freqitems) support(items(freqitems[1:2]), transactions=tdata) inspect(freqitems[1]) inspect(items(freqitems[1])) itemFrequencyPlot(tdata,topN = 5,type="absolute") itemFrequencyPlot(tdata,topN = 5,type="relative", horiz=T) write.csv(as.data.frame(inspect(freqitems)),'freqitems1.csv') rules = apriori(tdata, parameter = list(supp = 0.2, conf = 0.5, minlen=2)) itemFrequencyPlot(items(rules)) inspect(rules[1:5]) inspect(rules) write.csv(as.data.frame(inspect(rules)),'rules1.csv') rules_s = sort(rules, by="support", decreasing=TRUE ) inspect(rules_s) inspect(rules_s[1:5]) rules_c = sort(rules, by="confidence", decreasing=TRUE ) inspect(rules_c) inspect(rules_c[1:5]) inspect(head(rules, n = 3, by ="lift")) rules_l = sort(rules, by="lift", decreasing=TRUE ) inspect(rules_l) inspect(rules_l[1:5]) quality(rules_c) inspect(rules) (redundant = which(is.redundant(rules))) inspect(rules[c(8,9,10,11,12,14,14)]) inspect(rules[redundant]) inspect(rules) write.csv(as(rules,"data.frame"), file='./data/rulesR.csv') rulesNR <- rules[-redundant] is.redundant(rulesNR) sum(is.redundant(rulesNR)) inspect(rulesNR) rules2= rulesNR inspect(rules2) rules2.lhs1 <- subset(rules2, lhs %in% c("I1", "I5")) inspect(rules2.lhs1) rules2.rhs1 <- subset(rules2, rhs %in% c("I3")) inspect(rules2.rhs1) rules2.lhsrhs1 = subset(rules2, lhs %in% c("I1") & rhs %in% c("I3")) inspect(rules2.lhsrhs1) rules2.lhsrhs2 = subset(rules2, lhs %in% c("I1") | rhs %in% c("I3")) inspect(rules2.lhsrhs2) rules_DF <- as(rules,"data.frame") rules_DF str(rules_DF) write.csv(rules_DF, './data/myrules1.csv') plot(rules)
typical_value <- function(x, fun = "mean", weights = NULL, ...) { fnames <- names(fun) if (!is.null(fnames)) { if (is.integer(x)) { fun <- fun[which(fnames %in% c("integer", "i"))] x <- as.numeric(x) } else if (is.numeric(x)) { fun <- fun[which(fnames %in% c("numeric", "n"))] } else if (is.factor(x)) { fun <- fun[which(fnames %in% c("factor", "f"))] if (fun != "mode") x <- to_value(x, keep.labels = FALSE) } } if (!(fun %in% c("mean", "median", "mode", "weighted.mean", "zero"))) stop("`fun` must be one of \"mean\", \"median\", \"mode\", \"weighted.mean\" or \"zero\".", call. = FALSE) if (fun == "weighted.mean" && !is.null(weights)) { if (length(weights) != length(x)) { warning("Vector of weights is of different length than `x`. Using `mean` as function for typical value.", call. = FALSE) fun <- "mean" } if (all(weights == 1)) { warning("All weight values are `1`. Using `mean` as function for typical value.", call. = FALSE) fun <- "mean" } } if (fun == "weighted.mean" && is.null(weights)) fun <- "mean" if (fun == "median") myfun <- get("median", asNamespace("stats")) else if (fun == "weighted.mean") myfun <- get("weighted.mean", asNamespace("stats")) else if (fun == "mode") myfun <- get("mode_value", asNamespace("sjmisc")) else if (fun == "zero") return(0) else myfun <- get("mean", asNamespace("base")) if (is.integer(x)) { stats::median(x, na.rm = TRUE) } else if (is.numeric(x)) { if (fun == "weighted.mean") do.call(myfun, args = list(x = x, na.rm = TRUE, w = weights, ...)) else do.call(myfun, args = list(x = x, na.rm = TRUE, ...)) } else if (is.factor(x)) { if (fun != "mode") levels(x)[1] else mode_value(x) } else { mode_value(x) } } mode_value <- function(x, ...) { counts <- table(x) modus <- names(counts)[max(counts) == counts] if (length(modus) > 1) modus <- modus[1] if (!is.na(suppressWarnings(as.numeric(modus)))) as.numeric(modus) else modus }
context("Test na_interp.R") test_that("na_interp() doesn't fall over", { sst_Med_prep <- sst_Med %>% dplyr::rename(ts_x = t, ts_y = temp) ts <- heatwaveR:::make_whole_fast(sst_Med_prep) res <- heatwaveR:::na_interp(doy = ts$doy, x = ts$ts_x, y = ts$ts_y, maxPadLength = 2) expect_is(res, "data.table") }) test_that("na_interp() handles unusual maxPadLength values correctly", { sst_Med_prep <- sst_Med %>% dplyr::rename(ts_x = t, ts_y = temp) ts <- heatwaveR:::make_whole_fast(sst_Med_prep) expect_is(heatwaveR:::na_interp(doy = ts$doy, x = ts$ts_x, y = ts$ts_y, maxPadLength = 0), "data.table") expect_is(heatwaveR:::na_interp(doy = ts$doy, x = ts$ts_x, y = ts$ts_y, maxPadLength = 15000), "data.table") })
gdfpd.read.dfp.zip.file <- function(my.zip.file, folder.to.unzip = tempdir(), id.type) { if (tools::file_ext(my.zip.file) != 'zip') { stop(paste('File', my.zip.file, ' is not a zip file.') ) } if (!file.exists(my.zip.file)) { stop(paste('File', my.zip.file, ' does not exists.') ) } if (file.size(my.zip.file) == 0){ file.remove(my.zip.file) stop(paste('File', my.zip.file, ' has size 0! File deleted. Try again..') ) } if (length(my.zip.file) != 1){ stop('This function only works for a single zip file... check your inputs') } if (!dir.exists(folder.to.unzip)) { cat(paste('Folder', folder.to.unzip, 'does not exist. Creating it.')) dir.create(folder.to.unzip) } my.basename <- tools::file_path_sans_ext(basename(my.zip.file)) rnd.folder.name <- file.path(folder.to.unzip, paste0('DIR-',my.basename)) if (!dir.exists(rnd.folder.name)) dir.create(rnd.folder.name) utils::unzip(my.zip.file, exdir = rnd.folder.name, junkpaths = TRUE) my.files <- list.files(rnd.folder.name) if (length(my.files) == 0) { file.remove(my.zip.file) stop(paste0('Zipped file contains 0 files. ', 'This is likelly a problem with the downloaded file. ', 'Try running the code again as the corrupted zip file was deleted and will be downloaded again.', '\n\nIf the problem persists, my suggestions is to remove the time period with problem.') ) } if (id.type == 'after 2011') { my.l <- gdfpd.read.dfp.zip.file.type.1(rnd.folder.name, folder.to.unzip) } if (id.type == 'before 2011') { my.l <- gdfpd.read.dfp.zip.file.type.2(rnd.folder.name, folder.to.unzip) } my.fct <- function(df.in) { if (nrow(df.in)==0) { df.out <- data.frame(acc.number = NA, acc.desc = NA, acc.value = NA) } else { df.out <- df.in } return(df.out) } my.l <- lapply(my.l, my.fct) return(my.l) } gdfpd.read.dfp.zip.file.type.1 <- function(rnd.folder.name, folder.to.unzip = tempdir()) { company.reg.file <- file.path(rnd.folder.name,'FormularioDemonstracaoFinanceiraDFP.xml') xml_data <- XML::xmlToList(XML::xmlParse(company.reg.file, encoding = 'UTF-8')) company.name = xml_data$CompanhiaAberta$NomeRazaoSocialCompanhiaAberta company.cvm_code <- xml_data$CompanhiaAberta$CodigoCvm company.SeqNumber <- xml_data$CompanhiaAberta$NumeroSequencialRegistroCvm company.date.delivery <- xml_data$DataEntrega date.docs <- as.Date(xml_data$DataReferenciaDocumento, format = '%Y-%m-%d') zipped.file <- file.path(rnd.folder.name, list.files(rnd.folder.name, pattern = '*.dfp')[1]) utils::unzip(zipped.file, exdir = rnd.folder.name) flag.thousands <- switch(xml_data$CodigoEscalaMoeda, '2' = FALSE, '1' = TRUE) fin.report.file <- file.path(rnd.folder.name, 'InfoFinaDFin.xml') if (!file.exists(fin.report.file)) { stop('Cant find file', fin.report.file) } xml_data <- XML::xmlToList(XML::xmlParse(fin.report.file, encoding = 'UTF-8')) file.remove(fin.report.file) my.fct <- function(x, type.df, info, flag.thousands){ if (type.df == 'individual') my.char = '1' if (type.df == 'consolidated') my.char = '2' if (x$PlanoConta$VersaoPlanoConta$CodigoTipoInformacaoFinanceira == my.char){ if (info == 'Descricao') return(x$DescricaoConta1) if (info == 'Valor') { my.value <- as.numeric(c(x$ValorConta1, x$ValorConta2, x$ValorConta3,x$ValorConta4)) if (length(my.value)==0) { my.value <- 0 } else { if (flag.thousands) { my.value <- my.value[1]*1/1000 } else { my.value <- my.value[1] } } return(my.value) } if (info == 'id') return(x$PlanoConta$NumeroConta) } else { return(NA) } } type.df <- 'individual' acc.desc <- as.character(sapply(xml_data, my.fct, type.df = type.df, info = 'Descricao', flag.thousands = flag.thousands)) acc.value <- as.numeric(sapply(xml_data, my.fct, type.df = type.df, info = 'Valor', flag.thousands = flag.thousands)) acc.number <- as.character(sapply(xml_data, my.fct, type.df = type.df, info = 'id', flag.thousands = flag.thousands)) ind.df <- data.frame(acc.number,acc.desc,acc.value) df.assets <- stats::na.omit(ind.df[stringr::str_sub(ind.df$acc.number,1,1) == '1', ]) df.liabilities <- stats::na.omit(ind.df[stringr::str_sub(ind.df$acc.number,1,1) == '2', ]) df.income <- stats::na.omit(ind.df[stringr::str_sub(ind.df$acc.number,1,1) == '3', ]) df.cashflow <- stats::na.omit(ind.df[stringr::str_sub(ind.df$acc.number,1,1) == '6', ]) df.value <- stats::na.omit(ind.df[stringr::str_sub(ind.df$acc.number,1,1) == '7', ]) l.individual.dfs <- list(df.assets = df.assets, df.liabilities = df.liabilities, df.income = df.income, df.cashflow = df.cashflow, df.value = df.value) type.df <- 'consolidated' acc.desc <- as.character(sapply(xml_data, my.fct, type.df = type.df, info = 'Descricao', flag.thousands = flag.thousands)) acc.value <- as.numeric(sapply(xml_data, my.fct, type.df = type.df, info = 'Valor', flag.thousands = flag.thousands)) acc.number <- as.character(sapply(xml_data, my.fct, type.df = type.df, info = 'id', flag.thousands = flag.thousands)) consolidated.df <- data.frame(acc.number,acc.desc,acc.value) df.assets.cons <- stats::na.omit(consolidated.df[stringr::str_sub(consolidated.df$acc.number,1,1) == '1', ]) df.liabilities.cons <- stats::na.omit(consolidated.df[stringr::str_sub(consolidated.df$acc.number,1,1) == '2', ]) df.income.cons <- stats::na.omit(consolidated.df[stringr::str_sub(consolidated.df$acc.number,1,1) == '3', ]) df.cashflow.cons <- stats::na.omit(consolidated.df[stringr::str_sub(consolidated.df$acc.number,1,1) == '6', ]) df.value.cons <- stats::na.omit(consolidated.df[stringr::str_sub(consolidated.df$acc.number,1,1) == '7', ]) l.consolidated.dfs <- list(df.assets = df.assets, df.liabilities = df.liabilities, df.income = df.income, df.cashflow = df.cashflow, df.value = df.value) fin.report.file <- file.path(rnd.folder.name, 'AnexoTexto.xml') if (!file.exists(fin.report.file)) { stop('Cant find file', fin.report.file) } xml_data <- NA try({ xml_data <- XML::xmlToList(XML::xmlParse(fin.report.file, encoding = 'UTF-8')) }) if (is.na(xml_data)) { warning('Cant read auditing notes..') df.auditing.report = data.frame(text.indep.auditor = NA, text.fiscal.counsil = NA, text.directors.about.fr = NA, text.directors.about.auditor = NA, stringsAsFactors = FALSE) } else { parsing.fct <- function(x, n.item) { if (x$NumeroQuadroRelacionado == as.character(n.item)) { return(x$Texto) } else { return('') } } text.indep.auditor <- paste0(sapply(xml_data, parsing.fct, n.item = 1655 ), collapse = '') text.fiscal.counsil <- paste0(sapply(xml_data, parsing.fct, n.item = 1657 ), collapse = '') text.directors.about.fr <- paste0(sapply(xml_data, parsing.fct, n.item = 1660 ), collapse = '') text.directors.about.auditor <- paste0(sapply(xml_data, parsing.fct, n.item = 1662 ), collapse = '') df.auditing.report = data.frame(text.indep.auditor = text.indep.auditor, text.fiscal.counsil = text.fiscal.counsil, text.directors.about.fr = text.directors.about.fr, text.directors.about.auditor = text.directors.about.auditor, stringsAsFactors = FALSE) } my.l <- list(df.assets = df.assets, df.liabilities = df.liabilities, df.income = df.income, df.cashflow = df.cashflow, df.value = df.value, df.assets.cons = df.assets.cons, df.liabilities.cons = df.liabilities.cons, df.income.cons = df.income.cons, df.cashflow.cons = df.cashflow.cons, df.value.cons = df.value.cons, df.auditing.report = df.auditing.report) return(my.l) } gdfpd.read.dfp.zip.file.type.2 <- function(rnd.folder.name, folder.to.unzip = tempdir()) { fin.report.file <- file.path(rnd.folder.name, 'CONFIG.XML') if (!file.exists(fin.report.file)) { flag.thousands = TRUE } else { xml_data <- XML::xmlToList(XML::xmlParse(fin.report.file, encoding = 'UTF-8')) flag.thousands <- switch(xml_data$ROWDATA$ROW['MOEDA'], '02' = FALSE, '01' = TRUE) } my.f <- list.files(rnd.folder.name,'DFPBPA', full.names = T)[1] df.assets <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name, 'DFPBPP', full.names = T)[1] df.liabilities <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name, 'DFPDERE', full.names = T)[1] df.income <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name, 'DFPDVAE', full.names = T)[1] df.value <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name, 'DFPDFCE', full.names = T) if ( (length(my.f) == 0) ) { df.cashflow <- data.frame(acc.desc = NA, acc.value = NA, acc.number = NA) }else { df.cashflow <- gdfpd.read.fwf.file(my.f[1], flag.thousands) } l.individual.dfs <- list(df.assets = df.assets, df.liabilities = df.liabilities, df.income = df.income, df.cashflow = df.cashflow, df.value = df.value) my.f <- list.files(rnd.folder.name,'DFPCBPA', full.names = T)[1] df.assets.cons <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name,'DFPCBPP', full.names = T)[1] df.liabilities.cons <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name,'DFPCDER', full.names = T)[1] df.income.cons <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name, 'DFPCDVAE', full.names = T)[1] df.value.cons <- gdfpd.read.fwf.file(my.f, flag.thousands) my.f <- list.files(rnd.folder.name,'DFPCDFCE', full.names = T) if (length(my.f) == 0) { df.cashflow.cons <- data.frame(acc.desc = NA, acc.value = NA, acc.number = NA) } else { df.cashflow.cons <- gdfpd.read.fwf.file(my.f[1], flag.thousands) } l.consolidated.dfs<- list(df.assets = df.assets, df.liabilities = df.liabilities, df.income = df.income, df.cashflow = df.cashflow, df.value = df.value) df.auditing.report = data.frame(text = NA) my.l <- list(df.assets = df.assets, df.liabilities = df.liabilities, df.income = df.income, df.cashflow = df.cashflow, df.value = df.value, df.assets.cons = df.assets.cons, df.liabilities.cons = df.liabilities.cons, df.income.cons = df.income.cons, df.cashflow.cons = df.cashflow.cons, df.value.cons = df.value.cons, df.auditing.report = df.auditing.report) return(my.l) }