code
stringlengths
1
13.8M
chebyshev.t.quadrature <- function( functn, rule, lower=-1, upper=1, weighted=TRUE, ... ) { if ( !is.function( functn ) ) stop( "functn argument is not an R function" ) if ( !is.data.frame( rule ) ) stop( "rule argument is not a data frame" ) if ( is.infinite( lower ) ) stop( "lower bound is infinite" ) if ( is.infinite( upper ) ) stop( "lower bound is infinite" ) if ( weighted ) { ff <- if ( length( list( ... ) ) && length( formals( functn ) ) > 1 ) function( x ) functn( x, ... ) else functn } else { ff <- if ( length( list( ... ) ) && length( formals( functn ) ) > 1 ) function( x ) { functn( x, ... ) / chebyshev.t.weight( x ) } else function( x ) { functn( x ) / chebyshev.t.weight( x ) } } lambda <- ( upper - lower ) / ( 2 ) mu <- ( lower + upper ) / ( 2 ) x <- rule$x w <- rule$w y <- lambda * x + mu z <- ff(y) return( lambda * sum( w * z ) ) }
CDaR<-function (R, weights = NULL, geometric = TRUE, invert = TRUE, p = 0.95, ...) { if (is.vector(R) || ncol(R) == 1) { R = na.omit(R) nr = nrow(R) if((p*nr) %% 1 == 0){ drawdowns = -Drawdowns(R) drawdowns = drawdowns[order(drawdowns),increasing = TRUE] result = -(1/((1-p)*nr))*sum(drawdowns[((p)*nr):nr]) } else{ f.obj = c(rep(0,nr),rep(((1/(1-p))*(1/nr)),nr),1) f.con = cbind(-diag(nr),diag(nr),1) f.dir = c(rep(">=",nr)) f.rhs = c(rep(0,nr)) ut = diag(nr) ut[-1,-nr] = ut[-1,-nr] - diag(nr - 1) f.con = rbind(f.con,cbind(ut,matrix(0,nr,nr),0)) f.dir = c(rep(">=",nr)) f.rhs = c(f.rhs,-R) f.con = rbind(f.con,cbind(matrix(0,nr,nr),diag(nr),0)) f.dir = c(rep(">=",nr)) f.rhs = c(f.rhs,rep(0,nr)) f.con = rbind(f.con,cbind(diag(nr),matrix(0,nr,nr),0)) f.dir = c(rep(">=",nr)) f.rhs = c(f.rhs,rep(0,nr)) val = lp("min",f.obj,f.con,f.dir,f.rhs) val_disp = lp("min",f.obj,f.con,f.dir,f.rhs,compute.sens = TRUE ) result = -val$objval } if (invert) result <- -result return(result) } else { R = checkData(R, method = "matrix") if (is.null(weights)) { result = matrix(nrow = 1, ncol = ncol(R)) for (i in 1:ncol(R)) { result[i] <- CDaR(R[, i, drop = FALSE], p = p, geometric = geometric, invert = invert, ... = ...) } dim(result) = c(1, NCOL(R)) colnames(result) = colnames(R) rownames(result) = paste("Conditional Drawdown ", round(p,3)*100, "%", sep = "") } else { portret <- Return.portfolio(R, weights = weights, geometric = geometric) result <- CDaR(portret, p = p, geometric = geometric, invert = invert, ... = ...) } return(result) } }
melt_dataframe <- function(data, id_ind, measure_ind, variable_name, value_name, attrTemplate, factorsAsStrings, valueAsFactor, variableAsFactor) { .Call(`_tidyr_melt_dataframe`, data, id_ind, measure_ind, variable_name, value_name, attrTemplate, factorsAsStrings, valueAsFactor, variableAsFactor) } simplifyPieces <- function(pieces, p, fillLeft) { .Call(`_tidyr_simplifyPieces`, pieces, p, fillLeft) }
setMethod("evalModel", signature(data = "dataSet"), function(data, folds = 5){ if (missing(folds)) folds <- 5 if (folds < 2) stop("k-fold cross validation requires at least two folds to continue!") x <- data@data nr <- nrow(x) fold_indices <- vector("list", folds) fold_indices_x_user <- vector("list", nr) rated_index_by_row <- lapply(1:nr, function(temp) which(!is.na(x[temp, ]))) for (i in 1:nr) { where <- sample(1:folds) userRatings <- sample(rated_index_by_row[[i]]) splitList <- suppressWarnings(split(userRatings, where)) fold_indices_x_user[[i]] <- splitList splitList <- lapply(splitList, function(v) (v-1)*nr + i) fold_indices <- lapply(1:folds, function(t) c(fold_indices[[t]], splitList[[t]])) } new("evalModel", data = data, folds = folds, fold_indices = fold_indices, fold_indices_x_user = fold_indices_x_user) }) setMethod("evalModel", signature(data = "sparseDataSet"), function(data, folds = 5){ if (missing(folds)) folds <- 5 if (folds < 2) stop("k-fold cross validation requires at least two folds to continue!") fold_indices <- vector("list", folds) fold_indices_x_user <- vector("list", nrow(data)) for(i in 1:nrow(data)){ userRatings <- data@userPointers[[i]] userRatings <- sample(userRatings) where <- sample(1:folds) splitList <- suppressWarnings(split(userRatings, where)) fold_indices <- lapply(1:folds, function(t) c(fold_indices[[t]], splitList[[t]])) fold_indices_x_user[[i]] <- splitList } new("evalModel", data = data, folds = folds, fold_indices = fold_indices, fold_indices_x_user = fold_indices_x_user) }) removeScores <- function(x, tsI){ UseMethod("removeScores", x) stop("Wrong input method!") } removeScores.dataSet <- function(x, tsI){ nusers <- nrow(x) x@data[tsI] <- NA x@data <- matrix(x@data, nusers) x } removeScores.sparseDataSet <- function(x, tsI){ x@data <- x@data[-tsI, ] x@userPointers <- getPointers(1:nrow(x), x@data$user) x@itemPointers <- getPointers(1:ncol(x), x@data$item) x }
nardl<-function(formula,data,ic=c("aic","bic"),maxlag=4,graph=FALSE,case= 3){ f<-formula a<-unlist(strsplit(as.character(f),"[|]")) if(length(a)==4){ lhs <- a[[2]] core <- a[[3]] suffix <- a[[4]] fm <-as.formula(paste(lhs,"~",core,"-1","|",suffix,"-1")) mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0) mf <- mf[c(1, m)] ffm <- Formula::Formula(fm) mf[[1]] <- as.name("model.frame") mf$formula <- ffm mf <- model.frame(formula=ffm, data=data) x <- model.matrix(ffm, data = mf, rhs = 1) if(ncol(x)>=2) stop("nardl package accept only one decomposed variable") h <- model.matrix(ffm, data = mf, rhs = 2) y<-model.response(mf) y<-as.matrix(y) k<-ncol(x)+ncol(h) colnames(y)<-lhs dy<-diff(y) colnames(dy)<-paste("D",lhs,sep=".") dx<-diff(x) colnames(dx)<-paste("D",colnames(x),sep=".") dh<-diff(h) colnames(dh)<-paste("D",colnames(h),sep=".") n<-nrow(dx) cl<-ncol(dx) pos<-dx[,1:cl]>=0 dxp<-as.matrix(as.numeric(pos)*dx[,1:cl]) colnames(dxp)<-paste(colnames(dx),"p",sep="_") dxn<-as.matrix((1-as.numeric(pos))*dx[,1:cl]) colnames(dxn)<-paste(colnames(dx),"n",sep="_") xp<-apply(dxp,2,cumsum) colnames(xp)<-paste(colnames(x),"p",sep="_") xn<-apply(dxn,2,cumsum) colnames(xn)<-paste(colnames(x),"n",sep="_") l <- rep(list(0:maxlag),(k+2)) grid0=expand.grid(l) b=which(grid0[1:nrow(grid0),]==0) grid=grid0[-b,] if(case==5){ trend<-seq_along(dy) if(ncol(h)==2){ ss=lapply(1:nrow(grid),function(x) lm(dy~nlagm1(y,grid[x,1])[-1,]+xn+nlagm1(xn,grid[x,3])+ xp+nlagm1(xp,grid[x,2]) +slag(h,grid[x,4:ncol(grid)])[-1,]+trend)) if(ic=="aic"){ ak=sapply(1:nrow(grid),function(x) AICC(ss[[x]])) } if(ic=="bic"){ ak=sapply(1:nrow(grid),function(x) BICC(ss[[x]])) } cii=as.matrix(ak) np=which.min(cii) pg=grid[np,] lay1=nlagm1(y,pg[,1]) lay=as.matrix(nlagm1(y,pg[,1])[-1,]) colnames(lay)=colnames(lay1) lxp=nlagm(xp,pg[,2]) lxn=nlagm(xn,pg[,3]) lagh1=slag(h,pg[,4:ncol(pg)])[-1,,drop=FALSE] rhnams<-c("Const",colnames(lay),colnames(lxp),colnames(lxn),colnames(lagh1),"trend") fits= lm(dy~lay+lxp+lxn+lagh1+trend,na.action =na.exclude ) }else{ ss=lapply(1:nrow(grid),function(x) lm(dy~nlagm1(y,grid[x,1])[-1,]+xn+nlagm1(xn,grid[x,3])+ xp+nlagm1(xp,grid[x,2])+nlagm(h,grid[x,4])[-1,]+trend)) if(ic=="aic"){ ak=sapply(1:nrow(grid),function(x) AIC(ss[[x]])) } if(ic=="bic"){ ak=sapply(1:nrow(grid),function(x) BIC(ss[[x]])) } cii=as.matrix(ak) np=which.min(cii) pg=grid[np,] lay1=nlagm1(y,pg[,1]) lay=as.matrix(nlagm1(y,pg[,1])[-1,]) colnames(lay)=colnames(lay1) lxp=nlagm(xp,pg[,2]) lxn=nlagm(xn,pg[,3]) lagh1=as.matrix(nlagm(h,pg[,4])[-1,,drop=FALSE]) rhnams<-c("Const",colnames(lay),colnames(lxp),colnames(lxn),colnames(lagh1),"trend") fits= lm(dy~lay+lxp+lxn+lagh1+trend,na.action =na.exclude ) } } if(case==3){ if(ncol(h)==2){ ss=lapply(1:nrow(grid),function(x) lm(dy~nlagm1(y,grid[x,1])[-1,]+xn+nlagm1(xn,grid[x,3])+ xp+nlagm1(xp,grid[x,2]) +slag(h,grid[x,4:ncol(grid)])[-1,])) if(ic=="aic"){ ak=sapply(1:nrow(grid),function(x) AICC(ss[[x]])) } if(ic=="bic"){ ak=sapply(1:nrow(grid),function(x) BICC(ss[[x]])) } cii=as.matrix(ak) np=which.min(cii) pg=grid[np,] lay1=nlagm1(y,pg[,1]) lay=as.matrix(nlagm1(y,pg[,1])[-1,]) colnames(lay)=colnames(lay1) lxp=nlagm(xp,pg[,2]) lxn=nlagm(xn,pg[,3]) lagh1=slag(h,pg[,4:ncol(pg)])[-1,,drop=FALSE] rhnams<-c("Const",colnames(lay),colnames(lxp),colnames(lxn),colnames(lagh1)) fits= lm(dy~lay+lxp+lxn+lagh1,na.action =na.exclude ) } else{ ss=lapply(1:nrow(grid),function(x) lm(dy~nlagm1(y,grid[x,1])[-1,]+xn+nlagm1(xn,grid[x,3])+ xp+nlagm1(xp,grid[x,2])+nlagm(h,grid[x,4])[-1,])) if(ic=="aic"){ ak=sapply(1:nrow(grid),function(x) AIC(ss[[x]])) } if(ic=="bic"){ ak=sapply(1:nrow(grid),function(x) BIC(ss[[x]])) } cii=as.matrix(ak) np=which.min(cii) pg=grid[np,] lay1=nlagm1(y,pg[,1]) lay=as.matrix(nlagm1(y,pg[,1])[-1,]) colnames(lay)=colnames(lay1) lxp=nlagm(xp,pg[,2]) lxn=nlagm(xn,pg[,3]) lagh1=as.matrix(nlagm(h,pg[,4])[-1,,drop=FALSE]) rhnams<-c("Const",colnames(lay),colnames(lxp),colnames(lxn),colnames(lagh1)) fits= lm(dy~lay+lxp+lxn+lagh1,na.action =na.exclude ) } } }else{ aa<-unlist(as.character(f)) lhs <- aa[[2]] core <- aa[[3]] fm <- paste(lhs,"~",core) ffm<-as.formula(fm) fffm<-update(ffm, ~ . -1) mf <- model.frame(formula=fffm, data=data) x <- model.matrix(attr(mf, "terms"), data=mf) k<-ncol(x) if(ncol(x)>=2) stop("nardl package accept only one decomposed variable") y <- model.response(mf) y<-as.matrix(y) colnames(y)<-lhs dy<-diff(y) colnames(dy)<-paste("D",lhs,sep=".") dx<-diff(x) core=strsplit(a[[3]],"[+]") core=unlist(core) colnames(dx)<-paste("D",core,sep=".") n<-nrow(dx) cl<-ncol(dx) pos<-dx[,1:cl]>=0 dxp<-as.matrix(as.numeric(pos)*dx[,1:cl]) colnames(dxp)<-paste(colnames(dx),"p",sep="_") dxn<-as.matrix((1-as.numeric(pos))*dx[,1:cl]) colnames(dxn)<-paste(colnames(dx),"n",sep="_") xp<-apply(dxp,2,cumsum) colnames(xp)<-paste(colnames(x),"p",sep="_") xn<-apply(dxn,2,cumsum) colnames(xn)<-paste(colnames(x),"n",sep="_") lagy<-lagm(as.matrix(y),1) lxp<-lagm(as.matrix(xp),1) lxn<-lagm(as.matrix(xn),1) l <- rep(list(0:maxlag),(k+2)) grid0=expand.grid(l) b=which(grid0[1:nrow(grid0),]==0) grid=grid0[-b,] if(case==5){ trend<-seq_along(dy) ss=lapply(1:nrow(grid),function(x) lm(dy~nlagm1(y,grid[x,1])[-1,]+xn+nlagm1(xn,grid[x,3])+ xp+nlagm1(xp,grid[x,2])+trend)) if(ic=="aic"){ ak=sapply(1:nrow(grid),function(x) AICC(ss[[x]])) } if(ic=="bic"){ ak=sapply(1:nrow(grid),function(x) BICC(ss[[x]])) } cii=as.matrix(ak) np=which.min(cii) pg=grid[np,] lay1=nlagm1(y,pg[,1]) lay=as.matrix(nlagm1(y,pg[,1])[-1,]) colnames(lay)=colnames(lay1) lxp=nlagm(xp,pg[,2]) lxn=nlagm(xn,pg[,3]) rhnams<-c("Const",colnames(lay),colnames(lxp),colnames(lxn),"trend") fits= lm(dy~lay+lxp+lxn+trend,na.action =na.exclude ) } if(case==3){ ss=lapply(1:nrow(grid),function(x) lm(dy~nlagm1(y,grid[x,1])[-1,]+xn+nlagm1(xn,grid[x,2])+ xp+nlagm1(xp,grid[x,3]))) if(ic=="aic"){ ak=sapply(1:nrow(grid),function(x) AICC(ss[[x]])) } if(ic=="bic"){ ak=sapply(1:nrow(grid),function(x) BIC(ss[[x]])) } cii=as.matrix(ak) np=which.min(cii) pg=grid[np,] lay1=nlagm1(y,pg[,1]) lay=as.matrix(nlagm1(y,pg[,1])[-1,]) colnames(lay)=colnames(lay1) lxp=nlagm(xp,pg[,2]) lxn=nlagm(xn,pg[,3]) rhnams<-c("Const",colnames(lay),colnames(lxp),colnames(lxn)) fits= lm(dy~lay+lxp+lxn,na.action =na.exclude ) } } names(fits$coefficients)<-rhnams sels=summary(fits) errors=sels$residuals nl=pg[[1]] jbtest<-shapiro.test(errors) lm2<-bp2(fits,nl,fill=0,type="F") arch<-ArchTest(errors,nl) coeff<-sels$coefficients nlvars<-length(coeff[,1]) lvars<-coeff[3:nlvars,1] seldata<-data.matrix(coeff) coof<- -lvars/coeff[[2]] cof<- matrix(coof, length(lvars),1) vc<-vcov(fits) vcc<-vc[2:nrow(vc),2:ncol(vc)] nsel<-length(sels$coefficients[,1]) fb1<-lvars/coeff[[2]]^2 fb2<-(-1/coeff[[2]])*diag(nrow(as.matrix(fb1))) fb<-cbind(as.matrix(fb1),fb2) lrse<-sqrt(diag(fb%*%vcc%*%t(fb))) lrse2=lrse lrt<-coof/lrse2 lrpv<-2 * pnorm(-abs(lrt)) lres<-cbind(cof,lrse2,lrt,lrpv) rownames(lres)<-names(lvars) colnames(lres)<-c("Estimate", "Std. Error", "t value", "Pr(>|t|)" ) l<-c(paste(names(coeff[-1,1]),"=0")) coin<-linearHypothesis(fits,l,test="F") fstat<-coin$F[2] tcoin=fits$coefficients[2] rcap=matrix(c(0),1,2) rcap[1,1]=1 rcap[1,2]=-1 rsml=matrix(c(0),1,1) bp=paste(colnames(x),"p",sep="_") bn=paste(colnames(x),"n",sep="_") vcc1=vcc[c(bp,bn),c(bp,bn)] lbetas=coof[c(bp,bn)] wldq=wtest(rcap,lbetas,vcc1,rsml) sbeta=coeff[c(bp,bn),1] wldsr=wtest(rcap,sbeta,vcc1,rsml) Nobs=length(fits$residuals) rece<-strucchange::recresid(fits) if(graph==TRUE){ if(length(rece)<=1) stop("length of recursive residuals is less then 1! ") bbst<-sels$coefficients[,1] k<-length(bbst[-1]) n<-length(errors) cusum(rece,k,n) cumsq(rece,k,n) } out<-list(fstat=fstat,tcoin=tcoin, fits=fits, sels=sels, cof=cof,coof=coof, k=k,n=n,case=case,lvars=lvars,selresidu=errors, jbtest=jbtest,arch=arch, nl=nl,rece=rece,Nobs=Nobs,vcc=vcc,fb=fb, fb1=fb1,fb2=fb2,lrse=lrse,lrt=lrt,lrpv=lrpv, lres=lres,lm2=lm2,wldsr=wldsr,wldq=wldq,pg=pg, ak=ak) class(out) <- "nardl" return(out) }
update.mu <- function(theta, y1, yP1, n){ (y1 - theta*yP1)/n }
context("test-1-4-0-swap") test_that("swap works", { a <- 1 b <- 2 a %<->% b expect_equal(a, 2) expect_equal(b, 1) }) test_that("swap errors", { "***temp***" <- NULL a <- list() b <- c() expect_error(a %<->% b) })
test_that("classif_bst", { requirePackagesOrSkip("bst", default.method = "load") parset.list1 = list( list(), list(cost = 0.6, family = "gaussian"), list(ctrl = bst::bst_control(mstop = 40L)), list(learner = "tree", control.tree = list(maxdepth = 2L)) ) parset.list2 = list( list(), list(cost = 0.6, family = "gaussian"), list(mstop = 40L), list(Learner = "tree", maxdepth = 2L) ) old.predicts.list = list() for (i in seq_along(parset.list1)) { parset = parset.list1[[i]] parset$y = ifelse(binaryclass.train[, binaryclass.class.col] == binaryclass.class.levs[2], 1, -1) parset$x = binaryclass.train[, -binaryclass.class.col] m = do.call(bst::bst, parset) p = predict(m, binaryclass.test) old.predicts.list[[i]] = ifelse(p > 0, binaryclass.class.levs[2], binaryclass.class.levs[1]) } testSimpleParsets("classif.bst", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.predicts.list, parset.list2) })
context("Basic Tests") test_that("steepest descent with constant step size", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = constant_step_size( value = 0.0001 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 19.18, 15.52, 12.81) g2ns <- c(232.87, 198.56, 170.43, 147.11) steps <- c(0, 0.0233, 0.0199, 0.017) par <- c(-1.144, 1.023) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) expect_equal(res$f, min(res$progress$f)) expect_equal(res$g2n, min(res$progress$g2n)) expect_equal(res$nf, nfs[length(nfs)]) expect_equal(res$ng, ngs[length(ngs)]) }) test_that("counting result fun grad calls increases counts", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = constant_step_size( value = 0.0001 ) ), verbose = FALSE ) ) res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(1, 2, 3, 4) ngs <- c(1, 2, 3, 4) fs <- c(24.2, 19.18, 15.52, 12.81) g2ns <- c(232.87, 198.56, 170.43, 147.11) steps <- c(0, 0.0233, 0.0199, 0.017) par <- c(-1.144, 1.023) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) expect_equal(res$f, min(res$progress$f)) expect_equal(res$g2n, min(res$progress$g2n)) expect_equal(res$nf, nfs[length(nfs)]) expect_equal(res$ng, ngs[length(ngs)]) }) test_that("can check convergence less often and get fewer fn/gr calls", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = constant_step_size( value = 0.0001 ) ), verbose = FALSE ) ) res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5, check_conv_every = 1000 ) progress_iters <- c("0", "3") nfs <- c(1, 2) ngs <- c(1, 4) fs <- c(24.2, 12.81) g2ns <- c(232.87, 147.11) steps <- c(0, 0.017) par <- c(-1.144, 1.023) expect_equal(rownames(res$progress), progress_iters) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) expect_equal(res$f, min(res$progress$f)) expect_equal(res$g2n, min(res$progress$g2n)) expect_equal(res$nf, nfs[length(nfs)]) expect_equal(res$ng, ngs[length(ngs)]) }) test_that("no grad norm returned or stored in progress when grad_tol is NULL", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = constant_step_size( value = 0.0001 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = NULL ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 19.18, 15.52, 12.81) steps <- c(0, 0.0233, 0.0199, 0.017) par <- c(-1.144, 1.023) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_true(is.null(res$progress$g2n)) expect_true(is.null(res$g2n)) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("steepest descent with constant step size and normalized direction", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.0001 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 24.18, 24.15, 24.13) g2ns <- c(232.87, 232.72, 232.57, 232.42) steps <- c(0, 1e-4, 1e-4, 1e-4) par <- c(-1.2, 1.0) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("steepest descent with bold driver", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver( init_step_size = 1 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 7, 12) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 4.12, 4.11) g2ns <- c(232.87, 64.72, 2.90, 2.39) steps <- c(0, 0.25, 0.069, 0.0047) par <- c(-1.024, 1.060) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with 0 step size should be like using no momentum", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.01 ) ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 21.95, 19.84, 17.88) g2ns <- c(232.87, 217.96, 203.31, 188.93) steps <- c(0, 1e-2, 1e-2, 1e-2) mus <- c(0, 0, 0, 0) par <- c(-1.172, 1.011) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with constant step size", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.01 ) ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 21.95, 19.44, 17.06) g2ns <- c(232.87, 217.96, 200.42, 182.69) steps <- c(0, 0.01, 0.012, 0.0124) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.168, 1.013) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("eager classical momentum with constant step size should give same results as non-eager", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.01 ) ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt$eager_update <- TRUE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 21.95, 19.44, 17.06) g2ns <- c(232.87, 217.96, 200.42, 182.69) steps <- c(0, 0.01, 0.012, 0.0124) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.168, 1.013) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with bold driver", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 8, 10) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 5.25, 4.62) g2ns <- c(232.87, 64.72, 47.19, 33.88) steps <- c(0, 0.25, 0.020, 0.0795) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.051, 1.040) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("eager classical momentum with bold driver same as 'lazy' result", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$eager_update <- TRUE opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 8, 10) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 5.25, 4.62) g2ns <- c(232.87, 64.72, 47.19, 33.88) steps <- c(0, 0.25, 0.020, 0.0795) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.051, 1.040) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("linear weighted classical momentum with bold driver", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt <- append_stage(opt, momentum_correction_stage()) res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 10, 12) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 4.27, 5.04, 4.67) g2ns <- c(232.87, 17.16, 42.78, 33.27) steps <- c(0, 0.2, 0.027, 0.01) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-0.998, 1.078) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("linear weighted eager classical momentum with bold driver", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt <- append_stage(opt, momentum_correction_stage()) opt$count_res_fg <- FALSE opt$eager_update <- TRUE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 10, 12) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 4.27, 5.04, 4.67) g2ns <- c(232.87, 17.16, 42.78, 33.27) steps <- c(0, 0.2, 0.027, 0.01) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-0.998, 1.078) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("bold classical momentum with bold driver", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(normalize = TRUE), step_size = bold_driver() ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 6, 19, 45) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 4.12, 4.10) g2ns <- c(232.87, 64.72, 2.81, 2.41) steps <- c(0, 0.25, 0.064, 0.0047) mus <- c(1, 1.1, 4.73e-3, 1.64e-8) par <- c(-1.027, 1.059) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("bold classical momentum with bold driver without cache gives same results, but requires extra work", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(normalize = TRUE), step_size = bold_driver() ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, invalidate_cache = TRUE, grad_tol = 1e-5 ) nfs <- c(0, 6, 20, 47) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 4.12, 4.10) g2ns <- c(232.87, 64.72, 2.81, 2.41) steps <- c(0, 0.25, 0.064, 0.0047) mus <- c(1, 1.1, 4.73e-3, 1.64e-8) par <- c(-1.027, 1.059) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with bold driver and fn adaptive restart, same results as without when everything is ok", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt <- adaptive_restart(opt, "fn") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 5, 9, 11) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 5.25, 4.62) g2ns <- c(232.87, 64.72, 47.19, 33.88) steps <- c(0, 0.25, 0.020, 0.0795) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.051, 1.040) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with bold driver and gr adaptive restart, same results as without when everything is ok", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt <- adaptive_restart(opt, "gr") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 8, 10) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 5.25, 4.62) g2ns <- c(232.87, 64.72, 47.19, 33.88) steps <- c(0, 0.25, 0.020, 0.0795) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.051, 1.040) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with bold driver aggressive momentum can cause cost increase", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.4 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 8, 10) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 8.71, 4.69) g2ns <- c(232.87, 64.72, 91.13, 34.39) steps <- c(0, 0.25, 0.033, 0.064) mus <- c(0.4, 0.4, 0.4, 0.4) par <- c(-0.989, 1.064) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with bold driver adaptive gr momentum prevents cost increase", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.4 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt <- adaptive_restart(opt, "gr") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 8, 10) ngs <- c(0, 1, 2, 2) fs <- c(24.2, 6.32, 6.32, 4.12) g2ns <- c(232.87, 64.72, 64.72, 2.90) steps <- c(0, 0.25, 0, 0.069) mus <- c(0.4, 0.4, 0.4, 0.4) par <- c(-1.029, 1.061) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with bold driver adaptive fn momentum prevents cost increase", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.4 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt <- adaptive_restart(opt, "fn") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 5, 9, 11) ngs <- c(0, 1, 2, 2) fs <- c(24.2, 6.32, 6.32, 4.12) g2ns <- c(232.87, 64.72, 64.72, 2.90) steps <- c(0, 0.25, 0, 0.069) mus <- c(0.4, 0.4, 0.4, 0.4) par <- c(-1.029, 1.061) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with constant function factory", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.01 ) ), momentum_stage( direction = momentum_direction(), step_size = make_momentum_step( make_constant( value = 0.2 ), use_init_mom = TRUE ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 21.95, 19.44, 17.06) g2ns <- c(232.87, 217.96, 200.42, 182.69) steps <- c(0, 0.01, 0.012, 0.0124) mus <- c(0, 0.2, 0.2, 0.2) par <- c(-1.168, 1.013) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with ramp function", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.01 ) ), momentum_stage( direction = momentum_direction(), step_size = make_momentum_step( make_ramp( init_value = 0.1, final_value = 0.3, wait = 0 ), use_init_mom = TRUE ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 21.95, 19.44, 16.84) g2ns <- c(232.87, 217.96, 200.42, 181.00) steps <- c(0, 0.01, 0.012, 0.0136) mus <- c(0, 0.1, 0.2, 0.3) par <- c(-1.167, 1.014) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("classical momentum with switch function", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = constant_step_size( value = 0.01 ) ), momentum_stage( direction = momentum_direction(), step_size = make_momentum_step( make_switch( init_value = 0.5, final_value = 0.8, switch_iter = 2 ), use_init_mom = TRUE ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 21.95, 18.26, 14.00) g2ns <- c(232.87, 217.96, 191.79, 157.67) steps <- c(0, 0.01, 0.018, 0.0244) mus <- c(0, 0.5, 0.8, 0.8) par <- c(-1.152, 1.020) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("sutskever nesterov momentum with bold driver", { opt <- make_opt( make_stages( momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt$eager_update <- TRUE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 4, 7, 10) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 4.33, 4.78) g2ns <- c(232.87, 64.72, 22.22, 36.89) steps <- c(0, 0.25, 0.088, 0.0584) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.042, 1.046) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) expect_equal(res$f, min(fs), tol = 1e-3) }) test_that("nesterov momentum with bold driver and adaptive fn", { opt <- make_opt( make_stages( momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), gradient_stage( direction = sd_direction(normalize = TRUE), step_size = bold_driver() ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt$eager_update <- TRUE opt <- adaptive_restart(opt, "fn") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 5, 8, 11) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 6.32, 4.33, 4.33) g2ns <- c(232.87, 64.72, 22.22, 22.22) steps <- c(0, 0.25, 0.088, 0) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-1.042, 1.046) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("nesterov accelerated gradient with wolfe line search", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9) ), momentum_stage( direction = nesterov_momentum_direction(), step_size = nesterov_convex_step() ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt$eager_update <- TRUE opt$depends <- c(opt$depends, "keep_stage_fs") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, ret_opt = TRUE, grad_tol = 1e-5 ) nfs <- c(0, 9, 17, 22) ngs <- c(0, 9, 17, 22) fs <- c(24.2, 4.128, 3.913, 3.558) g2ns <- c(232.87, 1.777, 23.908, 7.200) steps <- c(0, 0.184, 0.301, 0.048) mus <- c(0, 0, 0.282, 0.434) par <- c(-0.869, 0.781) all_fs <- c(4.128, 4.128, 3.886, 3.913, 3.583, 3.558) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) expect_equal(res$opt$all_fs, all_fs, tol = 1e-3) }) test_that("nesterov momentum with wolfe line search is like NAG", { opt <- make_opt( make_stages( momentum_stage( direction = momentum_direction(), step_size = nesterov_convex_step(burn_in = 2) ), gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE opt$eager_update <- TRUE opt$depends <- c(opt$depends, "keep_stage_fs") res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, ret_opt = TRUE, grad_tol = 1e-5 ) nfs <- c(0, 9, 17, 22) ngs <- c(0, 9, 17, 22) fs <- c(24.2, 4.128, 3.886, 3.582) g2ns <- c(232.87, 1.777, 18.114, 1.858) steps <- c(0, 0.184, 0.235, 0.0709) mus <- c(0, 0, 0, 0.282) par <- c(-0.891, 0.802) all_fs <- c(24.2, 4.128, 4.128, 3.886, 3.913, 3.583) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) expect_equal(res$opt$all_fs, all_fs, tol = 1e-3) }) test_that("NAG with q = 1 is steepest descent", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9) ), momentum_stage( direction = nesterov_momentum_direction(), step_size = nesterov_convex_step(q = 1) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 9, 17, 22) ngs <- c(0, 9, 17, 22) fs <- c(24.2, 4.128, 3.886, 3.704) g2ns <- c(232.87, 1.777, 18.114, 1.843) steps <- c(0, 0.184, 0.235, 0.020) mus <- c(0, 0, 0, 0) par <- c(-0.923, 0.860) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("NAG with q close to 0 is the same as == 0", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9) ), momentum_stage( direction = nesterov_momentum_direction(), step_size = nesterov_convex_step(q = 1e-8) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 9, 17, 22) ngs <- c(0, 9, 17, 22) fs <- c(24.2, 4.128, 3.913, 3.558) g2ns <- c(232.87, 1.777, 23.908, 7.200) steps <- c(0, 0.184, 0.301, 0.048) mus <- c(0, 0, 0.282, 0.434) par <- c(-0.869, 0.781) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("NAG with q = 0.5 between full NAG and SD", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9) ), momentum_stage( direction = nesterov_momentum_direction(), step_size = nesterov_convex_step(q = 0.5) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 9, 17, 21) ngs <- c(0, 9, 17, 21) fs <- c(24.2, 4.128, 3.891, 3.664) g2ns <- c(232.87, 1.777, 20.711, 3.442) steps <- c(0, 0.184, 0.265, 0.028) mus <- c(0, 0, 0.128, 0.159) par <- c(-0.903, 0.831) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("NAG with approximate convex momentum", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9) ), momentum_stage( direction = nesterov_momentum_direction(), step_size = nesterov_convex_approx_step(use_init_mu = FALSE) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 9, 17, 22) ngs <- c(0, 9, 17, 22) fs <- c(24.2, 4.128, 4.004, 3.337) g2ns <- c(232.87, 1.777, 30.137, 7.777) steps <- c(0, 0.184, 0.369, 0.0999) mus <- c(0, 0, 0.571, 0.625) par <- c(-0.805, 0.676) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("NAG with approximate convex momentum and mu = 0.5 at t = 1", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(), step_size = more_thuente_ls(c2 = 1.e-9, max_alpha_mult = 10) ), momentum_stage( direction = nesterov_momentum_direction(), step_size = nesterov_convex_approx_step(use_init_mu = TRUE) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 9, 15, 26) ngs <- c(0, 9, 15, 26) fs <- c(24.2, 8.223, 4.097, 15.55) g2ns <- c(232.87, 86.69, 1.791, 77.44) steps <- c(0, 0.275, 0.0926, 1.703) mus <- c(0, 0.5, 0.571, 0.625) par <- c(-0.09, -0.371) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("Polak Ribiere CG with Rasmussen LS", { opt <- make_opt( make_stages( gradient_stage( direction = cg_direction(cg_update = pr_update), step_size = rasmussen_ls( initial_step_length = "r", max_alpha_mult = 10 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 6, 10, 12) ngs <- c(0, 6, 10, 12) fs <- c(24.2, 4.13, 3.84, 3.52) g2ns <- c(232.87, 1.87, 19.06, 25.24) steps <- c(0, 0.184, 0.273, 0.311) par <- c(-0.777, 0.543) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("BFGS with More-Thuente LS", { opt <- make_opt( make_stages( gradient_stage( direction = bfgs_direction(), step_size = more_thuente_ls( c2 = 1e-9, initial_step_length = "sci", initializer = "q", try_newton_step = TRUE ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosen_no_hess, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 6, 11, 17) ngs <- c(0, 6, 11, 17) fs <- c(24.2, 4.13, 3.85, 3.53) g2ns <- c(232.87, 1.78, 18.62, 24.98) steps <- c(0, 0.184, 0.261, 0.307) par <- c(-0.785, 0.558) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("L-BFGS with More-Thuente LS gives same results as BFGS with sufficiently high memory", { opt <- make_opt( make_stages( gradient_stage( direction = lbfgs_direction(), step_size = more_thuente_ls( c2 = 1e-9, initial_step_length = "sci", initializer = "q", try_newton_step = TRUE ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosen_no_hess, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 6, 11, 17) ngs <- c(0, 6, 11, 17) fs <- c(24.2, 4.13, 3.85, 3.53) g2ns <- c(232.87, 1.78, 18.62, 24.98) steps <- c(0, 0.184, 0.261, 0.307) par <- c(-0.785, 0.558) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("delta bar delta adaptive learning rate", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = delta_bar_delta( epsilon = 0.1, kappa_fun = `*`, kappa = 1.1, phi = 0.5, theta = 0.2 ) ) ), verbose = FALSE ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 7.10, 5.28, 4.21) g2ns <- c(232.87, 83.18, 47.48, 13.66) steps <- c(0, 0.11, 0.121, 0.0605) par <- c(-1.040, 1.060) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("delta bar delta adaptive learning rate using momentum", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = TRUE), step_size = delta_bar_delta( epsilon = 0.1, use_momentum = TRUE, kappa_fun = `*`, kappa = 1.1, phi = 0.5 ) ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.2 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 7.10, 6.53, 4.84) g2ns <- c(232.87, 83.18, 67.62, 37.87) steps <- c(0, 0.11, 0.143, 0.032) mus <- c(0.2, 0.2, 0.2, 0.2) par <- c(-0.993, 1.080) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) }) test_that("delta bar delta adaptive learning rate using momentum and additive increase", { opt <- make_opt( make_stages( gradient_stage( direction = sd_direction(normalize = FALSE), step_size = delta_bar_delta( epsilon = 0.001, use_momentum = TRUE, kappa_fun = `+`, kappa = 0.02, phi = 0.8 ) ), momentum_stage( direction = momentum_direction(), step_size = constant_step_size( value = 0.4 ) ), verbose = FALSE ) ) opt$count_res_fg <- FALSE res <- opt_loop(opt, rb0, rosenbrock_fg, 3, store_progress = TRUE, verbose = FALSE, grad_tol = 1e-5 ) nfs <- c(0, 0, 0, 0) ngs <- c(0, 1, 2, 3) fs <- c(24.2, 5.59, 9.45, 6.01) g2ns <- c(232.87, 53.36, 97.69, 60.21) steps <- c(0, 0.238, 0.052, 0.044) mus <- c(0.4, 0.4, 0.4, 0.4) par <- c(-0.966, 1.079) expect_equal(res$progress$nf, nfs) expect_equal(res$progress$ng, ngs) expect_equal(res$progress$f, fs, tol = 1e-3) expect_equal(res$progress$g2n, g2ns, tol = 1e-3) expect_equal(res$progress$step, steps, tol = 1e-3) expect_equal(res$progress$mu, mus, tol = 1e-3) expect_equal(res$par, par, tol = 1e-3) })
wdekde <- function(x, w, bandwidth,s.x) { if (!missing(bandwidth) && bandwidth <= 0) stop("'bandwidth' must be strictly positive") if(missing(w)){ w <- rep(1,length(x)) }else{ stopifnot(length(w)==length(x)) stopifnot(all(w>0)) } sele <- is.na(x)|is.na(w) if(any(sele)){ x <- x[!sele] w <- w[!sele] } if(missing(bandwidth)){ h0 <- bw.nrd(x); }else{ stopifnot(is.numeric(bandwidth)) stopifnot(length(bandwidth)==1) stopifnot(bandwidth > 0) h0 <- bandwidth } tau <- 4; gridsize = 512L M <- 2^(ceiling(log2(gridsize))) range.x <- c(min(x)-tau*h0, max(x)+tau*h0) a <- range.x[1L]; b <- range.x[2L] gpoints <- seq(a, b, length = M) out <- .Fortran(.F_wdekde, as.double(x), as.double(w/sum(w)), as.integer(length(x)), y=as.double(gpoints), as.integer(M), as.double(h0), as.double(s.x)) list(y=out$y,x=gpoints) } wkde <- function(x, w, bandwidth, freq=FALSE, gridsize = 401L, range.x, truncate = TRUE, na.rm=TRUE) { name <- deparse(substitute(x)) if (!missing(bandwidth) && bandwidth <= 0) stop("'bandwidth' must be strictly positive") if(missing(w)){ if(any(is.na(x))){ if(na.rm) x <- x[!is.na(x)] else stop("'x' contains missing value(s)") } xt <- table(x); x <- as.numeric(names(xt)) w <- as.numeric(xt) n <- length(x) freq <- TRUE totMass <- 1.0 }else{ tmp = .wtdata(x,w,na.rm=na.rm) x <- tmp$x; w <- tmp$w; n <- tmp$n; totMass <- tmp$totMass } tau <- 4; h0 <- bw.wnrd0(x,w, freq=freq); gridsize = max(512L, gridsize) M <- 2^(ceiling(log2(gridsize))) if (missing(range.x)) range.x <- c(min(x)-tau*h0, max(x)+tau*h0) a <- range.x[1L]; b <- range.x[2L] gpoints <- seq(a, b, length = M) pars = c(h0,0) out <- if(missing(bandwidth)) .nwkde(x,w,h0,n,a,b,M,tau=tau,truncate=truncate) else if(is.numeric(bandwidth)) .nwkde(x,w,bandwidth,n,a,b,M,tau=tau,truncate=truncate) else if(is.character(bandwidth)) switch(tolower(bandwidth), "wnrd" = .nwkde(x,w,bw.wnrd(x,w,freq=freq),n,a,b,M, tau=tau,truncate=truncate), "wnrd0" = .nwkde(x,w,h0,n,a,b,M, tau=tau,truncate=truncate), "blscv" = .nwkde(x,w, bw.blscv(x,w,h0,gridsize=M), n,a,b,M,tau=tau,truncate=truncate), "wmise" = .Fortran(.F_wkde,as.double(x),as.double(w/sum(w)), as.integer(n),x=as.double(gpoints),y=as.double(gpoints), Fy=as.double(gpoints),as.integer(M), bw=as.double(pars)), "awmise" = .Fortran(.F_awkde,as.double(x),as.double(w/sum(w)), as.integer(n),x=as.double(gpoints),y=as.double(gpoints), Fy=as.double(gpoints),as.integer(M), bw=as.double(pars)), stop("Bandwidth selector not supported.")) else stop("Bandwidth selector not supported.") if(length(out$bw)==1){ bw = out$bw; sp=NULL; }else{ bw = out$bw[1]; sp = out$bw[2] } list(y=out$y,x=out$x, bw= bw, sp = sp) } .bw.wmise <- function(x, w, na.rm=TRUE) { tmp = .wtdata(x,w,na.rm=na.rm) x <- tmp$x; w <- tmp$w; n <- tmp$n; h0 <- bw.wnrd(x,w) m = 50; h = seq(h0/10, by = h0/10, length=m) out = .Fortran(.F_wmise, as.double(x), as.double(w), as.integer(n), h = as.double(h), mise = as.double(h), as.integer(m)) sele = which(out$mise == min(out$mise)) bw = out$h[sele[1]] list(bw = bw, x = out$h, y = out$mise) } bw.blscv <- function(x,w,h,gridsize=256) { n <- length(x); if(missing(w)) w = rep(1/n,n) h0 <- ifelse(missing(h), bw.wnrd0(x,w), h) hl <- h0 * 0.5; hh <- 2.5*h0 iter <- 50; y <- rep(0,iter) hs <- seq(hl,hh,length=iter) a <- min(x); b <- max(x); M <- 2^(ceiling(log(gridsize)/log(2))) gpoints <- seq(a, b, length = M) gcounts <- .wlinbin(x, w*n, gpoints, truncate=TRUE) gcounts <- gcounts * M/n/(b-a) Myl <- .Fortran(.F_yldist, as.double(gcounts), as.integer(M), y = double(M/2))$y ell <- 1:(M/2) sl <- 2*pi*ell/(b-a) lscv.temp <- function(h){ tmp2 <- n*h*sqrt(2*pi) hs2 <- h^2*sl^2 tmp <- exp(-hs2)-2.*exp(-0.5*hs2) sum(tmp*Myl)*(b-a)+1./tmp2 } opt <- optimise(f = lscv.temp, interval = c(0.25 * h0, 5 * h0, tol = .Machine$double.eps)) return(opt$minimum) } bw.wnrd <- function(x, w, freq=FALSE, na.rm=TRUE) { size <- ifelse(freq, sum(w), length(x)) tmp = .wtdata(x,w,na.rm=na.rm) x <- tmp$x; w <- tmp$w; n <- tmp$n; s = .wsd(x,w); iqr = .wiqr(x,w); 1.06*min(s,iqr/1.34)*size^-.2 } bw.wnrd0 <- function(x, w, freq=FALSE, na.rm=TRUE) { size <- ifelse(freq, sum(w), length(x)) tmp = .wtdata(x,w,na.rm=na.rm) x <- tmp$x; w <- tmp$w; n <- tmp$n; s = .wsd(x,w); iqr = .wiqr(x,w); 0.9*min(s,iqr/1.34)*size^-.2 } .wtdata <- function(x,w,na.rm=TRUE){ n <- length(x) if(missing(w)) w <- rep(1/n,n) stopifnot(all(w>0)) if(any(is.na(x))){ if(na.rm){ sele <- !is.na(x) x <- x[sele]; w <- w[sele] n <- length(x) }else stop("Missing value(s) in 'x'") stopifnot(any(!is.na(w))) } x.finite <- is.finite(x) totMass <- mean(x.finite) x <- x[x.finite]; w <- w[x.finite]; n <- length(x); w <- w/sum(w) list(x=x,w=w,n=n,totMass=totMass) } .wmean <- function(x,w) ifelse(missing(w), mean(x), sum(x*w)/sum(w)) .wvar <- function(x,w) sum((x-.wmean(x,w))^2 * w/sum(w)) .wsd <- function(x,w) sqrt(.wvar(x,w)) .wquantile <- function(x,w,level){ if(missing(w)) w = rep(1,length(x))/length(x) else stopifnot(length(x)==length(w)) w <- w/sum(w) ox <- order(x); w <- w[ox]; x <- x[ox] Fw <- cumsum(w)/sum(w) stopifnot(all(!is.na(level))) stopifnot(all(level <= 1 & level >= 0)) sele = level > min(Fw) & level < max(Fw) out = rep(0, length(level)) if(sum(sele)>0){ out[sele] = approx(Fw,x,level[sele])$y } if(sum(!sele)>0) out[!sele] = as.numeric(quantile(x,level[!sele], na.rm=TRUE)) out } .wiqr <- function(x,w){ diff(.wquantile(x,w,level=c(.25,.75))) } .nclass.scott <- function (x,w) { size <- length(x) h <- 3.5 * .wsd(x,w) * size^(-1/3) if (h > 0) ceiling(diff(range(x))/h) else 1L } .nclass.FD <- function (x,w) { size <- length(x) w <- w/sum(w) h <- .wiqr(x,w) if (h == 0){ cf <- abs(cumsum(w)-0.5) h <- x[which(cf==min(cf))[1]] } if (h > 0) ceiling(diff(range(x))/(2 * h * size^(-1/3))) else 1L } .nclass.Sturges <- function (n) ceiling(log2(n) + 1) .wlinbin <- function(X, W, gpoints, truncate = TRUE) { n <- length(X) M <- length(gpoints) trun <- ifelse(truncate, 1L, 0L) a <- gpoints[1L] b <- gpoints[M] .Fortran(.F_wlinbin, as.double(X), as.double(W), as.integer(n), as.double(a), as.double(b), as.integer(M), as.integer(trun), wts = double(M))$wts } .wedf <- function(y){ stopifnot(class(y)=="wdata") out = structure( list(x = y$x, y = cumsum(y$w), data=y ), class = "edf") } .plot.edf <- function (x, main = NULL, xlab = NULL, ylab = "Probability", zero.line = TRUE, ...) { if (is.null(xlab)) xlab <- paste("N =", x$data$n.total, " NA =", x$data$n.rm) if (is.null(main)) main <- ifelse(is.null(x$data$data.name), "Empirical Distribution Function", deparse(x$data$data.name)) plot.default(x, main = main, xlab = xlab, ylab = ylab, ylim=c(0,1),pch=20,cex=.5,...) n = length(x$x) for(i in 1: (n-1)) segments(x$x[i], x$y[i], x$x[i+1], x$y[i],...) if (zero.line) abline(h = 0, lwd = 0.1, col = "gray") invisible(NULL) } .lines.edf <- function (x, ...) { points(x,pch=20,cex=.5,...) n = length(x$x) for(i in 1: (n-1)) segments(x$x[i], x$y[i], x$x[i+1], x$y[i],...) segments(x$x[n], x$y[n], x$x[n]*10, x$y[n],...) invisible(NULL) } .nwkde <- function(x,w, h, n, a,b, M,tau=4,truncate=FALSE) { gpoints <- seq(a, b, length = M) if(any(w>1)) w <- w/sum(w) gcounts <- .wlinbin(x, w*n, gpoints, truncate) delta <- (b - a)/(h * (M-1L)) L <- min(floor(tau/delta), M) if (L == 0) warning("Binning grid too coarse for current (small) bandwidth: consider increasing 'gridsize'") lvec <- 0L:L kappa <- dnorm(lvec*delta)/(n*h) P <- 2^(ceiling(log(M+L+1L)/log(2))) kappa <- c(kappa, rep(0, P-2L*L-1L), rev(kappa[-1L])) tot <- sum(kappa) * (b-a)/(M-1L) * n gcounts <- c(gcounts, rep(0L, P-M)) kappa <- fft(kappa/tot) gcounts <- fft(gcounts) list(x = gpoints, y = (Re(fft(kappa*gcounts, TRUE))/P)[1L:M], bw = h) }
get_ARPA_Lombardia_W_registry <- function() { Metadata <- W_metadata_reshape() structure(list(Metadata = Metadata)) attr(Metadata, "class") <- c("ARPALdf","ARPALdf_W","tbl_df","tbl","data.frame") return(Metadata) }
met.ci.single <- function(M) { eigen <- met.eigen(M) eigen.max <- eigen[which.max(eigen)] num <- sum(eigen.max - eigen) m <- matrix(rep(0, ncol(M) * nrow(M)), ncol = ncol(M), nrow = nrow(M)) e <- sample(c(1:nrow(m)), 1) m[e, ] <- rep(1, ncol(m)) m[, e] <- rep(1, nrow(m)) diag(m) <- 0 eigen2 <- met.eigen(m) eigen2.max <- eigen2[which.max(eigen2)] den <- max(eigen2.max - eigen2) result <- 100 * (num / den) names(result) <- "CI" return(result) }
CurveFit2<-function(Data_Corrected){ NumTemps<-as.data.frame(Data_Corrected$NumberTemps)[1,] NumProteins<-as.numeric(nrow(Data_Corrected)) Protein<-1 CurveFitStats<-data.frame(matrix(ncol = 11, nrow = NumProteins)) Data_Corrected_Ordered<-Data_Corrected[order(Data_Corrected$Accession),] NumberRows<-as.numeric(nrow(Data_Corrected_Ordered)) row.names(Data_Corrected_Ordered) <- 1:NumberRows repeat{ ProteinCount<-1 repeat{ if(ProteinCount==1){ ProteinReplicateNumber<-1 Temperature<-as.data.frame(Data_Corrected_Ordered[Protein,(4+NumTemps):(3+NumTemps*2)]) Abundance<-as.data.frame(Data_Corrected_Ordered[Protein,(7+NumTemps*3):(6+NumTemps*4)]) ProteinCount<-ProteinCount+1 ProteinStart<-Protein ProteinID<-Data_Corrected_Ordered[Protein,1] Protein<-Protein+1 } else { if(ProteinCount>1 & ProteinID==Data_Corrected_Ordered[Protein,1]){ Temperature<-cbind(Temperature,as.data.frame(Data_Corrected_Ordered[Protein,(4+NumTemps):(3+NumTemps*2)])) Abundance<-cbind(Abundance,as.data.frame(Data_Corrected_Ordered[Protein,(7+NumTemps*3):(6+NumTemps*4)])) ProteinCount<-ProteinCount+1 Protein<-Protein+1 } else { ProteinEnd<-Protein-1 break } } if (Protein>NumProteins){ ProteinEnd<-(Protein-1) break } } Abundance<-as.numeric(t(Abundance)) Temperature<-as.numeric(t(Temperature)) AbundTemp<-as.data.frame(cbind(Temperature,Abundance)) CurveFit2<-nls(Abundance ~ B_Const+((T_Const-B_Const)/(1 + 10^(scal_Const*(xmid_Const-log10(Temperature)))))^1, data = AbundTemp, start = c(T_Const=1,B_Const=.1,xmid_Const=1.7,scal_Const=-10),nls.control(maxiter = 500,warnOnly = TRUE)) T_Const<-CurveFit2$m$getAllPars()[1] B_Const<-CurveFit2$m$getAllPars()[2] xmid_Const<-CurveFit2$m$getAllPars()[3] scal_Const<-CurveFit2$m$getAllPars()[4] if(CurveFit2$convInfo$isConv==TRUE){ CurveInflection<-10^(CurveFit2$m$getAllPars()[3]) FitParameters<-4 CurveFit2_Summary<-summary(CurveFit2) CurveSE<-CurveFit2_Summary$sigma if(CurveInflection < min(Temperature) || CurveInflection > max(Temperature)) { CurveFit2<-nls(Abundance ~ 0+((T_Const-0)/(1 + 10^(scal_Const*(xmid_Const-log10(Temperature)))))^1, data = AbundTemp, start = c(T_Const=1,xmid_Const=1.7,scal_Const=-10),nls.control(maxiter = 500,warnOnly = TRUE)) if(CurveFit2$convInfo$isConv==TRUE ){ T_Const<-CurveFit2$m$getAllPars()[1] B_Const<-0 xmid_Const<-CurveFit2$m$getAllPars()[2] scal_Const<-CurveFit2$m$getAllPars()[3] CurveFit2_Summary<-summary(CurveFit2) CurveSE<-CurveFit2_Summary$sigma PVal<-data.frame(t(CurveFit2_Summary$parameters[,4])) Xmid_SE<-data.frame(CurveFit2_Summary$parameters[3,2]) Data_CurveFit2Pars<-cbind(T_Const,cbind(B_Const,cbind(xmid_Const,scal_Const))) colnames(Data_CurveFit2Pars)<-paste(colnames(Data_CurveFit2Pars),"-Protein") colnames(PVal)<-paste("P-value",colnames(PVal)) colnames(Xmid_SE)<-"Xmid_SE" FitParameters<-3 } else { FitParameters<-NA T_Const<-NA B_Const<-NA xmid_Const<-NA scal_Const<-NA CurveSE<-NA PVal<-data.frame(t(c(NA,NA,NA,NA))) colnames(PVal)<-c("T_Const","B_Const","xmid_Const","scal_Const") } } else { CurveFit2_Summary<-summary(CurveFit2) CurveSE<-CurveFit2_Summary$sigma PVal<-data.frame(t(CurveFit2_Summary$parameters[,4])) Xmid_SE<-data.frame(CurveFit2_Summary$parameters[3,2]) Data_CurveFit2Pars<-cbind(T_Const,cbind(B_Const,cbind(xmid_Const,scal_Const))) colnames(Data_CurveFit2Pars)<-paste(colnames(Data_CurveFit2Pars),"-Protein") colnames(PVal)<-paste("P-value",colnames(PVal)) colnames(Xmid_SE)<-"Xmid_SE" } } else { CurveFit2<-nls(Abundance ~ 0+((T_Const-0)/(1 + 10^(scal_Const*(xmid_Const-log10(Temperature)))))^1, data = AbundTemp, start = c(T_Const=1,xmid_Const=1.7,scal_Const=-10),nls.control(maxiter = 500,warnOnly = TRUE)) if(CurveFit2$convInfo$isConv==TRUE ){ T_Const<-CurveFit2$m$getAllPars()[1] B_Const<-0 xmid_Const<-CurveFit2$m$getAllPars()[2] scal_Const<-CurveFit2$m$getAllPars()[3] CurveFit2_Summary<-summary(CurveFit2) CurveSE<-CurveFit2_Summary$sigma PVal<-data.frame(t(CurveFit2_Summary$parameters[,4])) Xmid_SE<-data.frame(CurveFit2_Summary$parameters[3,2]) Data_CurveFit2Pars<-cbind(T_Const,cbind(B_Const,cbind(xmid_Const,scal_Const))) colnames(Data_CurveFit2Pars)<-paste(colnames(Data_CurveFit2Pars),"-Protein") colnames(PVal)<-paste("P-value",colnames(PVal)) colnames(Xmid_SE)<-"Xmid_SE" FitParameters<-3 } else { FitParameters<-NA T_Const<-NA B_Const<-NA xmid_Const<-NA scal_Const<-NA CurveSE<-NA PVal<-data.frame(t(c(NA,NA,NA,NA))) colnames(PVal)<-c("T_Const","B_Const","xmid_Const","scal_Const") Xmid_SE<-data.frame(c(NA)) Data_CurveFit2Pars<-cbind(T_Const,cbind(B_Const,cbind(xmid_Const,scal_Const))) colnames(Data_CurveFit2Pars)<-paste(colnames(Data_CurveFit2Pars),"-Protein") colnames(PVal)<-paste("P-value",colnames(PVal)) colnames(Xmid_SE)<-"Xmid_SE" } } Data_CurveFit2_Summary<-cbind(Data_CurveFit2Pars,cbind(FitParameters,cbind(CurveSE,cbind(PVal,Xmid_SE)))) CurveFitStats[ProteinStart:ProteinEnd,]<-Data_CurveFit2_Summary if (Protein>NumProteins){ break } } colnames(CurveFitStats)<-colnames(Data_CurveFit2_Summary) Data_CurveFit2<-cbind(Data_Corrected_Ordered,CurveFitStats) Data_CurveFit2_woNA<-Data_CurveFit2[complete.cases(Data_CurveFit2),] Rsq<-data.frame(matrix(ncol = 1, nrow = NROW(Data_CurveFit2_woNA))) if(NROW(Data_CurveFit2_woNA)>0){ row.names(Data_CurveFit2_woNA)<-1:as.numeric(nrow(Data_CurveFit2_woNA)) NumProteins<-as.numeric(nrow(Data_CurveFit2_woNA)) NumTemps<-as.data.frame(Data_CurveFit2_woNA$NumberTemps)[1,] Protein<-1 repeat{ ProteinCount<-1 repeat{ if(ProteinCount==1){ Temperature<-as.data.frame(Data_CurveFit2_woNA[Protein,(4+NumTemps):(3+NumTemps*2)]) Abundance<-as.data.frame(Data_CurveFit2_woNA[Protein,(7+NumTemps*3):(6+NumTemps*4)]) ProteinID<-Data_CurveFit2_woNA[Protein,1] T_Const<-Data_CurveFit2_woNA[Protein,(11+NumTemps*4)] B_Const<-Data_CurveFit2_woNA[Protein,(12+NumTemps*4)] xmid_Const<-Data_CurveFit2_woNA[Protein,(13+NumTemps*4)] scal_Const<-Data_CurveFit2_woNA[Protein,(14+NumTemps*4)] CurveFit_Predict<-B_Const+((T_Const-B_Const)/(1 + 10^(scal_Const*(xmid_Const-log10(Temperature))))^1) CurveFit_Actual<-t(Abundance) CurveFit_Mean<-mean(CurveFit_Actual) CurveFitData_Rsq<-data.frame(as.numeric(Temperature),as.numeric(CurveFit_Predict),as.numeric(CurveFit_Mean),as.numeric(CurveFit_Actual)) ProteinStart<-Protein ProteinCount<-ProteinCount+1 Protein<-Protein+1 } else { if(ProteinCount>1 & ProteinID==Data_CurveFit2_woNA[Protein,1]){ Temperature<-cbind(Temperature,as.data.frame(Data_CurveFit2_woNA[Protein,(4+NumTemps):(3+NumTemps*2)])) Abundance<-cbind(Abundance,as.data.frame(Data_CurveFit2_woNA[Protein,(7+NumTemps*3):(6+NumTemps*4)])) CurveFit_Predict<-B_Const+((T_Const-B_Const)/(1 + 10^(scal_Const*(xmid_Const-log10(Temperature))))^1) CurveFit_Actual<-t(Abundance) CurveFit_Mean<-mean(CurveFit_Actual) CurveFitData_Rsq<-data.frame(as.numeric(Temperature),as.numeric(CurveFit_Predict),as.numeric(CurveFit_Mean),as.numeric(CurveFit_Actual)) ProteinCount<-ProteinCount+1 Protein<-Protein+1 } else { break } } if (Protein>NumProteins){ break } } ProteinEnd<-Protein-1 TempCount<-1 RSE<-0 TSE<-0 repeat{ RSE<-((CurveFitData_Rsq[TempCount,2]-CurveFitData_Rsq[TempCount,4])^2)+RSE TSE<-((CurveFitData_Rsq[TempCount,3]-CurveFitData_Rsq[TempCount,4])^2)+TSE TempCount<-TempCount+1 if(TempCount>NROW(CurveFitData_Rsq)){ break } } Rsq[ProteinStart:ProteinEnd,]<-1-(RSE/TSE) if (Protein>NumProteins){ break } } } colnames(Rsq)<-"Rsq" Data_CurveFit2_PreComplete<-cbind(Data_CurveFit2_woNA,Rsq) Data_CurveFit2<-Data_CurveFit2_PreComplete[complete.cases(Data_CurveFit2_PreComplete),] rm(CurveFitStats,Data_Corrected,Data_Corrected_Ordered,Data_CurveFit2_woNA,Data_CurveFit2_PreComplete) return(Data_CurveFit2) }
TableStyles <- R6::R6Class("TableStyles", public = list( initialize = function(parentTable, themeName=NULL, allowExternalStyles=FALSE) { if(parentTable$argumentCheckMode > 0) { checkArgument(parentTable$argumentCheckMode, FALSE, "TableStyles", "initialize", parentTable, missing(parentTable), allowMissing=FALSE, allowNull=FALSE, allowedClasses="BasicTable") checkArgument(parentTable$argumentCheckMode, FALSE, "TableStyles", "initialize", themeName, missing(themeName), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") checkArgument(parentTable$argumentCheckMode, FALSE, "TableStyles", "initialize", allowExternalStyles, missing(allowExternalStyles), allowMissing=TRUE, allowNull=TRUE, allowedClasses="logical") } private$p_parentTable <- parentTable if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$new", "Creating new Table Styles...") private$p_theme <- themeName private$p_allowExternalStyles <- allowExternalStyles private$p_styles <- list() if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$new", "Created new Table Styles.") }, isExistingStyle = function(styleName=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "isExistingStyle", styleName, missing(styleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$isExistingStyle", "Checking style exists...", list(styleName=styleName)) styleExists <- styleName %in% names(private$p_styles) if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$isExistingStyle", "Checked style exists.") return(invisible(styleExists)) }, getStyle = function(styleName=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "getStyle", styleName, missing(styleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$getStyle", "Getting style...", list(styleName=styleName)) style <- private$p_styles[[styleName]] if(is.null(style)) { stop(paste0("TableStyles$getStyle(): No style exists with the name '", styleName, "'"), call. = FALSE) } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$getStyle", "Got style.") return(invisible(style)) }, addStyle = function(styleName=NULL, declarations= NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "addStyle", styleName, missing(styleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "addStyle", declarations, missing(declarations), allowMissing=TRUE, allowNull=TRUE, allowedClasses="list", allowedListElementClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$addStyle", "Adding style...", list(styleName=styleName)) if(styleName %in% names(private$p_styles)) { stop(paste0("TableStyles$addStyle(): A style already exists", " with the name '", styleName, "'. styleName must unique."), call. = FALSE) } style <- TableStyle$new(private$p_parentTable, styleName, declarations) private$p_styles[[styleName]] <- style if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$addStyle", "Added style.") return(invisible(style)) }, copyStyle = function(styleName=NULL, newStyleName=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "copyStyle", styleName, missing(styleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "copyStyle", newStyleName, missing(newStyleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$copyStyle", "Copying style...", list(styleName=styleName, newStyleName=newStyleName)) style <- self$getStyle(styleName=styleName) newStyle <- self$addStyle(styleName=newStyleName, declarations=style$declarations) if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$copyStyle", "Copied style.") return(invisible(newStyle)) }, asCSSRule = function(styleName=NULL, selector=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "asCSSRule", styleName, missing(styleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "asCSSRule", selector, missing(selector), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$asCSSRule", "Getting style as CSS rule...", list(styleName=styleName)) style <- self$getStyle(styleName) cssRule <- style$asCSSRule(selector=selector) if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$asCSSRule", "Got style as CSS rule.") return(invisible(cssRule)) }, asNamedCSSStyle = function(styleName=NULL, styleNamePrefix=NULL) { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "asNamedCSSStyle", styleName, missing(styleName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "asNamedCSSStyle", styleNamePrefix, missing(styleNamePrefix), allowMissing=TRUE, allowNull=TRUE, allowedClasses="character") } if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$asNamedCSSStyle", "Getting style as named CSS rule...", list(styleName=styleName, styleNamePrefix=styleNamePrefix)) style <- self$getStyle(styleName) cssRule <- style$asNamedCSSStyle(styleNamePrefix=styleNamePrefix) if(private$p_parentTable$traceEnabled==TRUE) private$p_parentTable$trace("TableStyles$asNamedCSSStyle", "Got style as named CSS rule.") return(invisible(cssRule)) }, asList = function() { lst <- list() if(length(private$p_styles) > 0) { groupNames <- names(private$p_styles) for (i in 1:length(private$p_styles)) { groupName <- groupNames[i] lst[[groupName]] = private$p_styles[[groupName]]$asList() } } return(invisible(lst)) }, asJSON = function() { if (!requireNamespace("jsonlite", quietly = TRUE)) { stop("The jsonlite package is needed to convert to JSON. Please install the jsonlite package.", call. = FALSE) } jsonliteversion <- utils::packageDescription("jsonlite")$Version if(numeric_version(jsonliteversion) < numeric_version("1.1")) { stop("Version 1.1 or above of the jsonlite package is needed to convert to JSON. Please install an updated version of the jsonlite package.", call. = FALSE) } return(jsonlite::toJSON(self$asList())) }, asString = function(seperator=", ") { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "asString", seperator, missing(seperator), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character") } cstr <- "" if(length(private$p_styles)>0) { for(i in 1:length(private$p_styles)) { cg <- private$p_styles[[i]] sep <- "" if(i > 1) { sep <- seperator } cstr <- paste0(cstr, sep, cg$asString()) } } return(cstr) } ), active = list( count = function(value) { return(invisible(length(private$p_styles))) }, theme = function(value) { return(invisible(private$p_theme)) }, styles = function(value) { return(invisible(private$p_styles)) }, allowExternalStyles = function(value) { if(missing(value)) return(invisible(private$p_allowExternalStyles)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "allowExternalStyles", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="logical") } private$p_allowExternalStyles <- value return(invisible()) } }, tableStyle = function(value) { if(missing(value)) return(invisible(private$p_tableStyle)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "tableStyle", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_allowExternalStyles==FALSE) { if(!(value %in% names(private$p_styles))) stop(paste0("TableStyles$tableStyle: '", value, "' style not found in styles list.")) } private$p_tableStyle <- value return(invisible()) } }, rootStyle = function(value) { if(missing(value)) return(invisible(private$p_rootStyle)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "rootStyle", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_allowExternalStyles==FALSE) { if(!(value %in% names(private$p_styles))) stop(paste0("TableStyles$rootStyle: '", value, "' style not found in styles list.")) } private$p_rootStyle <- value return(invisible()) } }, rowHeaderStyle = function(value) { if(missing(value)) return(invisible(private$p_rowHeaderStyle)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "rowHeaderStyle", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_allowExternalStyles==FALSE) { if(!(value %in% names(private$p_styles))) stop(paste0("TableStyles$rowHeaderStyle: '", value, "' style not found in styles list.")) } private$p_rowHeaderStyle <- value return(invisible()) } }, colHeaderStyle = function(value) { if(missing(value)) return(invisible(private$p_colHeaderStyle)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "colHeaderStyle", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_allowExternalStyles==FALSE) { if(!(value %in% names(private$p_styles))) stop(paste0("TableStyles$colHeaderStyle: '", value, "' style not found in styles list.")) } private$p_colHeaderStyle <- value return(invisible()) } }, cellStyle = function(value) { if(missing(value)) return(invisible(private$p_cellStyle)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "cellStyle", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_allowExternalStyles==FALSE) { if(!(value %in% names(private$p_styles))) stop(paste0("TableStyles$cellStyle: '", value, "' style not found in styles list.")) } private$p_cellStyle <- value return(invisible()) } }, totalStyle = function(value) { if(missing(value)) return(invisible(private$p_totalStyle)) else { if(private$p_parentTable$argumentCheckMode > 0) { checkArgument(private$p_parentTable$argumentCheckMode, FALSE, "TableStyles", "totalStyle", value, missing(value), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_allowExternalStyles==FALSE) { if(!(value %in% names(private$p_styles))) stop(paste0("TableStyles$totalStyle: '", value, "' style not found in styles list.")) } private$p_totalStyle <- value return(invisible()) } } ), private = list( p_parentTable = NULL, p_theme = NULL, p_allowExternalStyles = FALSE, p_styles = NULL, p_tableStyle = NULL, p_rootStyle = NULL, p_rowHeaderStyle = NULL, p_colHeaderStyle = NULL, p_cellStyle = NULL, p_totalStyle = NULL ) )
summary.CA <- function(object,nb.dec=3,nbelements=10,ncp=3,align.names=TRUE,file="",...){ print2 <- function(mat,file=""){ if (file=="") print(mat, quote = FALSE, right = TRUE) else { mat <- cbind(format(rownames(mat)),mat) mat <- rbind(colnames(mat),mat) mat2 <- cbind(format(mat[,1],justify="right"),format(mat[,2],justify="right")) for (k in 3:ncol(mat)) mat2 <- cbind(mat2,format(mat[,k],justify="right")) mat2 <- cbind(mat2,"\n") for (i in 1:nrow(mat2)) cat(mat2[i,],file=file,append=TRUE) } } print3 <- function(obj,file="",ncp,width.row=0,nbelements=nbelements){ list.obj <- match.arg(names(obj),c("dist","inertia","coord","cos2","contrib","v.test","vtest"),several.ok=TRUE) nb.col <- sum(c("coord","cos2","contrib","v.test")%in%list.obj) nbelements <- min(nbelements,nrow(obj$coord)) mat <- matrix(NA,nbelements,sum(c("dist","inertia")%in%list.obj)+nb.col*ncp) colnames(mat) <- paste("v",1:ncol(mat)) rownames(mat) <- format(rownames(obj$coord)[1:nbelements,drop=FALSE],width=width.row) indice <- 1 if (sum(c("dist","inertia")%in%list.obj)) { if ("dist"%in%list.obj) { if (!is.null(obj$dist)) mat[,indice] <- obj$dist[1:nbelements] colnames(mat)[indice] <- "Dist" } if ("inertia"%in%list.obj) { if (!is.null(obj$inertia)) mat[,indice] <- obj$inertia[1:nbelements]*1000 colnames(mat)[indice] <- "Iner*1000" } indice <- indice + 1 } if ("coord"%in%list.obj){ if (!is.null(obj$coord)) mat[,indice+nb.col*(0:(ncp-1))] <- obj$coord[1:nbelements,1:ncp,drop=FALSE] colnames(mat)[indice+nb.col*(0:(ncp-1))] <- paste("Dim.",1:ncp,sep="") indice <- indice +1 } if ("contrib"%in%list.obj){ if (!is.null(obj$contrib)) mat[,indice+nb.col*(0:(ncp-1))] <- obj$contrib[1:nbelements,1:ncp,drop=FALSE] colnames(mat)[indice+nb.col*(0:(ncp-1))] <- "ctr" indice <- indice +1 } if ("cos2"%in%list.obj){ if (!is.null(obj$cos2)) mat[,indice+nb.col*(0:(ncp-1))] <- obj$cos2[1:nbelements,1:ncp,drop=FALSE] colnames(mat)[indice+nb.col*(0:(ncp-1))] <- "cos2" indice <- indice +1 } if ("v.test"%in%list.obj){ if (!is.null(obj$v.test)) mat[,indice+nb.col*(0:(ncp-1))] <- obj$v.test[1:nbelements,1:ncp,drop=FALSE] colnames(mat)[indice+nb.col*(0:(ncp-1))] <- "v.test" indice <- indice +1 } mat <- format(round(mat,nb.dec)) if (sum(c("dist","inertia")%in%list.obj)) mat2 <- cbind("|", mat[1:nbelements,1,drop=FALSE],"|") else mat2 <- "|" for (k in 1:ncp) mat2 <- cbind(mat2, mat[,(1+sum(c("dist","inertia")%in%list.obj)+nb.col*(k-1)):(sum(c("dist","inertia")%in%list.obj)+nb.col*k),drop=FALSE],"|") colnames(mat2)[1] <- "" print2(as.matrix(mat2),file=file) } res <- object if (!inherits(res, "CA")) stop("non convenient object") cat(paste("\nCall:\n"),file=file) cat(paste(deparse(res$call$call),"\n"),file=file,append=TRUE) cat("\n",file=file,append=TRUE) IT <- sum(res$eig[, 1] )* sum(res$call$X) df <- (nrow(res$call$X) - 1) * (ncol(res$call$X) - 1) pc <- pchisq(IT, df = df,lower.tail = FALSE) cat("The chi square of independence between the two variables is equal to", IT, "(p-value = ", pc, ").\n",file=file,append=TRUE) cat("\nEigenvalues\n",file=file,append=TRUE) eige <- format(t(round(res$eig[,1:3],nb.dec)),justify="right") rownames(eige) <- c("Variance","% of var.","Cumulative % of var.") colnames(eige) <- paste("Dim",1:ncol(eige),sep=".") print2(eige,file=file) width.row <- 0 if (align.names==TRUE){ aux <- match.arg(names(res),c("ind","ind.sup","freq","freq.sup","var","quanti.var","quanti.sup","quali.var","quali.sup","quanti.sup","quali.sup","group","row","row.sup","col","col.sup"),several.ok = TRUE) width.row = max(nchar(rownames(res[aux[1]][[1]]$coord))) for (k in 1:length(aux)) width.row = max(width.row,nchar(rownames(res[aux[k]][[1]]$coord)[1:min(nrow(res[aux[k]][[1]]$coord),nbelements)])) } ncp <- min(res$call$ncp,ncp) cat("\nRows",file=file,append=TRUE) if (nrow(res$row$coord) > nbelements) cat(paste(" (the ",nbelements," first)",sep=""),file=file,append=TRUE) cat("\n",file=file,append=TRUE) print3(res$row,file=file,ncp=ncp,width.row=width.row,nbelements=nbelements) cat("\nColumns",file=file,append=TRUE) if (nrow(res$col$coord) > nbelements) cat(paste(" (the ",nbelements," first)",sep=""),file=file,append=TRUE) cat("\n",file=file,append=TRUE) print3(res$col,file=file,ncp=ncp,width.row=width.row,nbelements=nbelements) if (!is.null(res$row.sup)){ cat("\nSupplementary row",file=file,append=TRUE) if (nrow(res$row.sup$coord)>1) cat("s",file=file,append=TRUE) if (nrow(res$row.sup$coord) > nbelements) cat(paste(" (the ",nbelements," first)",sep=""),file=file,append=TRUE) cat("\n",file=file,append=TRUE) print3(res$row.sup,file=file,ncp=ncp,width.row=width.row,nbelements=nbelements) } if (!is.null(res$col.sup)){ cat("\nSupplementary column",file=file,append=TRUE) if (nrow(res$col.sup$coord)>1) cat("s",file=file,append=TRUE) if (nrow(res$col.sup$coord) > nbelements) cat(paste(" (the ",nbelements," first)",sep=""),file=file,append=TRUE) cat("\n",file=file,append=TRUE) print3(res$col.sup,file=file,ncp=ncp,width.row=width.row,nbelements=nbelements) } if (!is.null(res$quanti.sup)){ cat("\nSupplementary continuous variable",file=file,append=TRUE) if (nrow(res$quanti.sup$coord)>1) cat("s",file=file,append=TRUE) cat("\n",file=file,append=TRUE) print3(res$quanti.sup,file=file,ncp=ncp,width.row=width.row,nbelements=nbelements) } if (!is.null(res$quali.sup)){ cat("\nSupplementary categorical variable",file=file,append=TRUE) if (nrow(res$quali.sup$coord)>1) cat("s",file=file,append=TRUE) cat("\n",file=file,append=TRUE) print3(res$quali.sup,file=file,ncp=ncp,width.row=width.row,nbelements=nbelements) } }
add_bar_grouped <- function(shift, data, cat, series, k , y, width_of_one, series_labels = NULL, df_styles = NULL) { svg_string <- "" labels <- "" value_label <- "" x <- get_margins()$left + shift for (i in length(series):1){ value <- data[,series[i]] color <- get_color_stacked(i) if(length(series) == 2 || i == 1){ styles <- df_styles[,length(series)-i+1] }else{ styles <- df_styles[,i - 1] } if(i != 1 && value[k] < 0){ x <- x - (width_of_one*abs(value[k])) } if(i == 1){ rect <- draw_triangle("", width_of_one*value[k] + x ,y+8 , orientation = "bottom", style=styles[k]) }else{ rect <- draw_rect(x, y - 4.8*(i-2), color$bar_color, (width_of_one*abs(value[k])), 16, style = styles[k]) } x <- get_margins()$left + shift svg_string <- paste(svg_string, rect, labels, sep = '\n') if(i == 2){ if(value[k]>0){value_label <- paste(value_label, add_label((x + width_of_one*value[k]+4.8), y+12, value[k], anchor="start"), sep='\n')} else{value_label <- add_label(x + 4.8, y+12, value[k], anchor="start")} } } return(paste(svg_string, value_label, add_label( get_margins()$left - 7.8, y+14, cat[k], anchor="end"), draw_line(get_margins()$left + shift, get_margins()$left+shift, (y-4.8) - 4.8, (y+16+4.8)), sep = '\n' )) } draw_bars_grouped <- function(svg_string, data, cat, foreground, background, markers, series_labels, df_with_real_values=NULL, df_styles = NULL){ bars <- svg_string y = get_margins()$top if(length(foreground) == 1){forg <- data[ ,foreground] }else{ forg <- foreground foreground <- "foreground"} if(length(background) == 1){backg <- data[ ,background] }else{ backg <- background background <- "background"} if(length(markers) == 1){mark <- data[ ,markers] }else{ mark <- markers markers <- "markers"} if(length(cat) == 1){cat <- data[ ,cat] } series <- c(markers, foreground, background) data <- cbind(mark, forg, backg) colnames(data) <- series data <- as.data.frame(data) neg <- data[, series][data[,series] < 0] maximum <- max(abs(data[,series])) width_of_one <- 200/maximum if(length(neg) == 0){shift <- 0 }else{ shift <- width_of_one*abs(min(neg))} if(length(series)==3){ bars <- paste( bars, add_label(get_margins()$left + shift + data[,series[3]][1]*width_of_one/2, get_margins()$top - 4.8*(length(series)-1), series_labels[3]), sep= '\n' ) } bars <- paste(bars, add_label(get_margins()$left + shift + data[,series[2]][length(cat)]*width_of_one/2, get_margins()$top + 24 * length(cat) + 4.8, series_labels[2]), add_bar_grouped(shift, data, cat, series, 1, y, width_of_one, series_labels, df_styles=df_styles), sep='\n') y <- y + 24 for(i in 2:length(cat)){ bars <- paste(bars, add_bar_grouped(shift ,data, cat, series,i, y, width_of_one, df_styles = df_styles), sep='\n') y <- y + 24 } return (bars) } bar_chart_grouped <- function(data, cat, foreground, background, markers=NULL, series_labels, styles = NULL){ svg_string <- initialize(width = 320 + get_margins()$left, height= get_margins()$top + 24*length(cat) + get_margins()$top) %>% draw_bars_grouped(data, cat, foreground, background, markers, series_labels, df_styles = styles) %>% finalize() class(svg_string) <- c('tidychart', 'character') return(svg_string) }
soboltouati <- function(model = NULL, X1, X2, conf = 0.95, ...) { if ((ncol(X1) != ncol(X2)) | (nrow(X1) != nrow(X2))) stop("The samples X1 and X2 must have the same dimensions") p <- ncol(X1) X <- rbind(X1,X2) for (i in 1:p) { Xb <- X1 Xb[,i] <- X2[,i] X <- rbind(X, Xb) } x <- list(model = model, X1 = X1, X2 = X2, conf = conf, X = X, call = match.call()) class(x) <- "soboltouati" if (!is.null(x$model)) { response(x, ...) tell(x) } return(x) } Pmv = function(x,Y,Z){ cov11 = cov(Y,Z) cov21 = cov(Y^2,Z) cov12 = cov(Y,Z^2) cov22 = cov(Y^2,Z^2) cov31 = cov(Y^3,Z) cov13 = cov(Y,Z^3) EY = mean(Y) EY2 = mean(Y^2) EZ = mean(Z) EZ2 = mean(Z^2) sdY = sd(Y) sdZ = sd(Z) corYZ = cor(Y,Z) K11 = var((Y-EY)*(Z-EZ)) K12 = (cov31 - 3*EY*cov21 - cov11*(EY2-4*EY^2))/(2*sdY) K13 = (cov13 - 3*EZ*cov12 - cov11*(EZ2-4*EZ^2))/(2*sdZ) K22 = (mean((Y-EY)^4) - sdY^4)/(4*sdY^2) K23 = (cov((Y-EY)^2,(Z-EZ)^2) + 2*EZ*cov((Y-EY)^2,(Z-EZ)) - 2*EZ*cov((Y-EY)^2, Y-EY))/(4*sdY*sdZ) K33 = (mean((Z-EZ)^4) - sdZ^4)/(4*sdZ^2) return(abs((K22/(sdY^2) + K33/(sdZ^2) + 2*K23/(sdY*sdZ))*x^2 - 2*x*(K12/sdY + K13/sdZ)/(sdY*sdZ) + K11/((sdY*sdZ)^2))) } estim.soboltouati <- function(data, i = 1 : nrow(data), conf=0) { d <- as.matrix(data[i, ]) n <- nrow(d) p <- ncol(d)-2 V <- var(d[, 1]) ecor <- rep(0,p) ; ecorcompl <- rep(0,p) if(conf != 0) { VV <- matrix(V,nrow=1,ncol=3,dimnames=list(1,c("estim","CIinf","CIsup"))) estcor <- matrix(0,nrow=p,ncol=3,dimnames=list(2:(p+1),c("estim","CIinf","CIsup"))) estcorcompl <- matrix(0,nrow=p,ncol=3,dimnames=list((p+2):(2*p+1),c("estim","CIinf","CIsup"))) } for(ii in 1:p) { ecor[ii] <- cor(d[,2],d[,ii+2],use="pairwise.complete.obs") ecorcompl[ii] <- cor(d[,1],d[,ii+2],use="pairwise.complete.obs") if(conf != 0) { estcor[ii,1] <- ecor[ii] tau2 = Pmv(estcor[ii,1],d[,2],d[,ii+2]) estcor[ii,2] <- estcor[ii,1] - sqrt(tau2)*qnorm((1+conf)/2)/sqrt(n) estcor[ii,3] <- estcor[ii,1] + sqrt(tau2)*qnorm((1+conf)/2)/sqrt(n) estcorcompl[ii,1] <- ecorcompl[ii] tau2 = Pmv(estcorcompl[ii,1],d[,1],d[,ii+2]) estcorcompl[ii,2] <- estcorcompl[ii,1] + sqrt(tau2)*qnorm((1+conf)/2)/sqrt(n) estcorcompl[ii,3] <- estcorcompl[ii,1] - sqrt(tau2)*qnorm((1+conf)/2)/sqrt(n) } } if(conf != 0) { return(rbind(VV, estcor, estcorcompl))} else { return(c(V, ecor, ecorcompl))} } tell.soboltouati <- function(x, y = NULL, return.var = NULL, ...) { id <- deparse(substitute(x)) if (! is.null(y)) { x$y <- y } else if (is.null(x$y)) { stop("y not found") } p <- ncol(x$X1) n <- nrow(x$X1) data <- matrix(x$y, nrow = n) V <- data.frame(original = estim.soboltouati(data, 1:n, x$conf)) if(x$conf){colnames(V) <- c("original","min. c.i.","max. c.i.")} else{colnames(V) <- c("original")} S <- V[2:(p + 1),, drop = FALSE] T <- 1 - V[(p + 2):(2 * p + 1),, drop = FALSE] rownames(S) <- colnames(x$X1) rownames(T) <- colnames(x$X1) x$V <- V x$S <- S x$T <- T assign(id, x, parent.frame()) } print.soboltouati <- function(x, ...) { cat("\nCall:\n", deparse(x$call), "\n", sep = "") if (!is.null(x$y)) { cat("\nModel runs:", length(x$y), "\n") cat("\nFirst order indices:\n") if(!is.null(x$S$original.CIinf)) { df=data.frame(pointEstimate=x$S[,1], minCI=x$S[,2], maxCI=x$S[,3]) colnames(df)=c("estimate","min. c.i.","max. c.i.") print(df) } else { print(x$S) } cat("\nTotal indices:\n") if(!is.null(x$T$original.CIinf)) { df=data.frame(pointEstimate=x$T[,1], minCI=x$T[,2], maxCI=x$T[,3]) colnames(df)=c("estimate","min. c.i.","max. c.i.") print(df) } else { print(x$T) } } } plot.soboltouati <- function(x, ylim = c(0, 1), ...) { if (!is.null(x$y)) { p <- ncol(x$X1) pch = c(21, 24) nodeplot(x$S, xlim = c(1, p + 1), ylim = ylim, pch = pch[1]) nodeplot(x$T, xlim = c(1, p + 1), ylim = ylim, labels = FALSE, pch = pch[2], at = (1:p)+.3, add = TRUE) legend(x = "topright", legend = c("main effect", "total effect"), pch = pch) } } ggplot.soboltouati <- function(x, ylim = c(0, 1), ...) { if (!is.null(x$y)) { p <- ncol(x$X1) pch = c(21, 24) nodeggplot(listx = list(x$S,x$T), xname = c("Main effet","Total effect"), ylim = ylim, pch = pch) } }
GroupFXTrades = function(group_trades, trade_classes_tree,hedging_set_name) { lapply(group_trades, function(x) x$base_ccy="EUR") lapply(group_trades, function(x) x$setFXDynamic()) ccypairs <- unique(lapply(group_trades, function(x) x$ccyPair)) if(!missing(hedging_set_name)) { if(substr(hedging_set_name,1,4)=="Vol_"||substr(hedging_set_name,1,6)=="Basis_") temp_ccypairs = paste0(hedging_set_name,"_",ccypairs) }else { temp_ccypairs = ccypairs} ccypairs_addon <- array(data<-0,dim<-length(ccypairs)) ccypairs_tree = list() if(length(trade_classes_tree[["Currency Pairs"]])==0) { ccypairs_tree_name = trade_classes_tree$AddChild("Currency Pairs") }else { ccypairs_tree_name = trade_classes_tree[["Currency Pairs"]]} for (j in 1:length(ccypairs)) { ccypairs_trades <- group_trades[sapply(group_trades, function(x) (x$ccyPair==temp_ccypairs[j]))] ccypairs_tree[[j]] = ccypairs_tree_name$AddChild(temp_ccypairs[[j]]) trades_tree_name = ccypairs_tree[[j]]$AddChild("Trades") for (l in 1:length(ccypairs_trades)) { tree_trade = trades_tree_name$AddChild(ccypairs_trades[[l]]$external_id) tree_trade$trade_details = Trading::GetTradeDetails(ccypairs_trades[[l]]) tree_trade$trade = ccypairs_trades[[l]] } } return(trade_classes_tree) }
context("Testing add_prior_information") orig_cell_ids <- c("a", "b", "c", "d", "e", "f") cell_ids <- unlist(map(1:100, ~ paste0(orig_cell_ids, .))) milestone_ids <- c("W", "X", "Y", "Z", "A") milestone_network <- tribble( ~from, ~to, ~length, ~directed, "W", "X", 2, TRUE, "X", "Y", 3, TRUE, "X", "Z", 4, TRUE, "Z", "A", 5, TRUE ) divergence_regions <- tribble( ~divergence_id, ~milestone_id, ~is_start, "XYZ", "X", TRUE, "XYZ", "Y", FALSE, "XYZ", "Z", FALSE ) milestone_percentages <- tribble( ~cell_id, ~milestone_id, ~percentage, "a", "W", 1, "b", "W", .2, "b", "X", .8, "c", "X", .8, "c", "Z", .2, "d", "Z", 1, "e", "X", .3, "e", "Y", .2, "e", "Z", .5, "f", "Z", .8, "f", "A", .2 ) %>% crossing(i = 1:100) %>% mutate(cell_id = paste0(cell_id, i)) %>% select(-i) progressions <- convert_milestone_percentages_to_progressions( cell_ids, milestone_ids, milestone_network, milestone_percentages ) num_genes <- 100 gene_ids <- paste0("Gene", seq_len(num_genes)) expression <- matrix(rbinom(num_genes * length(cell_ids), 10000, .01), ncol = num_genes, dimnames = list(cell_ids, gene_ids)) feature_info <- tibble( feature_id = gene_ids, test = 1, housekeeping = sample(c(T, F), size = length(gene_ids), replace = TRUE) ) cell_info <- tibble( cell_id = cell_ids, test = 2, simulationtime = runif(length(cell_ids)), timepoint = runif(length(cell_ids)) ) test_that("Testing generate_prior_information", { tmp <- tempfile() on.exit(file.remove(tmp)) sink(tmp) prior_info <- generate_prior_information( cell_ids = cell_ids, milestone_ids = milestone_ids, milestone_network = milestone_network, milestone_percentages = milestone_percentages, progressions = progressions, divergence_regions = divergence_regions, expression = expression, feature_info = feature_info, cell_info = cell_info, verbose = TRUE ) sink() expected_prior <- c( "start_milestones", "start_id", "end_milestones", "end_id", "groups_id", "groups_network", "features_id", "groups_n", "timecourse_continuous", "timecourse_discrete", "end_n", "start_n", "leaves_n" ) testthat::expect_true(all(expected_prior %in% names(prior_info))) testthat::expect_equal(prior_info$start_milestones, "W") testthat::expect_equal(gsub("[0-9]+", "", prior_info$start_id), "a") testthat::expect_equal(prior_info$end_milestones %>% sort, c("A", "Y")) testthat::expect_equal(gsub("[0-9]+", "", prior_info$end_id), c("b", "f")) join_check <- milestone_percentages %>% group_by(cell_id) %>% arrange(desc(percentage)) %>% slice(1) %>% select(-percentage) %>% ungroup() %>% full_join(prior_info$groups_id, by = "cell_id") testthat::expect_equal(join_check$group_id, join_check$milestone_id) testthat::expect_equal(prior_info$groups_network, milestone_network %>% select(from, to)) testthat::expect_true(all(prior_info$features_id %in% gene_ids)) testthat::expect_equal(prior_info$groups_n, 4) testthat::expect_equal(prior_info$timecourse_continuous, set_names(cell_info$simulationtime, cell_info$cell_id)) testthat::expect_equal(prior_info$timecourse_discrete, set_names(cell_info$timepoint, cell_info$cell_id)) testthat::expect_equal(prior_info$end_n, 2) testthat::expect_equal(prior_info$start_n, 1) testthat::expect_equal(prior_info$leaves_n, 3) }) test_that("Testing add_prior_information", { trajectory <- wrap_data( id = "test", cell_ids = cell_ids, cell_info = cell_info ) %>% add_trajectory( milestone_ids = milestone_ids, milestone_network = milestone_network, milestone_percentages = milestone_percentages, divergence_regions = divergence_regions ) %>% add_expression( counts = expression, expression = expression, feature_info = feature_info ) trajectory2 <- add_prior_information(trajectory, verbose = FALSE) prior_info <- trajectory2$prior_information expect_false(is_wrapper_with_prior_information(trajectory)) expect_true(is_wrapper_with_prior_information(trajectory2)) expected_prior <- c( "start_milestones", "start_id", "end_milestones", "end_id", "groups_id", "groups_network", "features_id", "groups_n", "timecourse_continuous", "timecourse_discrete", "start_n", "end_n", "leaves_n" ) testthat::expect_true(all(expected_prior %in% names(prior_info))) testthat::expect_equal(prior_info$start_milestones, "W") testthat::expect_equal(gsub("[0-9]+", "", prior_info$start_id), "a") testthat::expect_equal(prior_info$end_milestones %>% sort, c("A", "Y")) testthat::expect_equal(gsub("[0-9]+", "", prior_info$end_id), c("b", "f")) join_check <- milestone_percentages %>% group_by(cell_id) %>% arrange(desc(percentage)) %>% slice(1) %>% select(-percentage) %>% ungroup() %>% full_join(prior_info$groups_id, by = "cell_id") testthat::expect_equal(join_check$group_id, join_check$milestone_id) testthat::expect_equal(prior_info$groups_network, milestone_network %>% select(from, to)) testthat::expect_true(all(prior_info$features_id %in% gene_ids)) testthat::expect_equal(prior_info$groups_n, 4) testthat::expect_equal(prior_info$timecourse_continuous, set_names(cell_info$simulationtime, cell_info$cell_id)) testthat::expect_equal(prior_info$timecourse_discrete, set_names(cell_info$timepoint, cell_info$cell_id)) testthat::expect_equal(prior_info$end_n, 2) testthat::expect_equal(prior_info$start_n, 1) testthat::expect_equal(prior_info$leaves_n, 3) }) orig_cell_ids <- c("a", "b", "c", "d", "e", "f") cell_ids <- orig_cell_ids %>% map(~paste0(., seq_len(20))) %>% unlist() orig_map <- set_names(gsub("[0-9]+", "", cell_ids), cell_ids) milestone_ids <- c("X", "Y", "Z") milestone_network <- tribble( ~from, ~to, ~length, ~directed, "X", "Y", 3, FALSE, "Y", "Z", 4, FALSE, "Z", "X", 5, FALSE ) divergence_regions <- NULL orig_progressions <- tribble( ~orig_cell_id, ~from, ~to, ~percentage, "a", "Z", "X", 1, "b", "X", "Y", 0.8, "c", "X", "Y", 1, "d", "Y", "Z", 0.75, "e", "Y", "Z", 1, "f", "Z", "X", .6 ) progressions <- tibble(cell_id = cell_ids, orig_cell_id = orig_map) %>% left_join(orig_progressions, by = "orig_cell_id") %>% mutate( percentage = percentage + runif(n(), -.3, .3), percentage = ifelse(percentage > 1, 1, ifelse(percentage < 0, 0, percentage)) ) %>% select(-orig_cell_id) milestone_percentages <- convert_progressions_to_milestone_percentages( cell_ids, milestone_ids, milestone_network, progressions ) num_genes <- 20 orig_gene_ids <- paste0("Gene", seq_len(num_genes)) orig_expression <- matrix(rbinom(num_genes * length(cell_ids), 10000, .01), ncol = num_genes, dimnames = list(cell_ids, orig_gene_ids)) milpct <- milestone_percentages %>% reshape2::acast(cell_id ~ milestone_id, value.var = "percentage", fill = 0) expression <- cbind(orig_expression, milpct) * 100 + 2 gene_ids <- colnames(expression) test_that("Testing generate_prior_information", { prior_info <- generate_prior_information( cell_ids = cell_ids, milestone_ids = milestone_ids, milestone_network = milestone_network, milestone_percentages = milestone_percentages, progressions = progressions, divergence_regions = divergence_regions, expression = expression ) expected_prior <- c( "start_milestones", "start_id", "end_milestones", "end_id", "groups_id", "groups_network", "features_id", "groups_n", "timecourse_continuous", "timecourse_discrete", "end_n" ) testthat::expect_true(all(expected_prior %in% names(prior_info))) join_check <- milestone_percentages %>% group_by(cell_id) %>% arrange(desc(percentage)) %>% slice(1) %>% select(-percentage) %>% ungroup() %>% full_join(prior_info$groups_id, by = "cell_id") testthat::expect_equal(join_check$group_id, join_check$milestone_id) testthat::expect_equal(prior_info$groups_network, milestone_network %>% select(from, to)) testthat::expect_true(all(prior_info$features_id %in% gene_ids)) testthat::expect_equal(prior_info$groups_n, 3) }) test_that("Testing add_prior_information", { trajectory <- wrap_data( id = "test", cell_ids = cell_ids ) %>% add_trajectory( milestone_ids = milestone_ids, milestone_network = milestone_network, milestone_percentages = milestone_percentages, divergence_regions = divergence_regions ) %>% add_expression( expression = expression, counts = expression ) tmp <- tempfile() on.exit(file.remove(tmp)) sink(tmp) trajectory2 <- add_prior_information(trajectory, verbose = TRUE) sink() prior_info <- trajectory2$prior_information expect_false(is_wrapper_with_prior_information(trajectory)) expect_true(is_wrapper_with_prior_information(trajectory2)) expected_prior <- c( "start_milestones", "start_id", "end_milestones", "end_id", "groups_id", "groups_network", "features_id", "groups_n", "timecourse_continuous", "timecourse_discrete", "end_n" ) testthat::expect_true(all(expected_prior %in% names(prior_info))) join_check <- milestone_percentages %>% group_by(cell_id) %>% arrange(desc(percentage)) %>% slice(1) %>% select(-percentage) %>% ungroup() %>% full_join(prior_info$groups_id, by = "cell_id") testthat::expect_equal(join_check$group_id, join_check$milestone_id) testthat::expect_equal(prior_info$groups_network, milestone_network %>% select(from, to)) testthat::expect_true(all(prior_info$features_id %in% gene_ids)) testthat::expect_equal(prior_info$groups_n, 3) })
auk_clean <- function(f_in, f_out, sep = "\t", remove_text = FALSE, overwrite = FALSE) { .Deprecated() awk_path <- auk_get_awk_path() if (is.na(awk_path)) { stop("auk_clean() requires a valid AWK install.") } assertthat::assert_that( assertthat::is.string(sep), nchar(sep) == 1, sep != " ", assertthat::is.flag(remove_text), assertthat::is.flag(overwrite) ) f_in <- ebd_file(f_in) if (!dir.exists(dirname(f_out))) { stop("Output directory doesn't exist.") } if (!overwrite && file.exists(f_out)) { stop("Output file already exists, use overwrite = TRUE.") } f_out <- normalizePath(f_out, winslash = "/", mustWork = FALSE) header <- get_header(f_in, sep) if (header[length(header)] == "") { header <- header[-length(header)] } ncols <- length(header) if (ncols < 30) { stop( sprintf("There is an error in your EBD file, only %i columns detected.", ncols) ) } if (remove_text) { text_cols <- c("locality", "first name", "last name", "trip comments", "species comments") keep_cols <- which(!tolower(header) %in% text_cols) print_cols <- paste0("$", keep_cols, collapse = ",") } else { print_cols <- "$0" } awk <- str_interp(awk_clean, list(sep = sep, ncols = ncols, print_cols = print_cols)) exit_code <- system2(awk_path, args = paste0("'", awk, "' ", f_in), stdout = f_out, stderr = FALSE) if (exit_code == 0) { f_out } else { exit_code } } awk_clean <- " BEGIN { FS = \"${sep}\" OFS = \"${sep}\" } { sub(/\t$/, \"\", $0) if (NF != ${ncols} || NR == 1) { print ${print_cols} } } "
context("Testing minor lookup tables for STN_* functions") test_that("hy_stn_remarks returns a dataframe", { expect_is(hy_stn_remarks( station_number = "08MF005", hydat_path = hy_test_db() ), class = "tbl_df") }) test_that("hy_stn_datum_conv returns a dataframe", { expect_is(hy_stn_datum_conv( station_number = "08MF005", hydat_path = hy_test_db() ), class = "tbl_df") }) test_that("hy_stn_data_range returns a dataframe", { expect_is(hy_stn_data_range( station_number = "08MF005", hydat_path = hy_test_db() ), class = "tbl_df") }) test_that("hy_stn_data_coll returns a dataframe", { expect_is(hy_stn_data_coll( station_number = "08MF005", hydat_path = hy_test_db() ), class = "tbl_df") }) test_that("hy_stn_op_schedule returns a dataframe", { expect_is(hy_stn_op_schedule( station_number = "08MF005", hydat_path = hy_test_db() ), class = "tbl_df") }) test_that("hy_stn_data_range contains properly coded NA's",{ expect_true(is.na(hy_stn_data_range(hydat_path = hy_test_db())$SED_DATA_TYPE[1])) })
plot.gevp <- function(x, type = c("histogram","predictive", "retlevel"), t=2, k=100, ...){ if(type=="histogram"){ par(mfrow=c(1,3)) hist(x$posterior[,1],freq=FALSE,main=expression(mu), xlab=NULL) abline(v=quantile(x$posterior[,1],0.025),lwd=2) abline(v=quantile(x$posterior[,1],0.975),lwd=2) hist(x$posterior[,2],freq=FALSE,main=expression(sigma), xlab=NULL) abline(v=quantile(x$posterior[,2],0.025),lwd=2) abline(v=quantile(x$posterior[,2],0.975),lwd=2) hist(x$posterior[,3],freq=FALSE,main=expression(xi), xlab=NULL) abline(v=quantile(x$posterior[,3],0.025),lwd=2) abline(v=quantile(x$posterior[,3],0.975),lwd=2) par(mfrow=c(1,1)) } if(type=="predictive"){ dat=x$data linf = max(min(dat) - 1, 0) lsup = 11 * max(dat)/10 dat1 = seq(linf, lsup, (lsup - linf)/70) n = length(dat1) int = length(x$posterior[, 1]) res = array(0, c(n)) for (i in 1:n) { for (j in 1:int) { if ((x$posterior[j, 3] > 0) && (dat1[i] > (x$posterior[j, 1] - x$posterior[j, 2]/x$posterior[j, 3]))) res[i] = res[i] + (1/int) * dgev(dat1[i], x$posterior[j, 3], x$posterior[j, 1], x$posterior[j, 2]) if ((x$posterior[j, 3] < 0) && (dat1[i] < (x$posterior[j, 1] - x$posterior[j, 2]/x$posterior[j, 3]))) res[i] = res[i] + (1/int) * dgev(dat1[i], x$posterior[j, 3], x$posterior[j, 1], x$posterior[j, 2]) } } hist(dat, freq = F, ylim = c(min(res), max(res)), main=NULL, xlab = "data", ylab = "density", ...) lines(dat1, res) out<-list(pred=res) return(out) } if(type=="retlevel"){ sampl = qgev(1 - 1/t, x$posterior[, 3], x$posterior[, 1], x$posterior[, 2]) res = quantile(sampl, 0.5) ta=seq(1,k,1) n = length(ta) li = array(0, c(n)) ls = array(0, c(n)) pred = array(0, c(n)) for (s in 1:n) { sampl = qgev(1 - 1/s, x$posterior[, 3], x$posterior[, 1], x$posterior[, 2]) li[s] = quantile(sampl, 0.025) ls[s] = quantile(sampl, 0.975) pred[s] = quantile(sampl, 0.5) } plot(ta, pred, type = "l", xlab="t", ylim = c(li[2], max(ls)), ylab = "returns", ...) lines(ta, li, lty = 2) lines(ta, ls, lty = 2) out<-list(retmedian=res, retpred=pred) return(out) } }
AcceptableMove <- function(proposal, qmax, self.loops, target, fixed.edges) { acceptable = all(apply(proposal, 1, sum) <= qmax) if(!self.loops) { acceptable = acceptable && all(proposal[,target] == 0) } fixed.segs = t(matrix(c(fixed.edges, -1), dim(proposal)[2], dim(proposal)[1])) indices.fixed = fixed.segs >= 0 acceptable = acceptable && all(fixed.segs[indices.fixed] == proposal[indices.fixed]) return(acceptable) }
"arsefigures"
function.id <- function( cores, site.id, tree.id, core.id){ site <- substr( cores, site.id[ 1 ], site.id[ 2 ]) tree <- substr( cores, tree.id[ 1 ], tree.id[ 2 ]) series <- substr( cores,core.id[ 1 ], core.id[ 2 ]) cores.x <- toupper(paste("HUP",tree,series,sep="",collapse=NULL)) return( cores.x ) } SumNotNa <- function( x ) { sum( is.na( x ) == FALSE) } exact.ci<- function(p.adjust, size.x, size.y, i){ n <- (size.x[i]*size.y[i]) s <- as.integer(as.vector(p.adjust[i]*n)) ci.j <- matrix(NA, nrow = length(s), ncol = 2) for ( t in 1: length(s)){ if(is.na(s)){ci.j[,t] <- NA}else{ if(s[t] > n){s[t] = n} ci.j[t,] <- binom.test(s[t],n , p = 1, alternative = c("two.sided"), conf.level = 0.95)$conf.int } } return(ci.j) } function.id.master <- function( cores, site.id, tree.id, core.id){ site <- substr( cores, site.id[ 1 ], site.id[ 2 ]) tree <- substr( cores, tree.id[ 1 ], tree.id[ 2 ]) series <- substr( cores,core.id[ 1 ], core.id[ 2 ]) cores.x <- toupper(paste(site,tree,series,sep="",collapse=NULL)) return( cores.x ) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(gremes) data("SeineData", package = "gremes") head(Seine) seg<- graph(c(1,2, 2,3, 2,4, 4,5, 5,6, 5,7), directed = FALSE) name_stat<- c("Paris", "2", "Meaux", "Melun", "5", "Nemours", "Sens") seg<- set.vertex.attribute(seg, "name", V(seg), name_stat) tobj<- Tree(seg, Seine) Uc<- getNoDataNodes(tobj) Uc<- c("2", "5") tup<- Tuples() x<- rep(1,5) names(x)<- getNodesWithData(tobj) tup<- evalPoints(tup, tobj, x) eks<- EKS(seg) eks<-estimate(eks, Seine, tup, k_ratio=0.2) subs<- Neighborhood() subs<- subset(subs, 2, seg, Uc) eks_part<- EKS_part(seg) eks_part<- suppressMessages(estimate(eks_part, Seine, subs, k_ratio=0.2, xx=x)) eks$depParams eks_part$depParams
library("perryExamples") data("coleman") set.seed(1234) folds <- cvFolds(nrow(coleman), K = 5, R = 10) fit50 <- ltsReg(Y ~ ., data = coleman, alpha = 0.5) cv50 <- perry(fit50, splits = folds, fit = "both", cost = rtmspe, trim = 0.25) fit75 <- ltsReg(Y ~ ., data = coleman, alpha = 0.75) cv75 <- perry(fit75, splits = folds, fit = "both", cost = rtmspe, trim = 0.25) cv <- perrySelect("0.5" = cv50, "0.75" = cv75) cv reperry(cv50, cost = rtmspe, trim = 0.1) reperry(cv, cost = rtmspe, trim = 0.1)
is.inCH <- function(p, M, verbose=FALSE, ...) { verbose <- max(0, min(verbose, 4)) if(is.null(dim(p))) p <- rbind(p) if (!is.matrix(M)) stop("Second argument must be a matrix.") if ((d <- ncol(p)) != ncol(M)) stop("Number of columns in matrix (2nd argument) is not equal to dimension ", "of first argument.") if((n <- nrow(M)) == 1L){ for(i in seq_len(nrow(p))){ if(!isTRUE(all.equal(p[i,], M, check.attributes = FALSE))) return(FALSE) } return(TRUE) } timeout <- 1 setup.lp <- function(){ L <- cbind(1, M) lprec <- make.lp(n, d+1) for(k in seq_len(d+1)) set.column(lprec, k, L[,k]) set.constr.type(lprec, rep.int(2L, n)) set.rhs(lprec, numeric(n)) set.bounds(lprec, lower = rep.int(-1, d+1L), upper = rep.int(1, d+1L)) lp.control(lprec, break.at.value = -.Machine$double.eps, verbose=c("important","important","important","normal","detailed")[min(max(verbose+1,0),5)], timeout=timeout) lprec } lprec <- setup.lp() for(i in seq_len(nrow(p))){ flag <- -1 while(flag%in%c(-1,1,7)){ set.objfn(lprec, c(1, p[i,])) flag <- solve(lprec) if(flag%in%c(1,7)){ timeout <- timeout * 2 z <- rnorm(1) p <- p + z M <- M + z lprec <- setup.lp() } } if(get.objective(lprec) < 0){ if(verbose > 1) message(sprintf("is.inCH: iter = %d, outside hull.",i)) return(FALSE) }else if(verbose > 2 && nrow(p) > 1) message(sprintf("is.inCH: iter = %d, inside hull.", i)) } if(verbose > 1) message("is.inCH: all test points inside hull.") return(TRUE) }
GoralczykEtAl2011 <- data.frame("publication"=c("Fasola (2005)", "Innocenti (2003)", "Lu (2006)", "Neuhaus (2002)", "Schmeding (2007)", "Calmus (2010)", "Heffron (2001)", "Lin (2005)", "Neuberger (2009)", "Yan (2004)", "Yoshida (2005)", "Boillot (2005)", "de Simone (2007)", "Humar (2007)", "Kato, cohort 1 (2007)", "Kato, cohort 2 (2007)", "Klintmalm (2007)", "Lupo (2008)", "Washburn (2001)"), "year"=c(2005, 2003, 2006, 2002, 2007, 2010, 2001, 2005, 2009, 2004, 2005, 2005, 2007, 2007, 2007, 2007, 2007, 2008, 2001), "randomized"=factor(c("yes","no","n.s.")[c(1,2,3,1,1,1,3,2,1,1,1,1,1,2,1,1,1,1,1)], levels=c("yes","no","n.s.")), "control.type"=factor(c("concurrent","historical")[c(1,1,1,1,1, 1,1,1,1,1, 1,1,1,2,1, 1,1,1,1)], levels=c("concurrent","historical")), "comparison"=factor(c("IL-2RA only","delayed CNI","no/low steroids")[c(1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3,3)], levels=c("IL-2RA only","delayed CNI","no/low steroids")), "IL2RA"=factor(c("basiliximab","daclizumab")[c(2,2,2,1,1,2,2,1,2,1,2,2,1,1,2,2,2,1,2)]), "CNI"=factor(c("cyclosporine A","tacrolimus")[c(2,1,2,1,2,2,2,2,2,1,2,2,1,2,2,2,2,1,2)]), "MMF"=factor(c("yes","no")[c(1,1,1,2,2,1,1,1,1,1,1,2,1,1,2,1,1,2,1)], levels=c("yes","no")), "followup"=c(12,NA,6,12,NA,24,12,6,12,3,12,3,12,16,12,12,12,22,18), "exp.AR.events"=c(13,7,3,74,29,23,14,3,28,3,17,89,17,9,7,3,80,4,1), "exp.SRR.events"=c(NA,NA,NA,34,6,1,NA,NA,NA,0,NA,10,NA,0,NA,NA,NA,NA,NA), "exp.deaths"=c(4,0,3,25,4,9,4,0,11,NA,10,25,7,10,NA,NA,11,4,0), "exp.total"=c(46,24,40,188,51,98,54,27,168,24,72,351,95,83,15,16,153,26,15), "cont.AR.events"=c(11,4,3,88,25,24,23,5,45,9,21,92,21,10,9,8,46,6,1), "cont.SRR.events"=c(NA,NA,NA,51,3,3,NA,NA,NA,1,NA,22,NA,0,NA,NA,NA,NA,NA), "cont.deaths"=c(2,1,2,31,3,6,4,0,19,NA,5,20,8,16,NA,NA,8,8,1), "cont.total"=c(24,10,27,193,48,101,47,18,168,24,76,347,95,83,16,23,79,21,15), stringsAsFactors=FALSE)[c(7,19,4,2,10,12,1,8,11,3,13,14,15,16,17,5,18,9,6),] rownames(GoralczykEtAl2011) <- as.character(1:19)
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(bayesrules) example_data <- data.frame(x = sample(1:100, 20)) example_data$y <- example_data$x*3 + rnorm(20, 0, 5) example_model <- rstanarm::stan_glm(y ~ x, data = example_data, refresh = FALSE) prediction_summary(example_model, example_data, prob_inner = 0.6, prob_outer = 0.80, stable = TRUE) prediction_summary_cv(model = example_model, data = example_data, k = 2, prob_inner = 0.6, prob_outer = 0.80) x <- rnorm(20) z <- 3*x prob <- 1/(1+exp(-z)) y <- rbinom(20, 1, prob) example_data <- data.frame(x = x, y = y) example_model <- rstanarm::stan_glm(y ~ x, data = example_data, family = binomial, refresh = FALSE) classification_summary(model = example_model, data = example_data, cutoff = 0.5) classification_summary_cv(model = example_model, data = example_data, k = 2, cutoff = 0.5) data(penguins_bayes, package = "bayesrules") example_model <- e1071::naiveBayes(species ~ bill_length_mm, data = penguins_bayes) naive_classification_summary(model = example_model, data = penguins_bayes, y = "species") naive_classification_summary_cv(model = example_model, data = penguins_bayes, y = "species", k = 2)
wce <- function(x) { check_if_solver_is_available() validate_data_matrix(x) if (!is_distance_matrix(x)) { stop("The input via argument `weights` is not a similarity matrix, ", "the upper and lower triangulars of your matrix differ.") } x <- as.matrix(x) ilp <- anticlustering_ilp(x, K = 0, FALSE) solution <- solve_ilp(ilp, "max") ilp_to_groups(solution, nrow(x)) }
context("GSEA analysis") test_that("fgseaSimple works", { data(examplePathways) data(exampleRanks) set.seed(42) nperm <- 100 fgseaRes <- fgseaSimple(examplePathways, exampleRanks, nperm=nperm, maxSize=500) expect_equal(fgseaRes[23, ES], 0.5788464) expect_equal(fgseaRes[23, nMoreExtreme], 0) expect_gt(fgseaRes[1237, nMoreExtreme], 50 * nperm / 1000) expect_true("70385" %in% fgseaRes[grep("5991851", pathway), leadingEdge][[1]]) expect_true(!"68549" %in% fgseaRes[grep("5991851", pathway), leadingEdge][[1]]) expect_true(!"11909" %in% fgseaRes[grep("5992314", pathway), leadingEdge][[1]]) expect_true("69386" %in% fgseaRes[grep("5992314", pathway), leadingEdge][[1]]) fgsea1Res <- fgseaSimple(examplePathways[1237], exampleRanks, nperm=nperm, maxSize=500) expect_gt(fgseaRes[1, nMoreExtreme], 50 * nperm / 1000) fgseaRes <- fgseaSimple(examplePathways, exampleRanks, nperm=2000, maxSize=100, nproc=2) expect_false(all(fgseaRes$nMoreExtreme %% 2 == 0)) }) test_that("fgseaSimple is reproducable independent of bpparam settings", { data(examplePathways) data(exampleRanks) nperm <- 2000 set.seed(42) fr <- fgseaSimple(examplePathways[1:2], exampleRanks, nperm=nperm, maxSize=500, nproc=1) set.seed(42) fr1 <- fgseaSimple(examplePathways[1:2], exampleRanks, nperm=nperm, maxSize=500) expect_equal(fr1$nMoreExtreme, fr$nMoreExtreme) set.seed(42) fr2 <- fgseaSimple(examplePathways[1:2], exampleRanks, nperm=nperm, maxSize=500, nproc=0) expect_equal(fr2$nMoreExtreme, fr$nMoreExtreme) set.seed(42) fr3 <- fgseaSimple(examplePathways[1:2], exampleRanks, nperm=nperm, maxSize=500, nproc=2) expect_equal(fr3$nMoreExtreme, fr$nMoreExtreme) }) test_that("fgseaSimple works with zero pathways", { data(examplePathways) data(exampleRanks) set.seed(42) nperm <- 100 fgseaRes <- fgseaSimple(examplePathways, exampleRanks, nperm=nperm, minSize=50, maxSize=10) expect_equal(nrow(fgseaRes), 0) fgseaRes1 <- fgseaSimple(examplePathways[1], exampleRanks, nperm=nperm) expect_equal(colnames(fgseaRes), colnames(fgseaRes1)) }) test_that("fgseaLabel works", { mat <- matrix(rnorm(1000*20),1000,20) labels <- rep(1:2, c(10, 10)) rownames(mat) <- as.character(seq_len(nrow(mat))) pathways <- list(sample(rownames(mat), 100), sample(rownames(mat), 200)) fgseaRes <- fgseaLabel(pathways, mat, labels, nperm = 1000, minSize = 15, maxSize = 500) expect_true(!is.null(fgseaRes)) }) test_that("fgseaLabel example works", { skip_on_bioc() helpFile <- system.file("../man/fgseaLabel.Rd", package="fgsea") if (helpFile == "") { example("fgseaLabel", run.donttest = TRUE, local = FALSE) } else { tcon <- textConnection("exampleCode", open="w", local=TRUE) tools::Rd2ex(helpFile, out=tcon) close(tcon) econ <- textConnection(exampleCode, open="r") source(econ) } expect_true(!is.null(fgseaRes)) }) test_that("Ties detection in ranking works", { data(examplePathways) data(exampleRanks) exampleRanks.ties <- exampleRanks exampleRanks.ties[41] <- exampleRanks.ties[42] exampleRanks.ties.zero <- exampleRanks.ties exampleRanks.ties.zero[41] <- exampleRanks.ties.zero[42] <- 0 expect_silent(fgseaSimple(examplePathways, exampleRanks, nperm=100, minSize=10, maxSize=50, nproc=1)) expect_warning(fgseaSimple(examplePathways, exampleRanks.ties, nperm=100, minSize=10, maxSize=50, nproc=1)) expect_silent(fgseaSimple(examplePathways, exampleRanks.ties.zero, nperm=100, minSize=10, maxSize=50, nproc=1)) }) test_that("fgseaSimple throws a warning when there are duplicate gene names", { data(examplePathways) data(exampleRanks) exampleRanks.dupNames <- exampleRanks names(exampleRanks.dupNames)[41] <- names(exampleRanks.dupNames)[42] expect_warning(fgseaSimple(examplePathways, exampleRanks.dupNames, nperm=100, minSize=10, maxSize=50, nproc=1)) }) test_that("fgseaSimple returns leading edge ordered by decreasing of absolute statistic value", { data(examplePathways) data(exampleRanks) set.seed(42) nperm <- 100 fgseaRes <- fgseaSimple(examplePathways, exampleRanks, nperm=nperm, maxSize=50) expect_true(abs(exampleRanks[fgseaRes$leadingEdge[[1]][1]]) > abs(exampleRanks[fgseaRes$leadingEdge[[1]][2]])) expect_true(abs(exampleRanks[fgseaRes$leadingEdge[[2]][1]]) > abs(exampleRanks[fgseaRes$leadingEdge[[2]][2]])) }) test_that("collapsePathways work", { data(examplePathways) data(exampleRanks) set.seed(42) nperm <- 100 pathways <- list(p1=examplePathways$`5991851_Mitotic_Prometaphase`) pathways <- c(pathways, list(p2=unique(c(pathways$p1, sample(names(exampleRanks), 20))))) pathways <- c(pathways, list(p3=sample(pathways$p1, floor(length(pathways$p1) * 0.8)))) fgseaRes <- fgseaSimple(pathways, exampleRanks, nperm=nperm, maxSize=500) collapsedPathways <- collapsePathways(fgseaRes[order(pval)], pathways, exampleRanks) collapsedPathways$mainPathways expect_identical("p1", collapsedPathways$mainPathways) }) test_that("fgseaSimple throws a warning when there are unbalanced gene-level statistic values", { data(exampleRanks) data(examplePathways) ranks <- sort(exampleRanks, decreasing = TRUE) firstNegative <- which(ranks < 0)[1] ranks <- c(abs(ranks[1:(firstNegative - 1)]) ^ 0.1, ranks[firstNegative:length(ranks)]) pathway <- list(testPathway = names(ranks)[1:100]) set.seed(1) expect_warning(fgseaSimple(pathway, ranks, nperm = 200, minSize = 15, maxSize = 500)) }) test_that("fgseaSimple and fgseaMultilevel properly handle duplicated in gene sets", { data(exampleRanks) data(examplePathways) pathways <- list(p1=examplePathways$`5991851_Mitotic_Prometaphase`, p2=rep(examplePathways$`5991851_Mitotic_Prometaphase`, 2)) set.seed(42) fr1 <- fgseaSimple(pathways, exampleRanks, nperm=1000) expect_equal(fr1$size[1], fr1$size[2]) fr2 <- suppressWarnings(fgseaMultilevel(pathways, exampleRanks, eps = 1e-4)) expect_equal(fr2$size[1], fr2$size[2]) }) test_that("fgsea works correctly if gene sets have signed ES = 0 and scoreType != std", { data("exampleRanks") stats <- exampleRanks stats <- sort(stats, decreasing=TRUE) gsInTail <- list("gsInTail" = names(stats)[(length(stats) - 14) : length(stats)]) set.seed(1) expect_silent(fr <- fgseaSimple(gsInTail, stats, nperm = 1000, scoreType = "pos")) gsInHead <- list("gsInHead" = names(stats)[1:15]) set.seed(1) expect_silent(fr <- fgseaSimple(gsInHead, stats, nperm = 1000, scoreType = "neg")) })
library(hansard) context("all_answered_questions part2") test_that("all_answered_questions return expected format", { skip_on_cran() skip_on_travis() anameid <- hansard_all_answered_questions( house = "lords", answering_body = 60, start_date = "2017-03-01", end_date = "2017-03-20", verbose = TRUE ) expect_length(anameid, 31) expect_type(anameid, "list") expect_true(tibble::is_tibble(anameid)) expect_equal(nrow(anameid), 38) bidname <- hansard_all_answered_questions( house = 2, answering_body = "Education", start_date = "2017-03-01", end_date = "2017-03-20", verbose = TRUE ) expect_length(bidname, 31) expect_type(bidname, "list") expect_true(tibble::is_tibble(bidname)) expect_equal(nrow(bidname), 38) expect_true(names(bidname[1]) == names(anameid[1])) expect_equivalent(names(bidname), names(anameid)) expect_equal(nrow(bidname), nrow(anameid)) })
context("test-dynardl-auto") test_that("Stop for non-dynardl objects", { y <- rnorm(500) expect_error(dynardl.auto.correlated(y), "provide a dynardl model object") }) test_that("Correct fit statistics reported", { dyn.out.1.1 <- dynardl(concern ~ incshare10 + urate, data = ineq, lags = list("concern" = 1, "incshare10" = 1, "urate" = 1), ec = TRUE, simulate = FALSE) expect_output(dynardl.auto.correlated(dyn.out.1.1), paste(round(AIC(dyn.out.1.1$model), 3))) expect_output(dynardl.auto.correlated(dyn.out.1.1), paste(round(BIC(dyn.out.1.1$model), 3))) expect_output(dynardl.auto.correlated(dyn.out.1.1, digits = 5), paste(round(AIC(dyn.out.1.1$model), 5))) expect_output(dynardl.auto.correlated(dyn.out.1.1, digits = 5), paste(round(BIC(dyn.out.1.1$model), 5))) }) test_that("Correct bgtest reported", { dyn.out.1.1 <- dynardl(concern ~ incshare10 + urate, data = ineq, lags = list("concern" = 1, "incshare10" = 1, "urate" = 1), ec = TRUE, simulate = FALSE) expect_output(dynardl.auto.correlated(dyn.out.1.1, digits = 3), paste(round(bgtest(dyn.out.1.1$model)$statistic, 3))) expect_output(dynardl.auto.correlated(dyn.out.1.1, digits = 3, order = 5), paste(round(bgtest(dyn.out.1.1$model, order = 5)$statistic, 3))) expect_output(dynardl.auto.correlated(dyn.out.1.1, digits = 3, bg.type = "F"), paste(round(bgtest(dyn.out.1.1$model, type = "F")$statistic, 3))) }) test_that("Correct shapiro test reported", { dyn.out.1.1 <- dynardl(concern ~ incshare10 + urate, data = ineq, lags = list("concern" = 1, "incshare10" = 1, "urate" = 1), ec = TRUE, simulate = FALSE) expect_output(dynardl.auto.correlated(dyn.out.1.1, digits = 3), paste(round(shapiro.test(dyn.out.1.1$model$residuals)$statistic, 3))) }) test_that("Information out correctly", { dyn.out.1.2 <- dynardl(concern ~ incshare10 + urate, data = ineq, lags = list("concern" = 1, "incshare10" = 1, "urate" = 1), ec = TRUE, simulate = FALSE) info <- dynardl.auto.correlated(dyn.out.1.2, object.out = TRUE) expect_equal(names(info), c("bg", "sw", "AIC", "BIC", "logLik")) }) test_that("Does clear autocorrelation fail the test?", { dyn.out.1.3 <- dynardl(urate ~ concern, data = ineq, lags = list("urate" = 1), ec = FALSE, simulate = FALSE) expect_output(dynardl.auto.correlated(dyn.out.1.3), "Breusch-Godfrey test indicates we reject the null hypothesis") expect_output(dynardl.auto.correlated(dyn.out.1.3), "Shapiro-Wilk test indicates we reject the null hypothesis") })
make_tile_mosaic <- function(aoi, data_folder, dataset, filename="", stack="change", ...) { if (stack == 'change') { image_names <- c('treecover2000', 'lossyear', 'gain', 'datamask') band_names <- image_names } else if (stack == 'first') { image_names <- 'first' band_names <- c('Band3', 'Band4', 'Band5', 'Band7') } else if (stack == 'last') { image_names <- 'last' band_names <- c('Band3', 'Band4', 'Band5', 'Band7') } else { stop('"stack" must be equal to "change", "first", or "last"') } aoi <- check_aoi(aoi) tiles <- calc_gfc_tiles(aoi) aoi <- spTransform(aoi, CRS(proj4string(tiles))) file_root <- paste0('Hansen_', dataset, '_') tile_stacks <- c() for (n in 1:length(tiles)) { tile <- tiles[n] min_x <- bbox(tile)[1, 1] max_y <- bbox(tile)[2, 2] if (min_x < 0) { min_x <- paste0(sprintf('%03i', abs(min_x)), 'W') } else { min_x <- paste0(sprintf('%03i', min_x), 'E') } if (max_y < 0) { max_y <- paste0(sprintf('%02i', abs(max_y)), 'S') } else { max_y <- paste0(sprintf('%02i', max_y), 'N') } file_suffix <- paste0('_', max_y, '_', min_x, '.tif') filenames <- file.path(data_folder, paste0(file_root, image_names, file_suffix)) tile_stack <- crop(stack(filenames), aoi, datatype='INT1U', format='GTiff', options="COMPRESS=LZW") names(tile_stack) <- band_names tile_stacks <- c(tile_stacks, list(tile_stack)) } if (length(tile_stacks) > 1) { mosaic_list <- function(x, fun, datatype, format, options, overwrite, tolerance=0.05, filename="") { mosaic_args <- x if (!missing(fun)) mosaic_args$fun <- fun if (!missing(tolerance)) mosaic_args$tolerance <- tolerance if (!missing(datatype)) mosaic_args$datatype <- datatype if (!missing(format)) mosaic_args$format <- format if (!missing(options)) mosaic_args$options <- options if (!missing(overwrite)) mosaic_args$overwrite <- overwrite mosaic_args$filename <- filename do.call(mosaic, mosaic_args) } tile_mosaic <- mosaic_list(tile_stacks, fun='mean', filename=filename, datatype='INT1U', format='GTiff', options='COMPRESS=LZW', ...) } else { tile_mosaic <- tile_stacks[[1]] if (filename != '') { tile_mosaic <- writeRaster(tile_mosaic, filename=filename, datatype="INT1U", format="GTiff", options="COMPRESS=LZW", ...) } } names(tile_mosaic) <- band_names NAvalue(tile_mosaic) <- -1 return(tile_mosaic) } scale_toar <- function(x, ...) { if (!nlayers(x) == 4) { stop('input image should have 4 bands') } scale_func <- function(b3, b4, b5, b7) { b3 <- (b3 - 1) / 508 b4 <- (b4 - 1) / 254 b5 <- (b5 - 1) / 363 b7 <- (b7 - 1) / 423 return(cbind(b3, b4, b5, b7)) } x <- overlay(x, fun=scale_func, datatype='FLT4S', format='GTiff', options="COMPRESS=LZW", ...) return(x) } extract_gfc <- function(aoi, data_folder, to_UTM=FALSE, stack="change", dataset='GFC-2019-v1.7', ...) { if (stack == 'change') { band_names <- c('treecover2000', 'lossyear', 'gain', 'datamask') } else if (stack == 'first') { band_names <- c('Band3', 'Band4', 'Band5', 'Band7') } else if (stack == 'last') { band_names <- c('Band3', 'Band4', 'Band5', 'Band7') } else { stop('"stack" must be equal to "change", "first", or "last"') } if (to_UTM) { tile_mosaic <- make_tile_mosaic(aoi, data_folder, stack=stack, dataset=dataset, ...) bounding_poly <- as(extent(tile_mosaic), "SpatialPolygons") proj4string(bounding_poly) <- proj4string(tile_mosaic) utm_proj4string <- utm_zone(bounding_poly, proj4string=TRUE) band_name <- names(tile_mosaic) tile_mosaic <- projectRaster(tile_mosaic, crs=utm_proj4string, method='ngb', datatype='INT1U', format='GTiff', options="COMPRESS=LZW", ...) names(tile_mosaic) <- band_names NAvalue(tile_mosaic) <- -1 } else { tile_mosaic <- make_tile_mosaic(aoi, data_folder, stack=stack, dataset=dataset, ...) NAvalue(tile_mosaic) <- -1 } return(tile_mosaic) }
geodesic_pos<-function(P1,P2,p=2,steps){ P1type<-type_check(P1) P2type<-type_check(P2) P1<-process_data(P1,P1type,return_type="wpp") P2<-process_data(P2,P2type,return_type="wpp") plan<-transport::transport(P1,P2,p) L<-length(plan$from) d<-P1$dimension start<-matrix(0,L,d) V<-matrix(0,L,d) W<-rep(0,L) for (k in 1:L){ f<-plan$from[k] t<-plan$to[k] start[k,]<-P1$coordinates[f,] V[k,]<-P2$coordinates[t,]-P1$coordinates[f,] W[k]<-plan$mass[k] } N<-length(steps) out.list<-vector("list",N) for (i in 1:N){ out.list[[i]]<-transport::wpp(start+(V*steps[i]),W) } return(out.list) }
qregression <- function(bws, xeval, tau, quantile, quanterr = NA, quantgrad = NA, ntrain, trainiseval = FALSE, gradients = FALSE){ if (missing(bws) | missing(xeval) | missing(tau) | missing(quantile) | missing(ntrain)) stop("improper invocation of qregression constructor") d <- list( xbw = bws$xbw, ybw = bws$ybw, bws = bws, xnames = bws$xnames, ynames = bws$ynames, nobs = nrow(xeval), xndim = bws$xndim, yndim = bws$yndim, xnord = bws$xnord, xnuno = bws$xnuno, xncon = bws$xncon, ynord = bws$ynord, ynuno = bws$ynuno, yncon = bws$yncon, pscaling = bws$pscaling, ptype = bws$ptype, pcxkertype = bws$pcxkertype, puxkertype = bws$puxkertype, poxkertype = bws$poxkertype, pcykertype = bws$pcykertype, puykertype = bws$puykertype, poykertype = bws$poykertype, xeval = xeval, tau = tau, quantile = quantile, quanterr = quanterr, quantgrad = quantgrad, ntrain = ntrain, trainiseval = trainiseval, gradients = gradients) class(d) <- "qregression" return(d) } print.qregression <- function(x, digits=NULL, ...){ cat("\nQuantile regression data: ", x$ntrain, " training points,", ifelse(x$trainiseval, "", paste(" and ", x$nobs, " evaluation points,\n", sep="")), " in ", x$xndim + x$yndim, " variable(s)", "\n(", x$yndim, " dependent variable(s), and ", x$xndim, " explanatory variable(s))\n\n", sep="") print(matrix(x$ybw,ncol=x$yndim,dimnames=list(paste("Dep. Var. ",x$pscaling,":",sep=""),x$ynames))) print(matrix(x$xbw,ncol=x$xndim,dimnames=list(paste("Exp. Var. ",x$pscaling,":",sep=""),x$xnames))) cat(genRegEstStr(x)) cat(genBwKerStrs(x$bws)) cat("\n\n") if(!missing(...)) print(...,digits=digits) invisible(x) } fitted.qregression <- function(object, ...){ object$quantile } quantile.qregression <- function(x, ...){ x$quantile } plot.qregression <- function(x, ...) { npplot(bws = x$bws, ...) } predict.qregression <- function(object, se.fit = FALSE, ...) { tr <- eval(npqreg(bws = object$bws, ...), envir = parent.frame()) if(se.fit) return(list(fit = fitted(tr), se.fit = se(tr), df = tr$nobs, residual.scale = NA)) else return(fitted(tr)) } se.qregression <- function(x) { x$quanterr } gradients.qregression <- function(x, errors = FALSE, ...) { if(!errors) return(x$quantgrad) else return(NULL) } summary.qregression <- function(object, ...) { cat("\nQuantile Regression Data: ", object$ntrain, " training points,", ifelse(object$trainiseval, "", paste(" and ", object$nobs, " evaluation points,\n", sep="")), " in ", object$xndim + object$yndim, " variable(s)", "\n(", object$yndim, " dependent variable(s), and ", object$xndim, " explanatory variable(s))\n\n", sep="") cat(genOmitStr(object)) print(matrix(object$ybw,ncol=object$yndim,dimnames=list(paste("Dep. Var. ",object$pscaling,":",sep=""),object$ynames))) print(matrix(object$xbw,ncol=object$xndim,dimnames=list(paste("Exp. Var. ",object$pscaling,":",sep=""),object$xnames))) cat(genRegEstStr(object)) cat(genBwKerStrs(object$bws)) cat("\n\n") }
SnowMap <- function(xlim=c(3,20), ylim=c(3,20), axis.labels=FALSE, main="Snow's Cholera Map of London", scale=TRUE, polygons=FALSE, density=FALSE, streets.args=list(col="grey", lwd=1), deaths.args=list(col="red", pch=15, cex=0.6), pumps.args=list(col="blue", pch=17, cex=1.5, cex.lab=0.9), scale.args=list(xs=3.5, ys=19.7), polygons.args=list(col=NA, border="brown", lwd=2, lty=1), density.args=list(bandwidth=c(0.5,0.5), col1=rgb(0,1,0,0), col2=rgb(1,0,0,.8)) ) { Splot(xlim=xlim, ylim=ylim, axis.labels=axis.labels, main=main) do.call("Sstreets", streets.args) if (density) do.call("Sdensity", density.args) do.call("Sdeaths", deaths.args) do.call("Spumps", pumps.args) if (scale) do.call("Sscale", scale.args) if (polygons) do.call("Spolygons", polygons.args) } Splot <- function(xlim=c(3,20), ylim=c(3,20), xlab="", ylab="", axis.labels=FALSE, main="Snow's Cholera Map of London") { Snow.deaths <- NULL data(Snow.deaths, package = 'HistData', envir = environment()) plot(Snow.deaths[,c("x","y")], type="n", asp=1, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, xaxt = if (axis.labels) "s" else "n", yaxt = if (axis.labels) "s" else "n", main=main) } Sdeaths <- function(col="red", pch=15, cex=0.6) { Snow.deaths <- NULL data(Snow.deaths, package = 'HistData', envir = environment()) points(Snow.deaths[,c("x","y")], col=col, pch=pch, cex=cex) } Spumps <- function(col="blue", pch=17, cex=1.5, cex.lab=0.9) { Snow.pumps <- NULL data(Snow.pumps, package = 'HistData', envir = environment()) points(Snow.pumps[,c("x","y")], col=col, pch=pch, cex=cex) text(Snow.pumps[,c("x","y")], labels=Snow.pumps$label, pos=1, cex=cex.lab) } Sstreets <- function(col="gray", lwd=1) { Snow.streets <- NULL data(Snow.streets, package = 'HistData', envir = environment()) slist <- split(Snow.streets[,c("x","y")],as.factor(Snow.streets[,"street"])) invisible(lapply(slist, lines, col=col, lwd=lwd)) } Sscale <- function(xs=3.5, ys=19.7) { scale <- matrix(c(0,0, 4,0, NA, NA), nrow=3, ncol=2, byrow=TRUE) colnames(scale)<- c("x","y") scale <- rbind(scale, expand.grid(y=c(-.1, .1, NA), x=0:4)[,2:1]) lines(xs+scale[,1], ys+scale[,2]) stext <- matrix(c(0,0, 2,0, 4,0, 4, 0.1), nrow=4, ncol=2, byrow=TRUE) text(xs+stext[,1], ys+stext[,2], labels=c("0", "2", "4", "100 m."), pos=c(1,1,1,4), cex=0.8) } Spolygons <- function(col=NA, border="brown", lwd=2, lty=1) { polygons <- HistData::Snow.polygons np <- length(polygons) if (length(col) < np) col <- rep(col, length.out=np) if (length(border) < np) border <- rep(border, length.out=np) for(i in seq_along(polygons)) { coord <- polygons[[i]] polygon(coord$x, coord$y, col=col[i], border=border[i], lwd=lwd, lty=lty) } } Sdensity <- function(bandwidth=c(0.5,0.5), col1=rgb(0,1,0,0), col2=rgb(1,0,0,.8) ) { Snow.deaths <- NULL data(Snow.deaths, package = 'HistData', envir = environment()) kde2d <- KernSmooth::bkde2D(Snow.deaths[,2:3], bandwidth=bandwidth) clrs <- grDevices::colorRampPalette(c(col1, col2), alpha = TRUE)(20) graphics::contour(x=kde2d$x1, y=kde2d$x2,z=kde2d$fhat, add=TRUE) graphics::image(x=kde2d$x1, y=kde2d$x2,z=kde2d$fhat, add=TRUE, col=clrs) } TESTME <- FALSE if (TESTME) { library(HistData) SnowMap() SnowMap(axis.labels=TRUE) SnowMap(deaths.args=list(col="darkgreen")) SnowMap(polygons=TRUE, main="Snow's Cholera Map with Pump Polygons") SnowMap(density=TRUE) op <- par(mar=c(1,1,3,1)+.1) SnowMap(xlim=c(7.5,16.5), ylim=c(7,16), polygons=TRUE, main="Snow's Cholera Map, Enhanced") Sdensity() Spumps() par(op) obj <- c("SnowMap", "Splot", "Sdeaths", "Spumps", "Sstreets", "Sscale", "Spolygons", "Sdensity") SoDA::promptAll(obj) }
"typical_data"
NULL get_zillow_web_service_id <- function() { getOption('ZillowR-zws_id') } set_zillow_web_service_id <- function(x) { validate_arg(x, required = TRUE, class = 'character', length_min = 1, length_max = 1) options('ZillowR-zws_id' = x) return(invisible()) }
select_last_edges_created <- function(graph) { time_function_start <- Sys.time() fcn_name <- get_calling_fcn() if (graph_object_valid(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph object is not valid") } if (graph_contains_edges(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph contains no edges") } graph_transform_steps <- graph$graph_log %>% dplyr::mutate(step_created_edges = dplyr::if_else( function_used %in% edge_creation_functions(), 1, 0)) %>% dplyr::mutate(step_deleted_edges = dplyr::if_else( function_used %in% edge_deletion_functions(), 1, 0)) %>% dplyr::mutate(step_init_with_edges = dplyr::if_else( function_used %in% graph_init_functions() & edges > 0, 1, 0)) %>% dplyr::filter( step_created_edges == 1 | step_deleted_edges == 1 | step_init_with_edges) %>% dplyr::select(-version_id, -time_modified, -duration) if (nrow(graph_transform_steps) > 0) { if (graph_transform_steps %>% utils::tail(1) %>% dplyr::pull(step_deleted_edges) == 1) { emit_error( fcn_name = fcn_name, reasons = "The previous graph transformation function resulted in a removal of edges") } else { if (nrow(graph_transform_steps) > 1) { number_of_edges_created <- (graph_transform_steps %>% dplyr::select(edges) %>% utils::tail(2) %>% dplyr::pull(edges))[2] - (graph_transform_steps %>% dplyr::select(edges) %>% utils::tail(2) %>% dplyr::pull(edges))[1] } else { number_of_edges_created <- graph_transform_steps %>% dplyr::pull(edges) } } edge_id_values <- graph$edges_df %>% dplyr::select(id) %>% utils::tail(number_of_edges_created) %>% dplyr::pull(id) } else { edge_id_values <- NA } if (!any(is.na(edge_id_values))) { graph <- suppressMessages( select_edges_by_edge_id( graph = graph, edges = edge_id_values) ) graph$graph_log <- graph$graph_log[-nrow(graph$graph_log),] %>% add_action_to_log( version_id = nrow(graph$graph_log) + 1, function_used = fcn_name, time_modified = time_function_start, duration = graph_function_duration(time_function_start), nodes = nrow(graph$nodes_df), edges = nrow(graph$edges_df)) if (graph$graph_info$write_backups) { save_graph_as_rds(graph = graph) } } graph }
splitpick <- function(k, gen, k.WP, nfac.WP, show=10){ hilf <- c(k,abs(gen),k.WP,nfac.WP,show) if (!is.numeric(hilf)) stop ("All inputs to splitpick must be numeric.") if (!all(hilf == floor(hilf) & hilf > 0)) stop ("All inputs to splitpick must contain integer numbers.") minus <- which(gen<0) gen <- abs(gen) if (!k >= 3) stop ("splitpick requires k>=3.") if (!k.WP < k) stop ("splitpick requires k.WP < k.") if (!nfac.WP < 2^k.WP) stop ("nfac.WP >= 2^k.WP is not permitted.") if (!nfac.WP >= k.WP) stop ("nfac.WP < k.WP is not permitted. You must increase nfac.WP by ", k.WP - nfac.WP, " in order to support generation of ", 2^k.WP, " whole plots.") if (any(gen %in% 2^(0:(k-1)))) stop ("gen must not contain column numbers of base factors.") if (any(!gen %in% 3:(2^k-1))) stop ("Column numbers in gen must be smaller than ", 2^k,".") g <- length(gen) if (!nfac.WP < k+g) stop ("nfac.WP must be smaller than the total number of factors!") perm <- permutations(k) hilf <- digitsBase(gen,ndigits=k) ergeb <- matrix(0,nrow=nrow(perm),ncol=length(gen)) nfacs.WP <- rep(NA, nrow=nrow(perm)) for (i in 1:factorial(k)){ ergeb[i,] <- sort(as.integer(reord(hilf,perm[i,]))) nfacs.WP[i] <- sum(ergeb[i,]<2^k.WP) } pick <- which(nfacs.WP==nfac.WP-k.WP) if (length(pick)<show) show <- length(pick) if (show==0) stop("no adequate split-plot design found\n") else { gens <- ergeb[pick[1:show],,drop=FALSE] if (nfac.WP==k.WP) res.WP <- rep(Inf,show) else { if (nfac.WP > 2^(k.WP-1)) res.WP <- rep(3,show) else { hilf <- gens[,1:(nfac.WP-k.WP),drop=FALSE] res.WP <- apply(hilf,1,function(obj) min(sapply(words.all(k.WP,obj)[[2]],length))) } } reorder <- sort(res.WP,index.return=TRUE,decreasing=TRUE)$ix gen[minus] <- -gen[minus] list(orig=gen, basics=c(nruns=2^k, nWPs=2^k.WP, nfac.WP=nfac.WP, nfac.SP=k+g-nfac.WP), perms=perm[pick[1:show][reorder],,drop=FALSE], res.WP=res.WP[reorder], gen=gens[reorder,,drop=FALSE]) } }
`cophenetic.spantree` <- function(x) { n <- x$n mat <- matrix(NA, nrow=n, ncol=n) if (n < 2) return(as.dist(mat)) ind <- apply(cbind(2:n, x$kid), 1, sort) ind <- t(ind[2:1,]) mat[ind] <- x$dist d <- as.dist(mat) attr(d, "Labels") <- x$labels stepacross(d, path = "extended", toolong=0, trace=FALSE) }
ABB <- function(X, K=1) { if(missing(X)) stop("X is a required argument.") if(!is.matrix(X)) X <- as.matrix(X) J <- ncol(X) N <- nrow(X) M <- X*0 M[which(is.na(X))] <- 1 if(sum(M) == 0) stop("There are no missing values to impute.") M.sums <- colSums(M) MI <- list() for (k in 1:K) { imp <- NULL for (j in 1:J) { if(M.sums[j] > 0) { X.obs <- X[which(M[,j] == 0),j] X.star.obs <- sample(X.obs, length(X.obs), replace=TRUE) X.star.mis <- sample(X.star.obs, M.sums[j], replace=TRUE) if(length(imp) > 0) imp <- c(imp, X.star.mis) else imp <- X.star.mis} } MI[[k]] <- imp } return(MI) }
rawToCharNull <- function(raw_dat) { result <- "" if (length(raw_dat) < 3) try(result <- (rawToChar(raw_dat)), silent = T) else { result <- raw_dat runlength <- rle(result)$lengths if (length(runlength) > 2) { rel_range <- (runlength[1] + 1):(length(result) - runlength[length(runlength)]) if (result[[1]] != raw(1)) rel_range <- 1:rel_range[length(rel_range)] if (result[[length(result)]] != raw(1)) rel_range <- rel_range[1]:length(result) result[rel_range][result[rel_range] == as.raw(0x00)] <- as.raw(0x20) result <- result[result != raw(1)] } try(result <- rawToChar(result), silent = T) if ("raw" %in% class(result)) result <- "" } return(result) } rawToUnsignedInt <- function(raw_dat) { if (!("raw" %in% class(raw_dat))) stop ("This function requires raw data as input") result <- as.integer(raw_dat) return(as.integer(sum(result*(256^((length(result):1) - 1))))) } unsignedIntToRaw <- function(int_dat, length.out = 1) { if (length(int_dat) > 1) warning ("Argument 'int_dat' has more than 1 element. Only first element converted") if (int_dat < 0) warning ("Argument 'int_dat' is signed, taking absolute value") int_dat <- abs(as.integer(int_dat[[1]])) if (int_dat >= 256^length.out) { int_dat <- 256^length.out - 1 warning ("Argument 'in_dat' is out of range, proceeding with clipped value") } result <- NULL remaining <- int_dat repeat { result <- c(remaining%%256, result) remaining <- floor(remaining/256) if(remaining <= 0) break } result <- as.raw(result) if (length(result) < length.out) result <- c(raw(length.out - length(result)), result) return(result) } signedIntToRaw <- function(int_dat) { int_dat <- as.integer(int_dat) if(any(int_dat < -128)) stop("Some or all values out of range") if(any(int_dat > 127)) stop("Some or all values out of range") result <- int_dat result[result < 0] <- result[result < 0] + 256 return(as.raw(result)) } rawToSignedInt <- function(raw_dat) { if (!("raw" %in% class(raw_dat))) stop("Argument 'raw_dat' is not of class 'raw'") result <- as.integer(raw_dat) result[result > 127] <- result[result > 127] - 256 return(as.integer(result)) } .getPeriodIndex <- function(period) { return(128 - round(logb(period, 1.060199))) } periodToChar <- function(period) { oct <- as.character(octave(period)) oct[oct == "0"] <- "-" paste(note(period), oct, sep = "") } noteToPeriod <- function(note = "C-3", finetune = 0) { if (length(note) != length(finetune) && (length(note) > 1 && length(finetune) > 1)) stop("note and finetune should have the same length, or either should have length 1!") note <- toupper(as.character(note)) note[nchar(note) == 2] <- paste(substr(note[nchar(note) == 2], 1, 1), substr(note[nchar(note) == 2], 2, 2), sep = "-") finetune <- as.integer((finetune)) if (length(note) > length(finetune)) finetune <- rep(finetune, length(note)) if (length(note) < length(finetune)) note <- rep(note, length(finetune)) if (any(finetune > 7)) { warning("finetune is out of range. Value clipped") fintune[finetune > 7] <- 7 } if (any(finetune < -8)) { warning("finetune is out of range. Value clipped") fintune[finetune < -8] <- 8 } r_index <- suppressWarnings(apply(outer(ProTrackR::period_table$octave, as.numeric(substr(note, 3,3)), "==") & outer(ProTrackR::period_table$tuning, finetune, "=="), 2, which)) r_index <- unlist(lapply(as.list(r_index), function(x) ifelse(length(x) == 0, NA, x))) index <- cbind(r_index, match(substr(note, 1, 2), names(ProTrackR::period_table))) if (ncol(index) != 2) return (0) period <- ProTrackR::period_table[index] period[is.na(period)] <- 0 return(period) } noteToSampleRate <- function(note = "C-3", finetune = 0, video = c("PAL", "NTSC")) { rate <- periodToSampleRate(noteToPeriod(note, finetune), match.arg(video)) if (is.infinite(rate)) stop ("Note not in ProTracker period table.") return (rate) } periodToSampleRate <- function(period, video = c("PAL", "NTSC")) { ProTrackR::paula_clock$frequency[ProTrackR::paula_clock$video == match.arg(video)]/period } nybble <- function(raw_dat, which = c("low", "high")) { if (match.arg(which) == "low") return (loNybble(raw_dat)) if (match.arg(which) == "high") return (hiNybble(raw_dat)) } loNybble <- function(raw_dat) { if (!("raw" %in% class(raw_dat))) stop ("Only raw data is accepted as input") return(as.integer(raw_dat)%%16) } hiNybble <- function(raw_dat) { if (!("raw" %in% class(raw_dat))) stop ("Only raw data is accepted as input") return(as.integer(as.integer(raw_dat)/16)) } nybbleToSignedInt <- function(raw_dat, which = c("low", "high")) { nb <- nybble(raw_dat, which) nb[nb > 7] <- nb[nb > 7] - 16 return(nb) } signedIntToNybble <- function(int_dat, which = c("low", "high")) { int_dat <- as.integer(int_dat) if (any(int_dat < -8) || any(int_dat > 7)) stop("int_dat out of range [-8,7]!") int_dat[int_dat < 0] <- int_dat[int_dat < 0] + 16 fact <- ifelse(match.arg(which) == "low", 1, 16) return(as.raw(fact*int_dat)) } proTrackerVibrato <- function(x) { return(as.integer(255*sin(pi*(as.integer(x))/32))) } .unpackFibonacciDelta <- function(raw_data) { if (!("raw" %in% class(raw_data))) stop ("Only raw data is accepted as input") fibonacci <- c(-34, -21, -13, -8, -5, -3, -2, -1, 0, 1, 2, 3, 5, 8, 13, 21) result <- as.raw(rep(0, 2*length(raw_data) - 2)) result[1] <- raw_data[2] for (i_byte in 2:length(result)) { nybble <- ifelse((i_byte%%2) == 0, c(hiNybble), c(loNybble)) work_byte <- raw_data[1 + (i_byte/2)] result_val <- rawToSignedInt(result[i_byte - 1]) + fibonacci[1 + nybble[[1]](work_byte)] result_val <- ifelse(result_val > 127, 127, result_val) result_val <- ifelse(result_val < -128, -128, result_val) result[i_byte] <- signedIntToRaw(result_val) } return(result) }
cat("\014") rm(list = ls()) setwd("~/git/of_dollars_and_data") source(file.path(paste0(getwd(),"/header.R"))) library(scales) library(readxl) library(lubridate) library(ggrepel) library(tidylog) library(zoo) library(tidyverse) folder_name <- "0249_dca_around_the_world" out_path <- paste0(exportdir, folder_name) dir.create(file.path(paste0(out_path)), showWarnings = FALSE) period_length <- 120 raw_1970 <- read.csv(paste0(importdir, "/0249_world_returns/dfa_msci_1970.csv"), skip = 6, col.names = c("date", "US", "Spain", "UK", "Canada", "Japan", "Italy"), ) %>% filter(row_number() != 1, `US` != "") %>% mutate(date = as.Date(date, "%m/%d/%y")) df_1970 <- sapply(raw_1970[2:ncol(raw_1970)], as.numeric) %>% as.data.frame() %>% bind_cols(date = raw_1970[, "date"]) %>% select(date, everything()) raw_1999 <- read.csv(paste0(importdir, "/0249_world_returns/dfa_msci_1999.csv"), skip = 6, col.names = c("date", "China", "Greece", "Russia"), ) %>% filter(row_number() != 1, `China` != "") %>% mutate(date = as.Date(date, "%m/%d/%y")) df_1999 <- sapply(raw_1999[2:ncol(raw_1999)], as.numeric) %>% as.data.frame() %>% bind_cols(date = raw_1999[, "date"]) %>% select(date, everything()) df <- df_1970 %>% left_join(df_1999) long_df <- df %>% gather(-date, key=key, value=value) first_1970 <- long_df %>% filter(date == as.Date("1970-01-31")) %>% rename(first_value = value) %>% select(-date) %>% drop_na ew_df <- long_df %>% filter(date >= as.Date("1970-01-31")) %>% inner_join(first_1970) %>% mutate(index = value/first_value) %>% group_by(date) %>% summarize(count = n(), sum_index = sum(index), ) %>% ungroup() %>% mutate(EW = sum_index/count) %>% select(date, EW) df <- df %>% left_join(ew_df) index_cols <- colnames(df[, 2:ncol(df)]) final_results <- data.frame() counter <- 0 for(x in index_cols){ print(x) pre_filter <- df %>% select_("date", x) %>% rename_(.dots = setNames(paste0(x), "index")) %>% drop_na %>% mutate(ret = index/lag(index, 1) - 1) start_months <- pre_filter[1:(nrow(pre_filter)-period_length+1), "date"] for(s in 1:length(start_months)){ print(start_months[s]) start_month <- start_months[s] end_month <- start_month + days(1) + months(period_length-1) - days(1) tmp <- pre_filter %>% filter(date >= start_month, date <= end_month) dca_amount <- 100 for(j in 1:nrow(tmp)){ if(j == 1){ tmp[j, "cost_basis"] <- dca_amount tmp[j, "value"] <- dca_amount } else{ ret <- 1 + tmp[j, "ret"] mt <- month(tmp[j, "date"]) tmp[j, "cost_basis"] <- tmp[(j-1), "cost_basis"] + dca_amount tmp[j, "value"] <- (tmp[(j-1), "value"] * ret) + dca_amount } } tail <- tmp %>% tail(1) counter <- counter + 1 final_results[counter, "start_date"] <- start_month final_results[counter, "end_date"] <- end_month final_results[counter, "cost_basis"] <- tail$cost_basis final_results[counter, "value"] <- tail$value final_results[counter, "country"] <- x } } final_results <- final_results %>% mutate(stock_premium = value/cost_basis - 1, stock_beats_cash = ifelse(stock_premium > 0, 1, 0), stock_premium_bins = case_when( stock_premium < 0 ~ "<0%", stock_premium < 0.5~ "0%-50%", TRUE ~ ">50%" ) ) final_results$stock_premium_bins <- factor(final_results$stock_premium_bins, levels = c("<0%", "0%-50%",">50%")) final_results_no_ew <- final_results %>% filter(country != "EW") source_string <- paste0("Source: Returns 2.0") note_string <- str_wrap(paste0("Note: Assumes that DCA invests $100 a month for 10 years. Returns are shown net of dividends. ", "All country data starts in 1970, except data for China, Russia, and Greece which start in 1999."), width = 80) file_path <- paste0(out_path, "/dca_all_countries.jpeg") to_plot <- final_results_no_ew plot <- ggplot(to_plot, aes(x= start_date, y=value, col = country)) + geom_line() + scale_y_continuous(label = dollar) + geom_hline(yintercept = period_length*dca_amount, linetype = "dashed") + of_dollars_and_data_theme + theme(legend.position = "bottom", legend.title = element_blank()) + ggtitle(paste0("DCA Final Portfolio Value\nOver 10 Years\nBy Country")) + labs(x="Start Date", y="Final Portfolio Value", caption = paste0(source_string, "\n", note_string)) ggsave(file_path, plot, width = 15, height = 12, units = "cm") file_path <- paste0(out_path, "/dca_bins_all_countries.jpeg") country_bin <- final_results_no_ew %>% group_by(stock_premium_bins, country) %>% summarise(count = n()) %>% ungroup() country <- final_results_no_ew %>% group_by(country) %>% summarise(country_total = n()) %>% ungroup() to_plot <- country_bin %>% left_join(country) %>% mutate(pct = count/country_total, label = paste0(100*round(pct, 2), "%")) %>% select(country, stock_premium_bins, pct, label) plot <- ggplot(to_plot, aes(x=stock_premium_bins, y=pct, fill = country)) + geom_bar(stat = "identity") + geom_text(data=to_plot, aes(x=stock_premium_bins, y=pct + 0.05, label = label), col = "black", size = 2) + facet_wrap(~country) + scale_fill_discrete(guide = FALSE) + scale_y_continuous(label = percent_format(accuracy = 1)) + of_dollars_and_data_theme + ggtitle(paste0("DCA Return Above Cash\nOver 10 Years\nBy Country and Return Amount")) + labs(x="Final Return Above Cash", y="Percentage", caption = paste0(source_string, "\n", note_string)) ggsave(file_path, plot, width = 15, height = 12, units = "cm") print_sim_stats <- function(df){ print(paste0("Stock beats cash: ", 100*round(mean(df$stock_beats_cash), 2), "% of the time (avg)")) print(paste0("Stock beats cash by: ", 100*round(quantile(df$stock_premium, probs = 0.25), 2), "% (25th pct)")) print(paste0("Stock beats cash by: ", 100*round(quantile(df$stock_premium, probs = 0.5), 2), "% (median)")) print(paste0("Stock beats cash by: ", 100*round(quantile(df$stock_premium, probs = 0.75), 2), "% (75th pct)")) } ew_only <- final_results %>% filter(country == "EW") print_sim_stats(final_results_no_ew) print_sim_stats(ew_only)
eye <- hijack(r_sample_factor, name = "Eye", x = c("Brown", "Blue", "Green", "Hazel", "Gray"), prob = c(.44, .3, .13, .09, .04) )
dubininradanalysis <- function(Ce, Qe){ x <- Ce y <- Qe data <- data.frame(x, y) mod205 <- Qe ~ Xm*exp(-K*Ce^2) start <- data.frame(Xm = c(0, 10), K = c(0, 10)) set.seed(511) suppressWarnings(fit206<- nls2(mod205, start = start, control = nls.control(maxiter = 100, warnOnly = TRUE), algorithm = "plinear-random")) print("Dubinin-Radushkevich Isotherm") print(summary(fit206)) N <- nrow(na.omit(data)) error <- function(y){ pv <- (predict(fit206)) rmse<- (rmse(y,predict(fit206))) mae <- (mae(y,predict(fit206))) mse <- (mse(y,predict(fit206))) rae <- (rae(y,predict(fit206))) PAIC <- AIC(fit206) PBIC <- BIC(fit206) SE <-(sqrt(sum(predict(fit206)-x)^2)/(N-2)) colnames(y) <- rownames(y) <- colnames(y) list("Predicted Values" = pv, "Relative Mean Square Error" = rmse, "Mean Absolute Error" = mae, "Mean Squared Error" = mse, "Relative Absolute Error" = rae, "AIC" = PAIC, "BIC" = PBIC, "Standard Error Estimate" = SE) } e <- error(y) print(e) plot(x, y, main = "Dubinin-Radushkevich Isotherm Model", xlab = "Ce", ylab = "Qe") lines(x,predict(fit206),lty=1, col="black", lwd=1) rsqq <- lm(Qe~predict(fit206)) print(summary(rsqq)) }
check_integer <- function(x, min_len = 1, max_len = 1, min = -Inf, max = Inf, strict = FALSE) { arg <- deparse(substitute(x)) if (strict && !is.integer(x)) stop("The type of ", arg, " must be integer", call. = FALSE) fun <- function(e) stop(arg, " must be coercible to integer", call. = FALSE) tryCatch({ x <- as.integer(x) }, warning = fun, error = fun) x <- check_length(x, min_len, max_len, arg) x <- check_na(x, arg) x <- check_range(x, min, max, arg) return(x) } check_double <- function(x, min_len = 1, max_len = 1, min = -Inf, max = Inf, strict = FALSE) { arg <- deparse(substitute(x)) if (strict && !is.double(x)) stop("The type of ", arg, " must be double", call. = FALSE) fun <- function(e) stop(arg, " must be coercible to double", call. = FALSE) tryCatch({ x <- as.double(x) }, warning = fun, error = fun) x <- check_length(x, min_len, max_len, arg) x <- check_na(x, arg) x <- check_range(x, min, max, arg) return(x) } check_logical <- function(x, min_len = 1, max_len = 1, strict = FALSE) { arg <- deparse(substitute(x)) if (strict && !is.logical(x)) stop("The type of ", arg, " must be logical", call. = FALSE) fun <- function(e) stop(arg, " must be coercible to logical", call. = FALSE) tryCatch({ x <- as.logical(x) }, warning = fun, error = fun) x <- check_length(x, min_len, max_len, arg) x <- check_na(x, arg) return(x) } check_character <- function(x, min_len = 1, max_len = 1, min_nchar = 0, max_nchar = Inf, strict = FALSE) { arg <- deparse(substitute(x)) if (strict && !is.character(x)) stop("The type of ", arg, " must be character", call. = FALSE) fun <- function(e) stop(arg, " must be coercible to character", call. = FALSE) tryCatch({ x <- as.character(x) }, warning = fun, error = fun) x <- check_length(x, min_len, max_len, arg) x <- check_na(x, arg) n <- stringi::stri_length(x) if (any(n < min_nchar) || any(max_nchar < n)) { if (min_nchar == max_nchar) { stop("The value of ", arg, " must be ", max_nchar, " character\n", call. = FALSE) } else { stop("The value of ", arg, " must be between " , min_nchar, " and ", max_nchar, " character\n", call. = FALSE) } } return(x) } check_na <- function(x, arg) { if (any(is.na(x))) stop("The value of ", arg, " cannot be NA\n", call. = FALSE) return(x) } check_range <- function(x, min, max, arg) { if (any(x < min) || any(max < x)) stop("The value of ", arg, " must be between " , min, " and ", max, "\n", call. = FALSE) return(x) } check_length <- function(x, min_len, max_len, arg) { len <- length(x) if (len < min_len || max_len < len) { if (min_len == max_len) { stop("The length of ", arg, " must be ", max_len, "\n", call. = FALSE) } else { stop("The length of ", arg, " must be between " , min_len, " and ", max_len, "\n", call. = FALSE) } } return(x) } check_class <- function(class, method) { class_valid <- rownames(attr(utils::methods(method), "info")) class_valid <- stringi::stri_replace_first_fixed(class_valid, paste0(method, "."), "") class_valid <- class_valid[class_valid != "default"] if (!length(intersect(class, class_valid))) stop(method, "() only works on ", paste(class_valid, collapse = ", "), " objects.", call. = FALSE) } friendly_class_undefined_message <- check_class check_dots <- function(..., method = NULL) { arg <- setdiff(names(list(...)), "") if (!is.null(method)) { arg_used <- unlist(lapply(method, function(x) names(formals(x)))) arg <- setdiff(arg, arg_used) } if (length(arg) > 1) { warning(paste0(arg, collapse = ", "), " arguments are not used.", call. = FALSE) } else if (length(arg) == 1) { warning(arg, " argument is not used.", call. = FALSE) } } unused_dots <- check_dots
pressure <- function(x1,x2,x3,x4){ if(!is.numeric(x1) | !is.numeric(x2) | !is.numeric(x3) | !is.numeric(x4) | length(x1) != 1 | length(x2) !=1 | length(x3) != 1 | length(x4) != 1){ stop("Input is invalid.") }else if(x1 < 0 | x1 > 99 | x2 < 0 | x2 > 99 | x3 < 0 | x3 > 200 | x4 < 0 | x4 > 200){ stop("Input is outside of the domain.") }else{ ans <- .C("pressurec",x1=x1,x2=x2,x3=x3,x4=x4,fx=0,c1x=0,c2x=0,c3x=0,c4x=0) return(list(obj = ans$fx, con = c(ans$c1x,ans$c2x,ans$c3x,ans$c4x))) } }
library(shiny) library(rintrojs) ui <- fluidPage( introjsUI(), titlePanel("Tabsets"), sidebarLayout( sidebarPanel( introBox( radioButtons( "dist", "Distribution type:", c( "Normal" = "norm", "Uniform" = "unif", "Log-normal" = "lnorm", "Exponential" = "exp" ) ), data.step = 1, data.intro = "This is an input" ), br(), introBox( sliderInput( "n", "Number of observations:", value = 500, min = 1, max = 1000 ), data.step = 2, data.intro = "And so is this" ) ), mainPanel( tabsetPanel( type = "tabs", tabPanel( "Histogram", introBox( plotOutput("histogram"), data.step = 3, data.intro = "Took a look at this histogram" ) ), tabPanel( "Boxplot", introBox( plotOutput("boxplot"), data.step = 4, data.intro = "And this handsome boxplot.<br><br>See how the active tab switched from 'Histogram' to 'Boxplot' before moving to this step?" ) ), tabPanel( "Summary", tags$br(), tabsetPanel( tabPanel("Summary sub-tab 1", HTML("<br>Pretty boring tab, right?")), tabPanel( "Summary sub-tab 2", introBox( verbatimTextOutput("summary"), data.step = 5, data.intro = "There it goes again..." ) ) ) ) ) ) ) ) server <- shinyServer(function(input, output, session) { d <- reactive({ dist <- switch(input$dist, norm = rnorm, unif = runif, lnorm = rlnorm, exp = rexp, rnorm ) dist(input$n) }) output$histogram <- renderPlot({ dist <- input$dist n <- input$n hist( d(), main = paste("r", dist, "(", n, ")", sep = ""), col = " ) }) output$boxplot <- renderPlot({ dist <- input$dist n <- input$n boxplot( d(), main = paste("r", dist, "(", n, ")", sep = ""), col = " ) }) output$summary <- renderPrint({ summary(d()) }) introjs(session, events = list(onbeforechange = readCallback("switchTabs"))) }) shinyApp(ui, server)
rare_signatures <- function() { return(paste0("SBS", c(84:90, 91, 94))) }
MULTIPROCESS = R6::R6Class("MULTIPROCESS", inherit = QSys, public = list( initialize = function(addr=host("127.0.0.1"), ...) { if (! requireNamespace("callr", quietly=TRUE)) stop("The ", sQuote(callr), " package is required for ", sQuote("multiprocess")) super$initialize(addr=addr, ...) }, submit_jobs = function(n_jobs, ..., log_worker=FALSE, log_file=NULL, verbose=TRUE) { if (verbose) message("Starting ", n_jobs, " processes ...") if (log_worker && is.null(log_file)) log_file = "cmq-%i.log" for (i in seq_len(n_jobs)) { if (is.character(log_file)) log_i = suppressWarnings(sprintf(log_file, i)) else log_i = nullfile() cr = callr::r_bg(function(m) clustermq:::worker(m), args=list(m=private$master), stdout=log_i, stderr=log_i) private$callr[[as.character(cr$get_pid())]] = cr } private$workers_total = n_jobs }, cleanup = function(quiet=FALSE, timeout=3) { success = super$cleanup(quiet=quiet, timeout=timeout) dead_workers = sapply(private$callr, function(x) ! x$is_alive()) if (length(dead_workers) > 0) private$callr[dead_workers] = NULL invisible(success) }, finalize = function(quiet=FALSE) { if (!private$is_cleaned_up) { dead_workers = sapply(private$callr, function(x) ! x$is_alive()) if (length(dead_workers) > 0) private$callr[dead_workers] = NULL if (!quiet && length(private$callr) > 0) warning("Unclean shutdown for PIDs: ", paste(names(private$callr), collapse=", "), immediate.=TRUE) for (cr in private$callr) cr$kill_tree() private$is_cleaned_up = TRUE } } ), private = list( callr = list() ) )
test_partial_fn_parse <- function() { d <- data.frame(x = c(1, NA), g = c(1, 1)) expect_error( d %.>% project(., x = mean(x, na.rm = TRUE), groupby = c()) ) mean2 <- function(x) (mean(x, na.rm = TRUE)) ops <- local_td(d) %.>% project(., x = mean2(x), groupby = c()) sql <- to_sql(ops, rquery_default_db_info()) d <- data.frame(AUC = 0.6, R2 = 0.2) exprs <- list() exprs <- c(exprs, "v" %:=% "AUC + R2") exprs <- c(exprs, "x" %:=% "pmax(AUC,v)") ops <- extend_se(local_td(d), exprs) sql <- to_sql(ops, rquery_default_db_info()) invisible(NULL) } test_partial_fn_parse()
NULL tokenizer_delim <- function(delim, quote = '"', na = "NA", quoted_na = TRUE, comment = "", trim_ws = TRUE, escape_double = TRUE, escape_backslash = FALSE, skip_empty_rows = TRUE) { structure( list( delim = delim, quote = quote, na = na, quoted_na = quoted_na, comment = comment, trim_ws = trim_ws, escape_double = escape_double, escape_backslash = escape_backslash, skip_empty_rows = skip_empty_rows ), class = "tokenizer_delim" ) } tokenizer_csv <- function(na = "NA", quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip_empty_rows = TRUE) { tokenizer_delim( delim = ",", na = na, quoted_na = quoted_na, quote = quote, comment = comment, trim_ws = trim_ws, escape_double = TRUE, escape_backslash = FALSE, skip_empty_rows = skip_empty_rows ) } tokenizer_tsv <- function(na = "NA", quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip_empty_rows = TRUE) { tokenizer_delim( delim = "\t", na = na, quoted_na = quoted_na, quote = quote, comment = comment, trim_ws = trim_ws, escape_double = TRUE, escape_backslash = FALSE, skip_empty_rows = skip_empty_rows ) } tokenizer_line <- function(na = character(), skip_empty_rows = TRUE) { structure(list(na = na, skip_empty_rows = skip_empty_rows), class = "tokenizer_line" ) } tokenizer_log <- function(trim_ws) { structure(list(trim_ws = trim_ws), class = "tokenizer_log") } tokenizer_fwf <- function(begin, end, na = "NA", comment = "", trim_ws = TRUE, skip_empty_rows = TRUE) { structure(list( begin = as.integer(begin), end = as.integer(end), na = na, comment = comment, trim_ws = trim_ws, skip_empty_rows = skip_empty_rows ), class = "tokenizer_fwf" ) } tokenizer_ws <- function(na = "NA", comment = "", skip_empty_rows = TRUE) { structure(list(na = na, comment = comment, skip_empty_rows = skip_empty_rows), class = "tokenizer_ws" ) }
library(tidyverse) library(usethis) fastfood <- read_csv(here::here("data-raw/fastfood", "fastfood.csv")) fastfood <- fastfood %>% select(-X1) use_data(fastfood, overwrite = TRUE)
`quantBMAgamma0` <- function(alpha, WEIGHTS, MEAN, VAR, PROB0) { if (sum(WEIGHTS*PROB0) > alpha) return(0) lower <- 0 upper <- max(MEAN+6*sqrt(VAR)) if (cdfBMAgamma0(lower, WEIGHTS, MEAN, VAR, PROB0, 0) > alpha) return(NA) if (cdfBMAgamma0(upper, WEIGHTS, MEAN, VAR, PROB0, 0) < alpha) return(NA) z <- uniroot(cdfBMAgamma0, lower = lower, upper = upper, WEIGHTS=WEIGHTS, MEAN=MEAN, VAR=VAR, PROB0 = PROB0, offset = alpha) z$root }
set.seed(123) par(mar = c(6, 1, 0.1, 0.1), las = 2) plot(1:6, rep(1, 6), type = "n", axes = FALSE, ann = FALSE, xlim = c(0.8, 7.2), ylim = c(0, 5), panel.first = grid()) x = seq(1, 2, length = 4) symbols(x, 1:4, circles = runif(4, 0.1, 0.6), add = TRUE, bg = heat.colors(4), inches = FALSE) symbols(x + 1, 1:4, squares = runif(4, 0.1,0.6), add = TRUE, bg = terrain.colors(4), inches = FALSE) symbols(x + 2, 1:4, rect = matrix(runif(8,0.1, 0.6), 4), add = TRUE, bg = rainbow(4), inches = FALSE) symbols(x + 3, 1:4, stars = matrix(runif(20, 0.1, 0.6), 4), add = TRUE, bg = topo.colors(4), inches = FALSE) symbols(x + 4, 1:4, therm = matrix(runif(12, 0.1, 0.7), 4), add = TRUE, inches = FALSE) symbols(x + 5, 1:4, boxplot = matrix(runif(20, 0.1, 0.7), 4), add = TRUE, inches = FALSE) axis(1, 1:6, c("circles", "squares", "rectangles", "stars", "thermometers", "boxplots"), cex.axis = 0.85)
setGeneric("extender", function(object) standardGeneric("extender")) setMethod("extender", "nifti", function(object) object@"extender") setGeneric("extender<-", function(object, value) standardGeneric("extender<-")) setMethod("extender<-", signature(object="nifti"), function(object, value) { if ( "extender" %in% slotNames(object) ){ object@"extender" <- value audit.trail(object) <- niftiAuditTrailEvent(object, "modification", match.call(), paste("extender <-", value)) } else { warning("extender is not in slotNames of object") } return(object) })
censpois.mle <- function(x, tol = 1e-07) { ca <- min(x) z <- 0:ca fac <- factorial(z) n <- length(x) n2 <- sum(x == ca) n1 <- n - n2 sx <- sum( x[x > ca] ) a1 <- log( sx/n ) down <- sum( exp(a1 * z)/fac ) dera <- - n1 * exp(a1) + sx + n2 * sum( z * exp( a1 * z )/fac ) / down dera2 <- - n1 * exp(a1) + n2 * ( sum( z^2 * exp( a1 * z/fac ) ) - sum( z * exp(a1 * z)/fac )^2 ) / down^2 a2 <- a1 - dera/dera2 i <- 2 while ( abs(a2 - a1) > tol ) { i <- i + 1 down <- sum( exp(a1 * z)/fac ) a1 <- a2 dera <- - n * exp(a1) + sx + n2 * sum( z * exp( a1 * z )/fac ) / down dera2 <- - n * exp(a1) + n2 * ( sum( z^2 * exp( a1 * z/fac ) ) - sum( z * exp(a1 * z)/fac )^2 ) / down^2 a2 <- a1 - dera/dera2 } loglik <- - n * exp(a1) + sx * a1 - sum( lgamma(x + 1) ) + n2 * log( down ) list(iters = i, loglik = loglik, lambda = exp(a2) ) } censweibull.mle <- function(x, di, tol = 1e-07) { y <- log(x) y1 <- y[di == 1] y2 <- y[di == 0] n <- length(x) n1 <- length(y1) n2 <- n - n1 mod <- Rfast::weibull.mle(x[di==1]) if ( n2 > 0 ) { m <- log(mod$param[2]) es <- 1/mod$param[1] s <- log( es ) z1 <- ( y1 - m ) / es z2 <- ( y2 - m ) /es com <- sum(z1) ez1 <- exp(z1) ez2 <- exp(z2) com1 <- sum(ez1) com2 <- sum(ez2) lik1 <- com - com1 - n1 * s - com2 derm2 <- - com1 / es^2 - com2 / es^2 derm <- - n1/ es + - derm2 * es ders <- - com + sum(ez1 * z1) - n1 + sum(ez2 * z2) ders2 <- com - sum(ez1 * z1^2) - sum(ez1 * z1) - sum(ez2 * z2^2) - sum(ez2 * z2) derms <- n1/es - sum(ez1 * z1) / es - com1/es - sum(ez2 * z2) / es - com2/es anew <- c(m, s) - c(ders2 * derm - derms * ders, -derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) m <- anew[1] s <- anew[2] es <- exp(s) z1 <- ( y1 - m ) / es z2 <- ( y2 - m ) /es com <- sum(z1) ez1 <- exp(z1) ez2 <- exp(z2) com1 <- sum(ez1) com2 <- sum(ez2) lik2 <- com1 - sum(ez1) - n1 * s - com2 i <- 2 while ( abs(lik2 - lik1) > tol ) { i <- i + 1 lik1 <- lik2 derm2 <- - com1 / es^2 - com2 / es^2 derm <- - n1/ es + - derm2 * es ders <- - com + sum(ez1 * z1) - n1 + sum(ez2 * z2) ders2 <- com - sum(ez1 * z1^2) - sum(ez1 * z1) - sum(ez2 * z2^2) - sum(ez2 * z2) derms <- n1/es - sum(ez1 * z1) / es - com1/es - sum(ez2 * z2) / es - com2/es anew <- c(m, s) - c(ders2 * derm - derms * ders, -derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) m <- anew[1] s <- anew[2] es <- exp(s) z1 <- ( y1 - m ) / es z2 <- ( y2 - m ) /es com <- sum(z1) ez1 <- exp(z1) ez2 <- exp(z2) com1 <- sum(ez1) com2 <- sum(ez2) lik2 <- com - com1 - n1 * s - com2 } param <- c(exp(m), es) names(param) <- c("scale", "1/shape") mod <- list(iters = i, loglik = lik2 - sum(y1), param = param) } else mod <- mod mod } gammapois.mle <- function(x, tol = 1e-07) { n <- length(x) slx <- sum( lgamma(x + 1) ) sx <- sum(x) m <- sx/n m2 <- sum(x^2)/n p <- 1 - m/(m2 - m^2) ini.ea <- max(0, m/p - m) eb <- ini.ea/m if (eb < 1) { lik1 <- sum( lgamma(x + ini.ea) ) - n * lgamma(ini.ea) + sx * log(eb/(1 + eb)) - n *ea * log1p(eb) dera <- sum( digamma(x + ini.ea) ) * ini.ea - n * digamma(ini.ea) * ea - n * ini.ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ini.ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ini.ea) ) * ea^2 - n * trigamma(ini.ea) * ini.ea^2 derb2 <- - p * (1 - p) * sx - n * ini.ea * p * (1 - p) anew <- log(c(ini.ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 dera <- sum( digamma(x + ea) ) * ea - n * digamma(ea) * ea - n * ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ea) ) * ea^2 - n * trigamma(ea) * ea^2 derb2 <- - p * (1 - p) * sx - n * ea * p * (1 - p) anew <- log(c(ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) } par <- c(ea, eb) names(par) <- c("shape", "scale") res <- list(iters = i, loglik = lik2, par = par) } else { ea <- ini.ea eb <- m/ea lik1 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n *ea * log1p(eb) dera <- sum( digamma(x + ea) ) * ea - n * digamma(ea) * ea - n * ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ea) ) * ea^2 - n * trigamma(ea) * ea^2 derb2 <- - p * (1 - p) * sx - n * ea * p * (1 - p) anew <- log(c(ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 dera <- sum( digamma(x + ea) ) * ea - n * digamma(ea) * ea - n * ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ea) ) * ea^2 - n * trigamma(ea) * ea^2 derb2 <- - p * (1 - p) * sx - n * ea * p * (1 - p) anew <- log(c(ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) } par <- c(ea, eb) names(par) <- c("shape", "scale") res <- list(iters = i, loglik = lik2, par = par) } res } halfcauchy.mle <- function(x, tol = 1e-07) { n <- length(x) es <- 0.5 * (Rfast::nth(x, 3 * n/4) - Rfast::nth(x, n/4)) logs <- log(es) x2 <- x^2 down <- 1/(x2 + es^2) lik1 <- n * logs + sum( log(down) ) der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) } list(iters = i, loglik = lik2 - n * log(2/pi), scale = es) } cauchy0.mle <- function(x, tol = 1e-07) { n <- length(x) es <- 0.5 * (Rfast::nth(x, 3 * n/4) - Rfast::nth(x, n/4)) logs <- log(es) x2 <- x^2 down <- 1/(x2 + es^2) lik1 <- n * logs + sum( log(down) ) der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) } list(iters = i, loglik = lik2 - n * log(pi), scale = es) } kumar.mle <- function(x, tol = 1e-07, maxiters = 50) { n <- length(x) lx <- log(x) slx <- sum(lx) ini <- Rfast::beta.mle(x)$param expa <- ini[1] ; expb <- ini[2] xa <- x^expa ya <- 1 - xa com <- xa * lx / ya scom <- sum(com) derab <- - expb * expa * scom dera <- n + expa * slx + (1 - 1/ expb) * derab dera2 <- expa * slx - (expb - 1) * expa^2 * sum( com * lx / ya ) derb2 <- expb * sum( log(ya) ) derb <- n + derb2 aold <- c( log(expa), log(expb) ) anew <- aold - c( derb2 * dera - derab * derb, - derab * dera + dera2 * derb ) / ( dera2 * derb2 - derab^2 ) i <- 2 while ( sum( abs(anew - aold) ) > tol & i < maxiters ) { i <- i + 1 aold <- anew expa <- exp( aold[1] ) ; expb <- exp( aold[2] ) xa <- x^expa ya <- 1 - xa com <- xa * lx / ya scom <- sum(com) derab <- - expb * expa * scom dera <- n + expa * slx + (1 - 1/ expb) * derab dera2 <- expa * slx - (expb - 1) * expa^2 * sum( com * lx / ya ) derb2 <- expb * sum( log(ya) ) derb <- n + derb2 anew <- aold - c( derb2 * dera - derab * derb, - derab * dera + dera2 * derb ) / ( dera2 * derb2 - derab^2 ) } a <- exp( anew[1] ) ; b <- exp( anew[2] ) param <- c(a, b) loglik <- n * log(a * b) + (a - 1) * slx + (b - 1) * derb2/expb names(param) <- c("shape", "scale") list(iters = i, param = param, loglik = loglik) } powerlaw.mle <- function(x) { n <- length(x) x1 <- min(x) com <- sum( log(x) ) - n * log(x1) a <- 1 + n / com loglik <- n * log( (a - 1) / x1 ) - a * com list(alpha = a, loglik = loglik) } purka.mle <- function(x, tol = 1e-07) { if ( !is.matrix(x) ) x <- cbind( cos(x), sin(x) ) p <- dim(x)[2] theta <- Rfast::mediandir(x) a <- x %*% theta a[ abs(a) > 1 ] <- 1 A <- sum( acos(a) ) n <- dim(x)[1] circle <- function(a, A, n) n * log(a) - n * log(2) - n * log( 1 - exp( - a * pi ) ) - a * A sphere <- function(a, A, n) n * log(a^2 + 1) - n * log(2 * pi) - n * log( 1 + exp( - a * pi ) ) - a * A hypersphere <- function(a, A, n) { n * lgamma(p/2) - 0.5 * n * p * log(pi) + n * ( log(besselI(a, p - 1, expon.scaled = TRUE)) + a ) - a * A } if (p == 2) { lika <- optimize(circle, c(0.001, 30000), maximum = TRUE, A = A, n = n, tol = tol) a <- lika$maximum f2 <- -n / a^2 + n * pi^2 * exp( -a * pi)/ ( 1 - exp(-a * pi) )^2 } else if (p == 3) { lika <- optimize(sphere, c(0.001, 30000), maximum = TRUE, A = A, n = n, tol = tol) a <- lika$maximum f2 <- - (2 * a^2 * n - 2 * n) / (a^2 + 1)^2 - n * pi^2 * ( 1 + exp( a * pi) )^(-2) * exp( a * pi ) } else { lika <- optimize(hypersphere, c(0.001, 30000), maximum = TRUE, A = A, n = n, tol = tol) a <- lika$maximum up1 <- ( besselI(a, p - 3) + 2 * besselI(p - 1, a) + besselI(p + 1, a) ) * besselI(p - 1, a) up2 <- ( besselI(a, p - 2) + 2 * besselI(p, a) )^2 f2 <- 0.5 * n * ( up1 - up2 ) / besselI(p - 1, a)^2 } list( theta = theta, alpha = a, loglik = lika$objective, alpha.sd = 1 / sqrt( - f2 ) ) } simplex.mle <- function(x, tol = 1e-07) { n <- length(x) xx <- x * (1 - x) simplexfun <- function(m, xx, x) sum( (x - m)^2 /xx ) / ( m^2 * (1 - m)^2 ) mod <- optimise(simplexfun, c(0, 1), xx = xx, x = x, tol = tol) s <- sqrt( mod$objective/n ) param <- c( mod$minimum, s) names(param) <- c("mean", "sigma") list(param = param, loglik = -0.5 * n * log(2 * pi) - 1.5 * sum( log(xx) ) - n * log(s) - n/2 ) } trunccauchy.mle <- function (x, a, b, tol = 1e-07) { n <- length(x) m <- Rfast::med(x) es <- 0.5 * (Rfast::nth(x, 3 * n/4) - Rfast::nth(x, n/4)) logs <- log(es) y <- x - m y2 <- y^2 lik1 <- n * logs - sum(log(es^2 + y2)) down <- 1/(es^2 + y2) down2 <- down^2 derm <- 2 * sum(y * down) ders <- n - 2 * es^2 * sum(down) derm2 <- 2 * sum((y2 - es^2) * down2) ders2 <- -2 * es^2 * (derm2 + 2 * es^2 * sum(down2)) derms <- -4 * es^2 * sum(y * down2) m <- m - (ders2 * derm - derms * ders)/(derm2 * ders2 - derms^2) logs <- logs - (-derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) y <- x - m y2 <- y^2 es <- exp(logs) lik2 <- n * logs - sum(log(es^2 + y2)) i <- 2 while (lik2 - lik1 > tol) { i <- i + 1 lik1 <- lik2 down <- 1/(es^2 + y2) down2 <- down^2 derm <- 2 * sum(y * down) ders <- n - 2 * es^2 * sum(down) derm2 <- 2 * sum((y2 - es^2) * down2) ders2 <- -2 * es^2 * (derm2 + 2 * es^2 * sum(down2)) derms <- -4 * es^2 * sum(y * down2) m <- m - (ders2 * derm - derms * ders)/(derm2 * ders2 - derms^2) logs <- logs - (-derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) y <- x - m y2 <- y^2 es <- exp(logs) lik2 <- n * logs - sum(log(es^2 + y2)) } param <- c(m, es) names(param) <- c("location", "scale") tr <- atan(b) - atan(a) list(iters = i, loglik = lik2 - n * log(tr), param = param) } truncexpmle <- function(x, b, tol = 1e-07) { trexp <- function(lam, sx, b, n) { - n * log(lam) - sx/lam - n * log( 1 - exp(-b/lam) ) } mod <- optimise(trexp, c(0, b), sx = sum(x), b = b, n = length(x), tol = tol, maximum = TRUE ) list(loglik = mod$objective, lambda = mod$minimum) } zigamma.mle <- function(x, tol = 1e-07) { n <- length(x) x1 <- x[x > 0] n1 <- length(x1) n0 <- n - n1 prob <- n1/n lik0 <- n0 * log(1 - prob) + n1 * log(prob) mod <- Rfast::gammamle(x1, tol = tol) param <- c(prob, mod$param) names(param) <- c("prop1", "shape", "scale") list(iters = mod$iters, loglik = sum(lik0, mod$loglik, na.rm = TRUE), param = param) } zil.mle <- function(x) { n <- length(x) x1 <- x[x > 0] n1 <- length(x1) n0 <- n - n1 prob <- n1/n lik0 <- n0 * log(1 - prob) + n1 * log(prob) lx1 <- log(x1) lx2 <- log(1 - x1) y <- lx1 - lx2 sy <- sum(y) m <- sy/n1 s <- (sum(y^2) - n1 * m^2)/n1 loglik <- sum(dnorm(y, m, sqrt(s), log = TRUE)) - sy param <- c(prob, m, n1 * s/(n1 - 1)) names(param) <- c("prop1", "mean", "unbiased variance") list(loglik = sum(lik0, loglik, na.rm = TRUE), param = param) } ziweibull.mle <- function(x, tol = 1e-07) { n <- length(x) x1 <- x[x > 0] n1 <- length(x1) n0 <- n - n1 prob <- n1/n lik0 <- n0 * log(1 - prob) + n1 * log(prob) mod <- Rfast::weibull.mle(x1, tol = tol) param <- c(prob, mod$param) names(param) <- c("prop1", "shape", "scale") list(iters = mod$iters, loglik = sum(lik0, mod$loglik, na.rm = TRUE), param = param) } censpois.mle <- function(x, tol = 1e-07) { ca <- min(x) z <- 0:ca fac <- factorial(z) n <- length(x) n2 <- sum(x == ca) n1 <- n - n2 sx <- sum( x[x > ca] ) a1 <- log( sx/n ) down <- sum( exp(a1 * z)/fac ) dera <- - n1 * exp(a1) + sx + n2 * sum( z * exp( a1 * z )/fac ) / down dera2 <- - n1 * exp(a1) + n2 * ( sum( z^2 * exp( a1 * z/fac ) ) - sum( z * exp(a1 * z)/fac )^2 ) / down^2 a2 <- a1 - dera/dera2 i <- 2 while ( abs(a2 - a1) > tol ) { i <- i + 1 down <- sum( exp(a1 * z)/fac ) a1 <- a2 dera <- - n * exp(a1) + sx + n2 * sum( z * exp( a1 * z )/fac ) / down dera2 <- - n * exp(a1) + n2 * ( sum( z^2 * exp( a1 * z/fac ) ) - sum( z * exp(a1 * z)/fac )^2 ) / down^2 a2 <- a1 - dera/dera2 } loglik <- - n * exp(a1) + sx * a1 - sum( lgamma(x + 1) ) + n2 * log( down ) list(iters = i, loglik = loglik, lambda = exp(a2) ) } censweibull.mle <- function(x, di, tol = 1e-07) { y <- log(x) y1 <- y[di == 1] y2 <- y[di == 0] n <- length(x) n1 <- length(y1) n2 <- n - n1 mod <- Rfast::weibull.mle(x[di==1]) if ( n2 > 0 ) { m <- log(mod$param[2]) es <- 1/mod$param[1] s <- log( es ) z1 <- ( y1 - m ) / es z2 <- ( y2 - m ) /es com <- sum(z1) ez1 <- exp(z1) ez2 <- exp(z2) com1 <- sum(ez1) com2 <- sum(ez2) lik1 <- com - com1 - n1 * s - com2 derm2 <- - com1 / es^2 - com2 / es^2 derm <- - n1/ es + - derm2 * es ders <- - com + sum(ez1 * z1) - n1 + sum(ez2 * z2) ders2 <- com - sum(ez1 * z1^2) - sum(ez1 * z1) - sum(ez2 * z2^2) - sum(ez2 * z2) derms <- n1/es - sum(ez1 * z1) / es - com1/es - sum(ez2 * z2) / es - com2/es anew <- c(m, s) - c(ders2 * derm - derms * ders, -derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) m <- anew[1] s <- anew[2] es <- exp(s) z1 <- ( y1 - m ) / es z2 <- ( y2 - m ) /es com <- sum(z1) ez1 <- exp(z1) ez2 <- exp(z2) com1 <- sum(ez1) com2 <- sum(ez2) lik2 <- com1 - sum(ez1) - n1 * s - com2 i <- 2 while ( abs(lik2 - lik1) > tol ) { i <- i + 1 lik1 <- lik2 derm2 <- - com1 / es^2 - com2 / es^2 derm <- - n1/ es + - derm2 * es ders <- - com + sum(ez1 * z1) - n1 + sum(ez2 * z2) ders2 <- com - sum(ez1 * z1^2) - sum(ez1 * z1) - sum(ez2 * z2^2) - sum(ez2 * z2) derms <- n1/es - sum(ez1 * z1) / es - com1/es - sum(ez2 * z2) / es - com2/es anew <- c(m, s) - c(ders2 * derm - derms * ders, -derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) m <- anew[1] s <- anew[2] es <- exp(s) z1 <- ( y1 - m ) / es z2 <- ( y2 - m ) /es com <- sum(z1) ez1 <- exp(z1) ez2 <- exp(z2) com1 <- sum(ez1) com2 <- sum(ez2) lik2 <- com - com1 - n1 * s - com2 } param <- c(exp(m), es) names(param) <- c("scale", "1/shape") mod <- list(iters = i, loglik = lik2 - sum(y1), param = param) } else mod <- mod mod } gammapois.mle <- function(x, tol = 1e-07) { n <- length(x) slx <- sum( lgamma(x + 1) ) sx <- sum(x) m <- sx/n m2 <- sum(x^2)/n p <- 1 - m/(m2 - m^2) ini.ea <- max(0, m/p - m) eb <- ini.ea/m if (eb < 1) { lik1 <- sum( lgamma(x + ini.ea) ) - n * lgamma(ini.ea) + sx * log(eb/(1 + eb)) - n *ea * log1p(eb) dera <- sum( digamma(x + ini.ea) ) * ini.ea - n * digamma(ini.ea) * ea - n * ini.ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ini.ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ini.ea) ) * ea^2 - n * trigamma(ini.ea) * ini.ea^2 derb2 <- - p * (1 - p) * sx - n * ini.ea * p * (1 - p) anew <- log(c(ini.ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 dera <- sum( digamma(x + ea) ) * ea - n * digamma(ea) * ea - n * ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ea) ) * ea^2 - n * trigamma(ea) * ea^2 derb2 <- - p * (1 - p) * sx - n * ea * p * (1 - p) anew <- log(c(ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) } par <- c(ea, eb) names(par) <- c("shape", "scale") res <- list(iters = i, loglik = lik2, par = par) } else { ea <- ini.ea eb <- m/ea lik1 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n *ea * log1p(eb) dera <- sum( digamma(x + ea) ) * ea - n * digamma(ea) * ea - n * ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ea) ) * ea^2 - n * trigamma(ea) * ea^2 derb2 <- - p * (1 - p) * sx - n * ea * p * (1 - p) anew <- log(c(ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 dera <- sum( digamma(x + ea) ) * ea - n * digamma(ea) * ea - n * ea * log1p(eb) p <- eb / (1 + eb) derab <- - n * ea * p derb <- sx * (1 - p) + derab dera2 <- dera + sum( trigamma(x + ea) ) * ea^2 - n * trigamma(ea) * ea^2 derb2 <- - p * (1 - p) * sx - n * ea * p * (1 - p) anew <- log(c(ea, eb)) - c(derb2 * dera - derab * derb, -derab * dera + dera2 * derb)/(dera2 * derb2 - derab^2) ea <- exp(anew[1]) ; eb <- exp(anew[2]) lik2 <- sum( lgamma(x + ea) ) - n * lgamma(ea) + sx * log(eb/(1 + eb)) - n * ea * log1p(eb) } par <- c(ea, eb) names(par) <- c("shape", "scale") res <- list(iters = i, loglik = lik2, par = par) } res } halfcauchy.mle <- function(x, tol = 1e-07) { n <- length(x) es <- 0.5 * (Rfast::nth(x, 3 * n/4) - Rfast::nth(x, n/4)) logs <- log(es) x2 <- x^2 down <- 1/(x2 + es^2) lik1 <- n * logs + sum( log(down) ) der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) } list(iters = i, loglik = lik2 - n * log(2/pi), scale = es) } cauchy0.mle <- function(x, tol = 1e-07) { n <- length(x) es <- 0.5 * (Rfast::nth(x, 3 * n/4) - Rfast::nth(x, n/4)) logs <- log(es) x2 <- x^2 down <- 1/(x2 + es^2) lik1 <- n * logs + sum( log(down) ) der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) i <- 2 while ( lik2 - lik1 > tol ) { i <- i + 1 lik1 <- lik2 der <- n - 2 * es^2 * sum(down) der2 <- - 4 * es^4 * sum(down^2) logs <- logs - der/der2 es <- exp(logs) down <- 1/(x2 + es^2) lik2 <- n * logs + sum( log(down) ) } list(iters = i, loglik = lik2 - n * log(pi), scale = es) } kumar.mle <- function(x, tol = 1e-07, maxiters = 50) { n <- length(x) lx <- log(x) slx <- sum(lx) ini <- Rfast::beta.mle(x)$param expa <- ini[1] ; expb <- ini[2] xa <- x^expa ya <- 1 - xa com <- xa * lx / ya scom <- sum(com) derab <- - expb * expa * scom dera <- n + expa * slx + (1 - 1/ expb) * derab dera2 <- expa * slx - (expb - 1) * expa^2 * sum( com * lx / ya ) derb2 <- expb * sum( log(ya) ) derb <- n + derb2 aold <- c( log(expa), log(expb) ) anew <- aold - c( derb2 * dera - derab * derb, - derab * dera + dera2 * derb ) / ( dera2 * derb2 - derab^2 ) i <- 2 while ( sum( abs(anew - aold) ) > tol & i < maxiters ) { i <- i + 1 aold <- anew expa <- exp( aold[1] ) ; expb <- exp( aold[2] ) xa <- x^expa ya <- 1 - xa com <- xa * lx / ya scom <- sum(com) derab <- - expb * expa * scom dera <- n + expa * slx + (1 - 1/ expb) * derab dera2 <- expa * slx - (expb - 1) * expa^2 * sum( com * lx / ya ) derb2 <- expb * sum( log(ya) ) derb <- n + derb2 anew <- aold - c( derb2 * dera - derab * derb, - derab * dera + dera2 * derb ) / ( dera2 * derb2 - derab^2 ) } a <- exp( anew[1] ) ; b <- exp( anew[2] ) param <- c(a, b) loglik <- n * log(a * b) + (a - 1) * slx + (b - 1) * derb2/expb names(param) <- c("shape", "scale") list(iters = i, param = param, loglik = loglik) } powerlaw.mle <- function(x) { n <- length(x) x1 <- min(x) com <- sum( log(x) ) - n * log(x1) a <- 1 + n / com loglik <- n * log( (a - 1) / x1 ) - a * com list(alpha = a, loglik = loglik) } purka.mle <- function(x, tol = 1e-07) { if ( !is.matrix(x) ) x <- cbind( cos(x), sin(x) ) p <- dim(x)[2] theta <- Rfast::mediandir(x) a <- x %*% theta a[ abs(a) > 1 ] <- 1 A <- sum( acos(a) ) n <- dim(x)[1] circle <- function(a, A, n) n * log(a) - n * log(2) - n * log( 1 - exp( - a * pi ) ) - a * A sphere <- function(a, A, n) n * log(a^2 + 1) - n * log(2 * pi) - n * log( 1 + exp( - a * pi ) ) - a * A hypersphere <- function(a, A, n) { n * lgamma(p/2) - 0.5 * n * p * log(pi) + n * ( log(besselI(a, p - 1, expon.scaled = TRUE)) + a ) - a * A } if (p == 2) { lika <- optimize(circle, c(0.001, 30000), maximum = TRUE, A = A, n = n, tol = tol) a <- lika$maximum f2 <- -n / a^2 + n * pi^2 * exp( -a * pi)/ ( 1 - exp(-a * pi) )^2 } else if (p == 3) { lika <- optimize(sphere, c(0.001, 30000), maximum = TRUE, A = A, n = n, tol = tol) a <- lika$maximum f2 <- - (2 * a^2 * n - 2 * n) / (a^2 + 1)^2 - n * pi^2 * ( 1 + exp( a * pi) )^(-2) * exp( a * pi ) } else { lika <- optimize(hypersphere, c(0.001, 30000), maximum = TRUE, A = A, n = n, tol = tol) a <- lika$maximum up1 <- ( besselI(a, p - 3) + 2 * besselI(p - 1, a) + besselI(p + 1, a) ) * besselI(p - 1, a) up2 <- ( besselI(a, p - 2) + 2 * besselI(p, a) )^2 f2 <- 0.5 * n * ( up1 - up2 ) / besselI(p - 1, a)^2 } list( theta = theta, alpha = a, loglik = lika$objective, alpha.sd = 1 / sqrt( - f2 ) ) } simplex.mle <- function(x, tol = 1e-07) { n <- length(x) xx <- x * (1 - x) simplexfun <- function(m, xx, x) sum( (x - m)^2 /xx ) / ( m^2 * (1 - m)^2 ) mod <- optimise(simplexfun, c(0, 1), xx = xx, x = x, tol = tol) s <- sqrt( mod$objective/n ) param <- c( mod$minimum, s) names(param) <- c("mean", "sigma") list(param = param, loglik = -0.5 * n * log(2 * pi) - 1.5 * sum( log(xx) ) - n * log(s) - n/2 ) } trunccauchy.mle <- function (x, a, b, tol = 1e-07) { n <- length(x) m <- Rfast::med(x) es <- 0.5 * (Rfast::nth(x, 3 * n/4) - Rfast::nth(x, n/4)) logs <- log(es) y <- x - m y2 <- y^2 lik1 <- n * logs - sum(log(es^2 + y2)) down <- 1/(es^2 + y2) down2 <- down^2 derm <- 2 * sum(y * down) ders <- n - 2 * es^2 * sum(down) derm2 <- 2 * sum((y2 - es^2) * down2) ders2 <- -2 * es^2 * (derm2 + 2 * es^2 * sum(down2)) derms <- -4 * es^2 * sum(y * down2) m <- m - (ders2 * derm - derms * ders)/(derm2 * ders2 - derms^2) logs <- logs - (-derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) y <- x - m y2 <- y^2 es <- exp(logs) lik2 <- n * logs - sum(log(es^2 + y2)) i <- 2 while (lik2 - lik1 > tol) { i <- i + 1 lik1 <- lik2 down <- 1/(es^2 + y2) down2 <- down^2 derm <- 2 * sum(y * down) ders <- n - 2 * es^2 * sum(down) derm2 <- 2 * sum((y2 - es^2) * down2) ders2 <- -2 * es^2 * (derm2 + 2 * es^2 * sum(down2)) derms <- -4 * es^2 * sum(y * down2) m <- m - (ders2 * derm - derms * ders)/(derm2 * ders2 - derms^2) logs <- logs - (-derms * derm + derm2 * ders)/(derm2 * ders2 - derms^2) y <- x - m y2 <- y^2 es <- exp(logs) lik2 <- n * logs - sum(log(es^2 + y2)) } param <- c(m, es) names(param) <- c("location", "scale") tr <- atan(b) - atan(a) list(iters = i, loglik = lik2 - n * log(tr), param = param) } truncexpmle <- function(x, b, tol = 1e-07) { trexp <- function(lam, sx, b, n) { - n * log(lam) - sx/lam - n * log( 1 - exp(-b/lam) ) } mod <- optimise(trexp, c(0, b), sx = sum(x), b = b, n = length(x), tol = tol, maximum = TRUE ) list(loglik = mod$objective, lambda = mod$minimum) } zigamma.mle <- function(x, tol = 1e-07) { n <- length(x) x1 <- x[x > 0] n1 <- length(x1) n0 <- n - n1 prob <- n1/n lik0 <- n0 * log(1 - prob) + n1 * log(prob) mod <- Rfast::gammamle(x1, tol = tol) param <- c(prob, mod$param) names(param) <- c("prop1", "shape", "scale") list(iters = mod$iters, loglik = sum(lik0, mod$loglik, na.rm = TRUE), param = param) } zil.mle <- function(x) { n <- length(x) x1 <- x[x > 0] n1 <- length(x1) n0 <- n - n1 prob <- n1/n lik0 <- n0 * log(1 - prob) + n1 * log(prob) lx1 <- log(x1) lx2 <- log(1 - x1) y <- lx1 - lx2 sy <- sum(y) m <- sy/n1 s <- (sum(y^2) - n1 * m^2)/n1 loglik <- sum(dnorm(y, m, sqrt(s), log = TRUE)) - sy param <- c(prob, m, n1 * s/(n1 - 1)) names(param) <- c("prop1", "mean", "unbiased variance") list(loglik = sum(lik0, loglik, na.rm = TRUE), param = param) } ziweibull.mle <- function(x, tol = 1e-07) { n <- length(x) x1 <- x[x > 0] n1 <- length(x1) n0 <- n - n1 prob <- n1/n lik0 <- n0 * log(1 - prob) + n1 * log(prob) mod <- Rfast::weibull.mle(x1, tol = tol) param <- c(prob, mod$param) names(param) <- c("prop1", "shape", "scale") list(iters = mod$iters, loglik = sum(lik0, mod$loglik, na.rm = TRUE), param = param) } gnormal0.mle <- function(x, tol = 1e-06) { n <- length(x) xabs <- abs(x) fun <- function(b, xabs, n) { y <- xabs^b sy <- sum(y) 1 + digamma(1/b) / b - sum( y * log(xabs) ) / sy + log( b/n * sy ) / b } b <- mean(xabs) / sqrt( mean(x^2) ) mod <- uniroot(fun, lower = max(1e-5, b - 100 * b), upper = b + min(30, 200 * b), tol = tol, xabs = xabs, n = n ) b <- mod$root a <- ( b/n * sum( xabs^b ) ) ^ ( 1/b ) loglik <- n * log(b) - sum( xabs^b )/a^b - n * log(2 * a) - n * lgamma(1/b) param <- c(a, b) names(param) <- c( "alpha", "beta" ) list(iters = mod$iter, loglik = loglik, param = param) } unitweibull.mle <- function(x, tol = 1e-07, maxiters = 100) { lx <- - log(x) mod <- Rfast::weibull.mle( lx, tol = tol, maxiters = maxiters ) param <- as.vector( mod$param ) names(param) <- c("alpha", "beta") a <- mod$param[1] ; b <- mod$param[2] n <- length(x) loglik <- sum(lx) + n * log(a * b) + (b - 1) * sum( log(lx) ) - a * sum(lx^b) list(iters = mod$iters, loglik = loglik, param = param) }
species_aggreg <- function(df, species, plot, NI_label = ""){ if( missing(df) ){ stop("df not set", call. = F) }else if(!is.data.frame(df)){ stop("df must be a dataframe", call.=F) }else if(length(df)<=1 | nrow(df)<=1){ stop("Length and number of rows of 'df' must be greater than 1", call.=F) } if( missing(species) ){ stop("species not set", call. = F) }else if( !is.character(species) ){ stop("'species' must be a character containing a variable name", call.=F) }else if(length(species)!=1){ stop("Length of 'species' must be 1", call.=F) }else if(forestmangr::check_names(df, species)==F){ stop(forestmangr::check_names(df, species, boolean=F), call.=F) } if( missing(plot) ){ stop("plot not set", call. = F) }else if( !is.character(plot) ){ stop("'plot' must be a character containing a variable name", call.=F) }else if(length(plot)!=1){ stop("Length of 'plot' must be 1", call.=F) }else if(forestmangr::check_names(df, plot)==F){ stop(forestmangr::check_names(df, plot, boolean=F), call.=F) } if(!is.character( NI_label )){ stop( "'NI_label' must be character", call.=F) }else if(length(NI_label)!=1){ stop("Length of 'NI_label' must be 1", call.=F) } SPECIES = species PLOTS = plot NI = NI_label df <- as.data.frame(df) df = df[!is.na(df[SPECIES]),] if(is.null(NI)||NI==""){NI <- ""} df = df[! df[,SPECIES] %in% NI,] espList = levels(factor(df[,SPECIES])) df[,PLOTS] <- as.factor(df[,PLOTS]) df[,SPECIES] <- as.factor(df[,SPECIES]) pivot = data.frame(table(df[SPECIES])) names(pivot) = c("especie", "sum") pivot = pivot[which(pivot$especie %in% espList),] nplots = length(unique(df[,PLOTS])) chisq75 = stats::qchisq(0.75, nplots - 1) chisq99 = stats::qchisq(0.99, nplots - 1) for (i in levels(df[,PLOTS])){ tableFreq = data.frame(table(df[df[PLOTS] == i,SPECIES])) pivot = cbind(pivot, tableFreq[which(tableFreq[,1] %in% espList),2]) names(pivot)[ncol(pivot)] = i } agreg = pivot[1] if(nplots > 3){ for (i in seq(1, length(pivot[,1]))){ Si = stats::var(as.numeric(pivot[i, seq(3, (2 + nplots), 1)])) Mi = mean(as.numeric(pivot[i, seq(3, (2 + nplots), 1)])) agreg[i,"Payandeh"] = round(Si/Mi, 1) if(round(Si/Mi, 1) == 1){ agreg[i, "Pay.res"] = "Random" } else if(round(Si/Mi, 1) < 1) { agreg[i, "Pay.res"] = "Regular" } else { agreg[i, "Pay.res"] = "Aggregated" } agreg[i,"Hazen"] = round(Si/Mi * (nplots - 1), 1) if(round(Si/Mi * (nplots - 1), 1) > chisq99){ agreg[i, "Haz.res"] = "Aggregated" } else if(round(Si/Mi * (nplots - 1), 1) < chisq75) { agreg[i, "Haz.res"] = "Not aggregated" } else { agreg[i, "Haz.res"] = "Tends to aggregate" } if ( (as.numeric(pivot[i, 2]) * (as.numeric(pivot[i, 2])-1)) != 0){ agreg[i,"Morisita"] = round((sum(as.numeric(pivot[i, seq(3, (2 + nplots), 1)]) * (as.numeric(pivot[i, seq(3, (2 + nplots), 1)]) - 1))) / (as.numeric(pivot[i, 2]) * (as.numeric(pivot[i, 2])-1)) * nplots, 1) } else { agreg[i,"Morisita"] = round(0, 0) } if(agreg[i,"Morisita"] == 1){ agreg[i, "Mor.res"] = "Random" } else if(agreg[i,"Morisita"] < 1 & agreg[i,"Morisita"] > 0) { agreg[i, "Mor.res"] = "Regular" } else if(agreg[i,"Morisita"] == 0){ agreg[i, "Mor.res"] = "Rare" } else { agreg[i, "Mor.res"] = "Aggregated" } } return(dplyr::as_tibble(agreg)) } else { stop("Low number of plots", .call=FALSE) } }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(EBImage) library(ExpImage) end=example_image(2) im=read_image(end,plot=TRUE) im2=resize_image(im,w=1000,plot=TRUE) r=gray_scale(im2,method = "r",plot=T) g=gray_scale(im2,method = "g",plot=T) b=gray_scale(im2,method = "b",plot=T) plot_indexes(im,NumberCores=2) MatrizSegmentada=segmentation(b,treshold = 0.20,fillHull = F,selectHigher = T,plot=T) MatrizSegmentada=segmentation(b,treshold = 0.40,fillHull = F,selectHigher = T,plot=T) MatrizSegmentada=segmentation(b,treshold = 0.60,fillHull = F,selectHigher = T,plot=T) MatrizSegmentada=segmentation(b,treshold = 0.80,fillHull = F,selectHigher = T,plot=T) MatrizSegmentada=segmentation(r,treshold = "otsu",fillHull = F,selectHigher = T,plot=T) plot_image(b,col = 3) MatrizSegmentada=segmentation(b,treshold = 0.4,fillHull = F,selectHigher = F,plot=T) MatrizSegmentada=segmentation(b,treshold = 0.4,fillHull = T,selectHigher = F,plot=T) im3=extract_pixels(im2,target =MatrizSegmentada,valueTarget =1,valueSelect = c(0,0,0),plot=T ) r=gray_scale(im3,method = "r",plot=T) g=gray_scale(im3,method = "g",plot=T) b=gray_scale(im3,method = "b",plot=T) MatrizSegmentada2=segmentation(b,treshold = 0.50,fillHull = T,selectHigher = T,plot = T) Medidas=measure_image(MatrizSegmentada2) Medidas$ObjectNumber im4=extract_pixels(im2,target =MatrizSegmentada2,valueTarget =0,valueSelect = c(1,0,0),plot=T ) im5=join_image(im2,im4,plot = TRUE)
emnormmix <- function(y, prop, mu, sigma, err, maxit, verbose){ checkErrors(prop, mu, sigma, err) if (length(err) < 3) err <- rep(err, length.out = 3) k <- length(prop) yvals <- sort(unique(y)) n.yvals <- length(yvals) counts <- as.vector(table(y)) dy <- rep(yvals,each=k) no <- length(y) it <- 0 repeat { it <- it + 1 muold <- mu sigmaold <- sigma propold <- prop dprop <- rep(propold, n.yvals) dmu <- rep(muold, n.yvals) dsigma <- rep(sigmaold, n.yvals) dn <- dnorm(dy, mean = dmu, sd = dsigma) interprop <- matrix(dprop * dn, ncol = k, byrow = TRUE) indices <- sweep(interprop, 1, rowSums(interprop), `/`) sumIndices <- as.vector(counts %*% indices) prop <- sumIndices/no mu <- as.vector(((yvals * counts) %*% indices)/sumIndices) sigma <- sqrt(counts %*% (outer(yvals, mu, `-`) ^ 2 * indices) / sumIndices) flag <- checkStopVerbose(muold, mu, sigmaold, sigma, err, it, maxit, verbose, propold, prop) if(flag==1) break } list(prop = prop, mu = mu, sigma = sigma) } mritc.em <- function(y, prop, mu, sigma, err=1e-4, maxit=200, verbose) { checkErrors(prop, mu, sigma, err) k <- length(prop) nvert <- length(y) result <- emnormmix(y, prop, mu, sigma, err, maxit, verbose) prop <- result$prop mu <- result$mu sigma <- result$sigma yvals <- sort(unique(y)) n.yvals <- length(yvals) counts <- as.vector(table(y)) k <- length(prop) dy <- rep(yvals,each=k) no <- length(y) dprop <- rep(prop, n.yvals) dmu <- rep(mu, n.yvals) dsigma <- rep(sigma, n.yvals) dn <- dnorm(dy, mean = dmu, sd = dsigma) interprop <- matrix(dprop * dn, ncol = k, byrow = TRUE) indices <- sweep(interprop, 1, rowSums(interprop), `/`) pre <- indices list(prob=pre[match(y, yvals),], mu=mu, sigma=sigma) }
calculateRatio_gui <- function(env = parent.frame(), savegui = NULL, debug = FALSE, parent = NULL) { .gData <- NULL .gRef <- NULL .gDataName <- NULL .gRefName <- NULL fnc <- as.character(match.call()[[1]]) if (debug) { print(paste("IN:", fnc)) } strWinTitle <- "Calculate ratio" strChkGui <- "Save GUI settings" strBtnHelp <- "Help" strFrmDataset <- "Datasets" strLblDataset <- "Sample dataset:" strDrpDataset <- "<Select dataset>" strLblSamples <- "samples" strLblRefDataset <- "Reference dataset:" strLblRef <- "references" strBtnCheck <- "Check subsetting" strFrmOptions <- "Options" strLblPre <- "Pre-processing:" strChkOL <- "Remove off-ladder alleles" strLblMethod <- "Calculate marker ratio:" strLblNumerator <- "Select numerator markers:" strDrpMarker <- "<Select Marker>" strLblDenominator <- "Select denominator markers:" strLblGroupBy <- "Group by column:" strDrpColumn <- "<Select Columns>" strLblMatching <- "Reference sample name matching:" strChkIgnore <- "Ignore case" strChkWord <- "Add word boundaries" strChkExact <- "Exact matching" strFrmSave <- "Save as" strLblSave <- "Name for result:" strBtnCalculate <- "Calculate" strBtnProcessing <- "Processing..." strMsgDataset <- "A sample dataset and a reference dataset must be selected." strMsgTitleDataset <- "Dataset not selected" strMsgCheck <- "Data frame is NULL!\n\nMake sure to select a sample dataset." strWinTitleCheck <- "Check subsetting" strMsgTitleError <- "Error" dtStrings <- getStrings(gui = fnc) if (!is.null(dtStrings)) { strtmp <- dtStrings["strWinTitle"]$value strWinTitle <- ifelse(is.na(strtmp), strWinTitle, strtmp) strtmp <- dtStrings["strChkGui"]$value strChkGui <- ifelse(is.na(strtmp), strChkGui, strtmp) strtmp <- dtStrings["strBtnHelp"]$value strBtnHelp <- ifelse(is.na(strtmp), strBtnHelp, strtmp) strtmp <- dtStrings["strFrmDataset"]$value strFrmDataset <- ifelse(is.na(strtmp), strFrmDataset, strtmp) strtmp <- dtStrings["strLblDataset"]$value strLblDataset <- ifelse(is.na(strtmp), strLblDataset, strtmp) strtmp <- dtStrings["strDrpDataset"]$value strDrpDataset <- ifelse(is.na(strtmp), strDrpDataset, strtmp) strtmp <- dtStrings["strLblSamples"]$value strLblSamples <- ifelse(is.na(strtmp), strLblSamples, strtmp) strtmp <- dtStrings["strLblRefDataset"]$value strLblRefDataset <- ifelse(is.na(strtmp), strLblRefDataset, strtmp) strtmp <- dtStrings["strLblRef"]$value strLblRef <- ifelse(is.na(strtmp), strLblRef, strtmp) strtmp <- dtStrings["strBtnCheck"]$value strBtnCheck <- ifelse(is.na(strtmp), strBtnCheck, strtmp) strtmp <- dtStrings["strFrmOptions"]$value strFrmOptions <- ifelse(is.na(strtmp), strFrmOptions, strtmp) strtmp <- dtStrings["strLblPre"]$value strLblPre <- ifelse(is.na(strtmp), strLblPre, strtmp) strtmp <- dtStrings["strChkOL"]$value strChkOL <- ifelse(is.na(strtmp), strChkOL, strtmp) strtmp <- dtStrings["strLblMethod"]$value strLblMethod <- ifelse(is.na(strtmp), strLblMethod, strtmp) strtmp <- dtStrings["strLblNumerator"]$value strLblNumerator <- ifelse(is.na(strtmp), strLblNumerator, strtmp) strtmp <- dtStrings["strDrpMarker"]$value strDrpMarker <- ifelse(is.na(strtmp), strDrpMarker, strtmp) strtmp <- dtStrings["strLblDenominator"]$value strLblDenominator <- ifelse(is.na(strtmp), strLblDenominator, strtmp) strtmp <- dtStrings["strLblGroupBy"]$value strLblGroupBy <- ifelse(is.na(strtmp), strLblGroupBy, strtmp) strtmp <- dtStrings["strDrpColumn"]$value strDrpColumn <- ifelse(is.na(strtmp), strDrpColumn, strtmp) strtmp <- dtStrings["strLblMatching"]$value strLblMatching <- ifelse(is.na(strtmp), strLblMatching, strtmp) strtmp <- dtStrings["strChkIgnore"]$value strChkIgnore <- ifelse(is.na(strtmp), strChkIgnore, strtmp) strtmp <- dtStrings["strChkWord"]$value strChkWord <- ifelse(is.na(strtmp), strChkWord, strtmp) strtmp <- dtStrings["strChkExact"]$value strChkExact <- ifelse(is.na(strtmp), strChkExact, strtmp) strtmp <- dtStrings["strFrmSave"]$value strFrmSave <- ifelse(is.na(strtmp), strFrmSave, strtmp) strtmp <- dtStrings["strLblSave"]$value strLblSave <- ifelse(is.na(strtmp), strLblSave, strtmp) strtmp <- dtStrings["strBtnCalculate"]$value strBtnCalculate <- ifelse(is.na(strtmp), strBtnCalculate, strtmp) strtmp <- dtStrings["strBtnProcessing"]$value strBtnProcessing <- ifelse(is.na(strtmp), strBtnProcessing, strtmp) strtmp <- dtStrings["strMsgDataset"]$value strMsgDataset <- ifelse(is.na(strtmp), strMsgDataset, strtmp) strtmp <- dtStrings["strMsgTitleDataset"]$value strMsgTitleDataset <- ifelse(is.na(strtmp), strMsgTitleDataset, strtmp) strtmp <- dtStrings["strMsgCheck"]$value strMsgCheck <- ifelse(is.na(strtmp), strMsgCheck, strtmp) strtmp <- dtStrings["strWinTitleCheck"]$value strWinTitleCheck <- ifelse(is.na(strtmp), strWinTitleCheck, strtmp) strtmp <- dtStrings["strMsgTitleError"]$value strMsgTitleError <- ifelse(is.na(strtmp), strMsgTitleError, strtmp) } w <- gwindow(title = strWinTitle, visible = FALSE) addHandlerUnrealize(w, handler = function(h, ...) { .saveSettings() if (!is.null(parent)) { focus(parent) } if (gtoolkit() == "tcltk") { if (as.numeric(gsub("[^0-9]", "", packageVersion("gWidgets2tcltk"))) <= 106) { message("tcltk version <= 1.0.6, returned TRUE!") return(TRUE) } else { message("tcltk version >1.0.6, returned FALSE!") return(FALSE) } } else { message("RGtk2, returned FALSE!") return(FALSE) } }) gv <- ggroup( horizontal = FALSE, spacing = 8, use.scrollwindow = FALSE, container = w, expand = TRUE ) gh <- ggroup(container = gv, expand = FALSE, fill = "both") savegui_chk <- gcheckbox(text = strChkGui, checked = FALSE, container = gh) addSpring(gh) help_btn <- gbutton(text = strBtnHelp, container = gh) addHandlerChanged(help_btn, handler = function(h, ...) { print(help(fnc, help_type = "html")) }) f0 <- gframe( text = strFrmDataset, horizontal = TRUE, spacing = 5, container = gv ) g0 <- glayout(container = f0, spacing = 1) g0[1, 1] <- glabel(text = strLblDataset, container = g0) dfs <- c(strDrpDataset, listObjects(env = env, obj.class = "data.frame")) g0[1, 2] <- g0_data_drp <- gcombobox( items = dfs, selected = 1, editable = FALSE, container = g0, ellipsize = "none" ) g0[1, 3] <- g0_data_samples_lbl <- glabel( text = paste(" 0", strLblSamples), container = g0 ) addHandlerChanged(g0_data_drp, handler = function(h, ...) { val_obj <- svalue(g0_data_drp) requiredCol <- c("Sample.Name", "Marker", "Allele", "Height") ok <- checkDataset( name = val_obj, reqcol = requiredCol, slim = TRUE, slimcol = "Height", env = env, parent = w, debug = debug ) if (ok) { .gData <<- get(val_obj, envir = env) .gDataName <<- val_obj svalue(g0_data_samples_lbl) <- paste( length(unique(.gData$Sample.Name)), strLblSamples ) f1_numerator_drp[, ] <- unique(c(strDrpMarker, .gData$Marker)) f1_denominator_drp[, ] <- unique(c(strDrpMarker, .gData$Marker)) f1_group_drp[, ] <- unique(c(strDrpColumn, names(.gData))) svalue(f1_numerator_drp, index = TRUE) <- 1 svalue(f1_denominator_drp, index = TRUE) <- 1 svalue(f1_group_drp, index = TRUE) <- 1 svalue(save_edt) <- paste(val_obj, "_ratio", sep = "") } else { .gData <<- NULL .gDataName <<- NULL svalue(g0_data_drp, index = TRUE) <- 1 svalue(g0_data_samples_lbl) <- paste(" 0", strLblSamples) svalue(save_edt) <- "" f1_numerator_drp[, ] <- strDrpMarker f1_denominator_drp[, ] <- strDrpMarker f1_group_drp[, ] <- strDrpColumn svalue(f1_numerator_drp, index = TRUE) <- 1 svalue(f1_denominator_drp, index = TRUE) <- 1 svalue(f1_group_drp, index = TRUE) <- 1 } }) g0[2, 1] <- glabel(text = strLblRefDataset, container = g0) g0[2, 2] <- g0_ref_drp <- gcombobox( items = dfs, selected = 1, editable = FALSE, container = g0, ellipsize = "none" ) g0[2, 3] <- g0_ref_samples_lbl <- glabel( text = paste(" 0", strLblRef), container = g0 ) addHandlerChanged(g0_ref_drp, handler = function(h, ...) { val_obj <- svalue(g0_ref_drp) requiredCol <- c("Sample.Name", "Marker", "Allele") ok <- checkDataset( name = val_obj, reqcol = requiredCol, slim = TRUE, slimcol = "Allele", env = env, parent = w, debug = debug ) if (ok) { .gRef <<- get(val_obj, envir = env) .gRefName <<- val_obj svalue(g0_ref_samples_lbl) <- paste( length(unique(.gRef$Sample.Name)), strLblRef ) } else { .gRef <<- NULL .gRefName <<- NULL svalue(g0_ref_drp, index = TRUE) <- 1 svalue(g0_ref_samples_lbl) <- paste(" 0", strLblRef) } }) g0[3, 2] <- g0_check_btn <- gbutton(text = strBtnCheck, container = g0) addHandlerChanged(g0_check_btn, handler = function(h, ...) { val_data <- .gData val_ref <- .gRef val_ignore <- svalue(f1_ignore_chk) val_word <- svalue(f1_word_chk) if (!is.null(.gData) || !is.null(.gRef)) { chksubset_w <- gwindow( title = strWinTitleCheck, visible = FALSE, name = title, width = NULL, height = NULL, parent = w, handler = NULL, action = NULL ) chksubset_txt <- checkSubset( data = val_data, ref = val_ref, console = FALSE, ignore.case = val_ignore, word = val_word ) gtext( text = chksubset_txt, width = NULL, height = 300, font.attr = NULL, wrap = FALSE, container = chksubset_w ) visible(chksubset_w) <- TRUE } else { gmessage( msg = strMsgCheck, title = strMsgTitleError, icon = "error" ) } }) f1 <- gframe( text = strFrmOptions, horizontal = FALSE, spacing = 10, container = gv ) glabel(text = strLblPre, anchor = c(-1, 0), container = f1) f1_ol_chk <- gcheckbox( text = strChkOL, checked = TRUE, container = f1 ) glabel(text = strLblMethod, anchor = c(-1, 0), container = f1) f1g1 <- glayout(container = f1) f1g1[1, 1] <- glabel(text = strLblNumerator, container = f1g1) f1g1[1, 2] <- f1_numerator_drp <- gcombobox( items = strDrpMarker, container = f1g1, ellipsize = "none" ) f1g1[2, 1:2] <- f1_numerator_edt <- gedit(text = "", container = f1g1) f1g1[3, 1] <- glabel(text = strLblDenominator, container = f1g1) f1g1[3, 2] <- f1_denominator_drp <- gcombobox( items = strDrpMarker, container = f1g1, ellipsize = "none" ) f1g1[4, 1:2] <- f1_denominator_edt <- gedit(text = "", container = f1g1) f1g1[5, 1] <- glabel(text = strLblGroupBy, container = f1g1) f1g1[5, 2] <- f1_group_drp <- gcombobox( items = strDrpColumn, container = f1g1, ellipsize = "none" ) addHandlerChanged(f1_numerator_drp, handler = function(h, ...) { val_marker <- svalue(f1_numerator_drp) val_value <- svalue(f1_numerator_edt) if (!is.null(val_marker)) { if (val_marker != strDrpMarker) { if (nchar(val_value) == 0) { svalue(f1_numerator_edt) <- val_marker } else { svalue(f1_numerator_edt) <- paste(val_value, val_marker, sep = ",") } } } }) addHandlerChanged(f1_denominator_drp, handler = function(h, ...) { val_marker <- svalue(f1_denominator_drp) val_value <- svalue(f1_denominator_edt) if (!is.null(val_marker)) { if (val_marker != strDrpMarker) { if (nchar(val_value) == 0) { svalue(f1_denominator_edt) <- val_marker } else { svalue(f1_denominator_edt) <- paste(val_value, val_marker, sep = ",") } } } }) glabel(text = strLblMatching, anchor = c(-1, 0), container = f1) f1_ignore_chk <- gcheckbox( text = strChkIgnore, checked = TRUE, container = f1 ) f1_word_chk <- gcheckbox( text = strChkWord, checked = FALSE, container = f1 ) f1_exact_chk <- gcheckbox( text = strChkExact, checked = FALSE, container = f1 ) save_frame <- gframe(text = strFrmSave, container = gv) glabel(text = strLblSave, container = save_frame) save_edt <- gedit(expand = TRUE, fill = TRUE, container = save_frame) calculate_btn <- gbutton(text = strBtnCalculate, container = gv) addHandlerClicked(calculate_btn, handler = function(h, ...) { val_data <- .gData val_name_data <- .gDataName val_ref <- .gRef val_name_ref <- .gRefName val_ol <- svalue(f1_ol_chk) val_ignore <- svalue(f1_ignore_chk) val_word <- svalue(f1_word_chk) val_exact <- svalue(f1_exact_chk) val_name <- svalue(save_edt) val_numerator <- svalue(f1_numerator_edt) val_denominator <- svalue(f1_denominator_edt) val_group <- svalue(f1_group_drp) if (val_group == strDrpColumn) { val_group <- NULL } if (debug) { print("Read Values:") print("val_data") print(head(val_data)) print("val_ref") print(head(val_ref)) print("val_ol") print(val_ol) print("val_ignore") print(val_ignore) print("val_word") print(val_word) print("val_exact") print(val_exact) print("val_name") print(val_name) } if (!is.null(.gData)) { if (!nchar(val_numerator) > 0) { val_numerator <- NULL } else { val_numerator <- unlist(strsplit(val_numerator, split = ",")) } if (!nchar(val_denominator) > 0) { val_denominator <- NULL } else { val_denominator <- unlist(strsplit(val_denominator, split = ",")) } if (debug) { print("Sent Values:") print("val_numerator") print(val_numerator) print("val_denominator") print(val_denominator) print("val_group") print(val_group) } blockHandlers(calculate_btn) svalue(calculate_btn) <- strBtnProcessing unblockHandlers(calculate_btn) enabled(calculate_btn) <- FALSE datanew <- calculateRatio( data = val_data, ref = val_ref, numerator = val_numerator, denominator = val_denominator, group = val_group, ol.rm = val_ol, ignore.case = val_ignore, word = val_word, exact = val_exact, debug = debug ) keys <- list( "data", "ref", "numerator", "denominator", "group", "ol", "ignore.case", "word", "exact" ) values <- list( val_name_data, val_name_ref, val_numerator, val_denominator, val_group, val_ol, val_ignore, val_word, val_exact ) datanew <- auditTrail( obj = datanew, key = keys, value = values, label = fnc, arguments = FALSE, package = "strvalidator" ) saveObject(name = val_name, object = datanew, parent = w, env = env) if (debug) { print(str(datanew)) print(head(datanew)) print(paste("EXIT:", fnc)) } .saveSettings() dispose(w) } else { gmessage( msg = strMsgDataset, title = strMsgTitleDataset, icon = "error", parent = w ) } }) .loadSavedSettings <- function() { if (!is.null(savegui)) { svalue(savegui_chk) <- savegui enabled(savegui_chk) <- FALSE if (debug) { print("Save GUI status set!") } } else { if (exists(".strvalidator_calculateRatio_gui_savegui", envir = env, inherits = FALSE)) { svalue(savegui_chk) <- get(".strvalidator_calculateRatio_gui_savegui", envir = env) } if (debug) { print("Save GUI status loaded!") } } if (debug) { print(svalue(savegui_chk)) } if (svalue(savegui_chk)) { if (exists(".strvalidator_calculateRatio_gui_numerator", envir = env, inherits = FALSE)) { svalue(f1_numerator_edt) <- get(".strvalidator_calculateRatio_gui_numerator", envir = env) } if (exists(".strvalidator_calculateRatio_gui_denominator", envir = env, inherits = FALSE)) { svalue(f1_denominator_edt) <- get(".strvalidator_calculateRatio_gui_denominator", envir = env) } if (exists(".strvalidator_calculateRatio_gui_ol", envir = env, inherits = FALSE)) { svalue(f1_ol_chk) <- get(".strvalidator_calculateRatio_gui_ol", envir = env) } if (exists(".strvalidator_calculateRatio_gui_ignore", envir = env, inherits = FALSE)) { svalue(f1_ignore_chk) <- get(".strvalidator_calculateRatio_gui_ignore", envir = env) } if (exists(".strvalidator_calculateRatio_gui_word", envir = env, inherits = FALSE)) { svalue(f1_word_chk) <- get(".strvalidator_calculateRatio_gui_word", envir = env) } if (exists(".strvalidator_calculateRatio_gui_exact", envir = env, inherits = FALSE)) { svalue(f1_exact_chk) <- get(".strvalidator_calculateRatio_gui_exact", envir = env) } if (debug) { print("Saved settings loaded!") } } } .saveSettings <- function() { if (svalue(savegui_chk)) { assign(x = ".strvalidator_calculateRatio_gui_savegui", value = svalue(savegui_chk), envir = env) assign(x = ".strvalidator_calculateRatio_gui_numerator", value = svalue(f1_numerator_edt), envir = env) assign(x = ".strvalidator_calculateRatio_gui_denominator", value = svalue(f1_denominator_edt), envir = env) assign(x = ".strvalidator_calculateRatio_gui_word", value = svalue(f1_word_chk), envir = env) assign(x = ".strvalidator_calculateRatio_gui_ignore", value = svalue(f1_ignore_chk), envir = env) assign(x = ".strvalidator_calculateRatio_gui_exact", value = svalue(f1_exact_chk), envir = env) } else { if (exists(".strvalidator_calculateRatio_gui_savegui", envir = env, inherits = FALSE)) { remove(".strvalidator_calculateRatio_gui_savegui", envir = env) } if (exists(".strvalidator_calculateRatio_gui_numerator", envir = env, inherits = FALSE)) { remove(".strvalidator_calculateRatio_gui_numerator", envir = env) } if (exists(".strvalidator_calculateRatio_gui_denominator", envir = env, inherits = FALSE)) { remove(".strvalidator_calculateRatio_gui_denominator", envir = env) } if (exists(".strvalidator_calculateRatio_gui_ignore", envir = env, inherits = FALSE)) { remove(".strvalidator_calculateRatio_gui_ignore", envir = env) } if (exists(".strvalidator_calculateRatio_gui_word", envir = env, inherits = FALSE)) { remove(".strvalidator_calculateRatio_gui_word", envir = env) } if (exists(".strvalidator_calculateRatio_gui_exact", envir = env, inherits = FALSE)) { remove(".strvalidator_calculateRatio_gui_exact", envir = env) } if (debug) { print("Settings cleared!") } } if (debug) { print("Settings saved!") } } .loadSavedSettings() visible(w) <- TRUE focus(w) }
library(karel) test_that("Checking conditions work fine.", { generar_mundo("mundo001") expect_true(frente_abierto()) expect_false(frente_cerrado()) expect_true(izquierda_abierto()) expect_false(izquierda_cerrado()) expect_false(derecha_abierto()) expect_true(derecha_cerrado()) expect_false(hay_cosos()) expect_true(no_hay_cosos()) expect_true(karel_tiene_cosos()) expect_false(karel_no_tiene_cosos()) expect_true(mira_al_este()) expect_false(mira_al_oeste()) expect_false(mira_al_norte()) expect_false(mira_al_sur()) })
waggle <- function(min, max, value = (min + max) / 2, step = (max - min) / 50, fps = 10) { vals <- shiny::reactiveValues() vals$x <- value connect <- function(session, plot_id) { direction <- 1 shiny::observe({ shiny::invalidateLater(1000 / fps, NULL) next_value <- shiny::isolate(vals$x) + direction * step if (next_value < min || next_value > max) { direction <<- -1 * direction next_value <- pmax(pmin(next_value, max), min) } vals$x <<- next_value }) } create_broker(reactive(vals$x), connect = connect) }
myvector = round(runif(6*12)*100,0) myvector myts <- ts(myvector, start=c(2009, 1), end=c(2014, 12), frequency=12) myts myts2 <- window(myts, start=c(2014, 6), end=c(2014, 12)) myts2 plot(myts) sales= c(18,33,41,7,34,35,24,25,24,21,25,20, 22,31,40,29,25,21,22,54,31,25,26,35) tsales = ts(sales, start=c(2003,1), frequency=12) tsales plot(tsales) plot(tsales, type='o', pch=19) start(tsales) end(tsales) frequency(tsales) tsales.subset = window(tsales, start=c(2003,5), end=c(2004,6)) tsales.subset myvector = round(runif(50) * 100,0) myvector myts <- ts(myvector, start=c(2009,2), end=c(2014,11), frequency=3) myts myts2 <- window(myts, start=c(2010), end=c(2013)) myts2 myvector = round(runif(50) * 100,0) myvector myts <- ts(myvector, start=c(2009,1), end=c(2014,11), frequency=3) myts str(myts) plot(myts, type='o', pch=19) text() plot.ts(myts, type='o', pch=19, xy.labels=F) axis(1, myts$Date, format(myts$Date, "%b %d"), cex.axis = .7) myts <- ts(myvector, start=c(2009,2), end=c(2014,9), frequency=3) myts str(myts) myts2 <- window(myts, start=c(2010), end=c(2013)) myts2 plot(myts, type='o', pch=19) str(myts2) myts2 <- window(myts, start=c(2014, 6), end=c(2014, 12)) plot(myts,type='o', pch=19) text() plot(myts2,type='o', pch=19) library(zoo) x.Date <- as.Date(paste(rep(2003:2004, each = 12), rep(1:12, 2), 1, sep = "-")) x.Date ?zoo x <- zoo(rnorm(24), x.Date) x plot(x) plot(x, xaxt = "n") axis(1, at = time(x), labels = FALSE) plot(x) axis(1, at = time(x), labels = FALSE) plot(x) times <- time(x) ticks <- seq(times[1], times[length(times)], by = "weeks") axis(1, at = ticks, labels = FALSE, tcl = -0.3) library(zoo) library(lattice) z <- zooreg(1:83, start = as.Date("2009-04-01"), deltat = 7) xyplot(z) library(zoo) today = Sys.Date() dates = as.Date((today-500):today) dates z = zoo (100+cumsum(rnorm(501)), dates) z ?plot.zoo plot(z) ?plot.ts plot(ts(z)) time(z) library(lattice) ?xyplot.zoo xyplot(z) xyplot(z, lwd=2, col="tomato") library(xts) ?plot.xts plot(as.xts(z)) plot(as.xts(z), auto.grid=F, major.format="%b %y", las=2) timeline = time(z) summary(timeline) index = seq(from=1, to=length(timeline), 90) plot(z, xaxt="n") axis(side=1, at=timeline[index], label=format(timeline[index], "%b %y"), cex.axis=0.8) library(ggplot2) library(scales) ?date_breaks df = data.frame(date=as.POSIXct(time(z)), value=as.numeric(z)) head(df) ggplot(df, aes(x=date, y=value)) + geom_line() ggplot(df, aes(x=date, y=value)) + geom_line() + scale_x_datetime(labels=date_format("%b '%y")) ggplot(df, aes(x=date, y=value)) + geom_line() + scale_x_datetime(labels=date_format("%b '%y"), breaks=date_breaks("3 months"))
face.sparse.inner <- function(data, newdata = NULL, W = NULL, center=TRUE,argvals.new=NULL, knots=7, knots.option="equally-spaced", p=3,m=2,lambda=NULL,lambda_mean=NULL, search.length=14, lower=-3,upper=10, calculate.scores=FALSE,pve=0.99){ check.data(data) if(!is.null(newdata)){ check.data(newdata,type="predict")} y <- data$y t <- data$argvals subj <- data$subj tnew <- argvals.new if(is.null(tnew)) tnew <- seq(min(t),max(t),length=100) fit_mean <- NULL knots.initial <- knots r <- y mu.new <- rep(0,length(tnew)) if(center){ fit_mean <- pspline(data,argvals.new=tnew,knots=knots.initial,lambda=lambda_mean) mu.new <- fit_mean$mu.new r <- y - fit_mean$fitted.values } indW <- F if(is.null(W)) indW <- T raw <- raw.construct(data.frame("argvals" = t, "subj" = subj, "y" = as.vector(r))) C <- raw$C st <- raw$st N <- raw$st N2 <- raw$N2 if(indW) W <- raw$W n0 <- raw$n0 delta <- Matrix((st[,1]==st[,2]) * 1) knots <- construct.knots(t,knots,knots.option,p) List <- pspline.setting(st[,1],knots=knots,p,m,type="simple",knots.option=knots.option) B1 <- List$B B1 <- Matrix(B1) DtD <- List$P B2 = spline.des(knots=knots, x=st[,2], ord = p+1,outer.ok = TRUE,sparse=TRUE)$design c = dim(B1)[2] c2 = c*(c+1)/2 B = Matrix(t(KhatriRao(Matrix(t(B2)),Matrix(t(B1))))) G = Matrix(duplication.matrix(c)) BtWB = matrix(0,nrow=c^2,ncol=c^2) Wdelta = c() WC = c() for(i in 1:n0){ seq = (sum(N2[1:i])-N2[i]+1):(sum(N2[1:i])) B3 = Matrix(matrix(B[seq,],nrow=length(seq))) W3 = W[[i]] BtWB = BtWB + crossprod(B3, W3%*%B3) Wdelta <- c(Wdelta,as.matrix(W3 %*% delta[seq])) WC <- c(WC,as.matrix(W3 %*% C[seq])) } GtBtWBG = crossprod(G,BtWB%*%G) BG = B%*%G detWde <- crossprod(delta,Wdelta) GtBtWdelta <- crossprod(BG,Wdelta) XtWX <- rbind(cbind(GtBtWBG,GtBtWdelta), cbind(t(GtBtWdelta),detWde)) eSig = eigen(XtWX,symmetric=TRUE) V = eSig$vectors E = eSig$values E = E + 0.000001*max(E) Sigi_sqrt = matrix.multiply(V,1/sqrt(E))%*%t(V) P = crossprod(G,Matrix(suppressMessages(kronecker(diag(c),DtD))))%*%G Q = bdiag(P,0) tUQU = crossprod(Sigi_sqrt,(Q%*%Sigi_sqrt)) Esig = eigen(tUQU,symmetric=TRUE) U = Esig$vectors s = Esig$values A0 <- Sigi_sqrt%*%U X <- cbind(BG,delta) A = as.matrix(X%*%A0) AtA = crossprod(A) f = crossprod(A,C) ftilde = crossprod(A,WC) c2 <- c2 + 1 g <- rep(0, c2) G1 <- matrix(0,c2,c2) mat_list <- list() for(i in 1:n0){ seq = (sum(N2[1:i])-N2[i]+1):(sum(N2[1:i])) Ai = matrix(A[seq,],nrow=length(seq)) AitAi = crossprod(Ai) Wi = W[[i]] fi = crossprod(Ai,C[seq]) Ji = crossprod(Ai,Wi%*%C[seq]) Li = crossprod(Ai,Wi%*%Ai) g = g + Ji*fi G1 = G1 + AitAi*(Ji%*%t(ftilde)) LList <- list() LList[[1]] = AitAi LList[[2]] = Li mat_list[[i]] = LList } Lambda <- seq(lower,upper,length=search.length) Gcv <- 0*Lambda gcv <- function(x){ lambda <- exp(x) d <- 1/(1+lambda*s) ftilde_d <- ftilde*d cv0 <- -2*sum(ftilde_d*f) cv1 <- sum(ftilde_d*(AtA%*%ftilde_d)) cv2 <- 2*sum(d*g) cv3 <- -4*sum(d*(G1%*%d)) cv4 <- sum(unlist(sapply(mat_list,function(x){ a <- x[[1]]%*%ftilde_d b <- x[[2]]%*%ftilde_d 2*sum(a*b*d) }))) cv <- cv0 + cv1 + cv2 + cv3 + cv4 return(cv) } if(is.null(lambda)){ Lambda <- seq(lower,upper,length=search.length) Length <- length(Lambda) Gcv <- rep(0,Length) for(i in 1:Length) Gcv[i] <- gcv(Lambda[i]) i0 <- which.min(Gcv) lambda <- exp(Lambda[i0]) } alpha <- matrix.multiply(A0,1/(1+lambda*s))%*%ftilde Theta <- G %*% alpha[1:c2-1] Theta <- matrix(Theta,c,c) sigma2 <- alpha[c2] if(sigma2 <= 0.000001) { warning("error variance cannot be non-positive, reset to 1e-6!") sigma2 <- 0.000001 } Eigen <- eigen(Theta,symmetric=TRUE) Eigen$values[Eigen$values<0] <- 0 npc <- sum(Eigen$values>0) if(npc >1){ Theta <- matrix.multiply(Eigen$vectors[,1:npc],Eigen$values[1:npc])%*%t(Eigen$vectors[,1:npc]) Theta_half <- matrix.multiply(Eigen$vectors[,1:npc],sqrt(Eigen$values[1:npc])) } if(npc==1){ Theta <- Eigen$values[1]*suppressMessages(kronecker(Eigen$vectors[,1],t(Eigen$vectors[,1]))) Theta_half <- sqrt(Eigen$values[1])*Eigen$vectors[,1] } Eigen <- eigen(Theta,symmetric=TRUE) Bnew = spline.des(knots=knots, x=tnew, ord = p+1,outer.ok = TRUE,sparse=TRUE)$design Gmat <- crossprod(Bnew) / nrow(Bnew) eig_G <- eigen(Gmat, symmetric = T) G_half <- eig_G$vectors %*% diag(sqrt(eig_G$values)) %*% t(eig_G$vectors) G_invhalf <- eig_G$vectors %*% diag(1/sqrt(eig_G$values)) %*% t(eig_G$vectors) Chat.new = as.matrix(tcrossprod(Bnew%*%Matrix(Theta),Bnew)) Chat.diag.new = as.vector(diag(Chat.new)) Cor.new = diag(1/sqrt(Chat.diag.new))%*%Chat.new%*%diag(1/sqrt(Chat.diag.new)) Eigen.new = eigen(as.matrix(G_half%*%Matrix(Theta)%*%G_half),symmetric=TRUE) npc = which.max(cumsum(Eigen$values)/sum(Eigen$values)>pve)[1] eigenfunctions = matrix(Bnew%*%G_invhalf%*%Eigen.new$vectors[,1:min(npc,length(tnew))],ncol=min(npc,length(tnew))) eigenvalues = Eigen.new$values[1:min(npc,length(tnew))] var.error.hat <- rep(sigma2,length(t)) var.error.new <- rep(sigma2,length(tnew)) Chat.raw.new = as.matrix(tcrossprod(Bnew%*%Matrix(Theta),Bnew)) + diag(var.error.new) Chat.raw.diag.new = as.vector(diag(Chat.raw.new)) Cor.raw.new = diag(1/sqrt(Chat.raw.diag.new))%*%Chat.raw.new%*%diag(1/sqrt(Chat.raw.diag.new)) if(!is.null(newdata)){ mu.pred <- rep(0,length(newdata$argvals)) var.error.pred <- rep(sigma2,length(newdata$argvals)) if(center){ mu.pred <- predict.pspline.face(fit_mean,newdata$argvals) } subj.pred = newdata$subj subj_unique.pred = unique(subj.pred) y.pred = newdata$y Chat.diag.pred = 0*y.pred se.pred = 0*y.pred scores = list(subj=subj_unique.pred, scores = matrix(NA,nrow=length(subj_unique.pred),ncol=npc), u = matrix(NA,nrow=length(subj_unique.pred),ncol=nrow(Theta)) ) for(i in 1:length(subj_unique.pred)){ sel.pred = which(subj.pred==subj_unique.pred[i]) lengthi = length(sel.pred) pred.points <- newdata$argvals[sel.pred] mu.predi <- mu.pred[sel.pred] var.error.predi <- var.error.pred[sel.pred] y.predi = y.pred[sel.pred] - mu.predi sel.pred.obs = which(!is.na(y.predi)) obs.points <- pred.points[sel.pred.obs] if(!is.null(obs.points)){ var <- mean(var.error.predi[sel.pred.obs]) if(var==0&length(sel.pred.obs) < npc) stop("Measurement error estimated to be zero and there are fewer observed points thans PCs; scores cannot be estimated.") B3i.pred = spline.des(knots=knots, x=pred.points, ord = p+1,outer.ok = TRUE,sparse=TRUE)$design B3i = spline.des(knots=knots, x=obs.points, ord = p+1,outer.ok = TRUE,sparse=TRUE)$design Chati = tcrossprod(B3i%*%Theta,B3i) Chat.diag.pred[sel.pred] = diag(Chati) if(length(sel.pred.obs)==1) Ri = var.error.predi[sel.pred.obs] if(length(sel.pred.obs)>1) Ri = diag(var.error.predi[sel.pred.obs]) Vi.inv = as.matrix(solve(Chati + Ri)) Vi.pred = tcrossprod(B3i.pred%*%Theta,B3i.pred) Hi = as.matrix(B3i.pred%*%tcrossprod(Theta,B3i)%*%Vi.inv) ui =tcrossprod(Theta,B3i)%*%Vi.inv %*%y.predi[sel.pred.obs] scores$u[i,] = as.vector(ui) y.pred[sel.pred] = as.numeric(Hi%*%y.predi[sel.pred.obs]) + mu.predi temp = as.matrix(B3i.pred%*%tcrossprod(Theta,B3i)) if(length(sel.pred.obs) >1){ se.pred[sel.pred] = sqrt(diag(Vi.pred - temp%*%Vi.inv%*%t(temp))) } if(length(sel.pred.obs) ==1){ se.pred[sel.pred] = sqrt(Vi.pred[1,1] - Vi.inv[1,1]*temp%*%t(temp)) } if(calculate.scores==TRUE){ temp = matrix(t(eigenfunctions),nrow=npc)%*%(as.matrix(Bnew)%*%ui)/sum(eigenfunctions[,1]^2) temp = as.matrix(temp) scores$scores[i,1:npc] = temp[,1] } } } } if(is.null(newdata)){ y.pred=NULL mu.pred = NULL var.error.pred = NULL Chat.diag.pred = NULL se.pred = NULL scores=NULL } res <- list(newdata=newdata, W = W, y.pred = y.pred, Theta=Theta,argvals.new=tnew, mu.new = mu.new, Chat.new=Chat.new, var.error.new = var.error.new, Cor.new = Cor.new, eigenfunctions = eigenfunctions, eigenvalues = eigenvalues, Cor.raw.new = Cor.raw.new, Chat.raw.diag.new = Chat.raw.diag.new, scores = scores, calculate.scores=calculate.scores, mu.hat = fit_mean$fitted.values,var.error.hat = var.error.hat, mu.pred = mu.pred, var.error.pred = var.error.pred, Chat.diag.pred = Chat.diag.pred, se.pred = se.pred, fit_mean = fit_mean, lambda_mean=fit_mean$lambda, lambda=lambda,Gcv=Gcv,Lambda=Lambda,knots=knots,knots.option=knots.option,s=s,npc=npc, p = p, m=m, center=center,pve=pve,sigma2=sigma2, r = r, DtD = DtD, U = Eigen.new$vectors[,1:npc],G_invhalf = G_invhalf) class(res) <- "face.sparse" return(res) }
expected <- eval(parse(text="NULL")); test(id=0, code={ argv <- eval(parse(text="list(c(7.50863122075491e-09, 1.87762632589663e-07, 2.29589583061716e-06, 1.83002461474278e-05, 0.000106962770210119, 0.000488992941332962, 0.00182154707835978, 0.0056884235091347, 0.0152093632759767, 0.0353957474549943, 0.0726726073416657, 0.13316547411151))")); do.call(`oldClass`, argv); }, o=expected);
mstdesign <- " B1 =~ paste0('i',1:5) B2 =~ c(i6, i7, i8, i9, i10) B3 =~ c(i11, i12, i13, i14, i15) B4 =~ c(i16, i17, i18, i19, i20) B5 =~ c(i21, i22, i23, i24, i25) B6 =~ c(i26, i27, i28, i29, i30) b1 := B4(0,2) + B2(0,2) + B1(0,5) b2 := B4(0,2) + B2(3,5) + B3(0,5) b3 := B4(3,5) + B5(0,2) + B3(0,5) b4 := B4(3,5) + B5(3,5) + B6(0,5) " dat <- tmt:::sim.rm(100, 5, 1111) colnames(dat) <- paste0("i",seq_len(ncol(dat))) datna <- dat datna[sample(seq_len(length(datna)),50,replace = FALSE)] <- NA datrm_1 <- tmt_rm(dat, optimization="optim") items <- seq(-2,2, length.out = 30) names(items) <- c(paste0("i",seq_len(30))) dat_mst <- tmt_sim(mstdesign = mstdesign, items = items, persons = 500, seed = 1111) datrm_1a <- tmt_rm(dat, optimization = "optim") datrm_1b <- tmt_rm(data.frame(dat), optimization = "optim") datrm_1c <- tmt_rm(dat, optimization = "nlminb") datrm_2a <- tmt_rm(dat_mst$data, mstdesign = mstdesign, optimization = "optim") datrm_2b <- tmt_rm(dat_mst, optimization = "optim") datrm_2c <- tmt_rm(dat_mst, optimization = "nlminb") context("test-raschmodel") test_that("raschmodel.mst data structure", { expect_is(datrm_2a,"mst") expect_equal(datrm_1a$betapar,datrm_1b$betapar) expect_equal(datrm_1a$se.beta,datrm_1b$se.beta) expect_equal(datrm_2a$betapar,datrm_2b$betapar) expect_equal(datrm_2a$se.beta,datrm_2b$se.beta) }) test_that("raschmodel se", { expect_that(tmt_rm(dat, se = FALSE, optimization = "optim")$se.beta, equals(NULL)) expect_that(tmt_rm(dat, se = FALSE, optimization = "nlminb")$se.beta, equals(NULL)) expect_that(tmt_rm(datna, se = FALSE, optimization = "optim")$se.beta, equals(NULL)) expect_that(tmt_rm(datna, se = FALSE, optimization = "nlminb")$se.beta, equals(NULL)) expect_that(tmt_rm(dat_mst, se = FALSE, optimization = "optim")$se.beta, equals(NULL)) expect_that(tmt_rm(dat_mst, se = FALSE, optimization = "nlminb")$se.beta, equals(NULL)) }) test_that("raschmodel compare results nlminb and optim", { expect_equal( tmt_rm(dat, optimization = "optim")$betapar, tmt_rm(dat, optimization = "nlminb")$betapar, tolerance = 0.001) expect_equal( tmt_rm(datna, optimization = "optim")$betapar, tmt_rm(datna, optimization = "nlminb")$betapar, tolerance = 0.001) expect_equal( tmt_rm(dat_mst, optimization = "optim")$betapar, tmt_rm(dat_mst, optimization = "nlminb")$betapar, tolerance = 0.01) expect_equal( tmt_rm(dat, optimization = "optim")$se.beta, tmt_rm(dat, optimization = "nlminb")$se.beta, tolerance = 0.001) expect_equal( tmt_rm(dat_mst, optimization = "optim")$se.beta, tmt_rm(dat_mst, optimization = "nlminb")$se.beta, tolerance = 0.001) }) context("test-raschmodel check warnings") test_that("error raschmodel.mst",{ expect_that(tmt_rm(list(dat_mst$data),mstdesign=mstdesign, optimization="optim"),throws_error()) expect_that(tmt_rm(list(dat_mst$data),mstdesign=mstdesign), throws_error()) expect_that(tmt_rm(dat_mst,mstdesign=mstdesign, start = rep(0,10)), throws_error()) expect_that(raschmodel.mst(dat_mst$data,mstdesign=NULL), throws_error()) }) test_that("error raschmodel.nmst",{ expect_that(suppressWarnings(raschmodel.nmst(datrm_1a, start = rep(0,10))), throws_error()) expect_that(suppressWarnings(raschmodel.nmst(dat, start = rep(0,10))), throws_error()) }) context("test-raschmodel check errors") test_that("test-raschmodel mst wrong item names", { dat_mst_5 <- dat_mst_4 <- dat_mst_3 <- dat_mst dat_mst_4$data[!is.na(dat_mst_4$data[,1]),1] <- 0 dat_mst_5$data[3:500,] <- 0 colnames(dat_mst_3$data)[1] <- "ii1" expect_that(raschmodel.mst(dat_mst_3, optimization="optim"), throws_error()) expect_that(tmt_rm(dat, optimization="optimo"), throws_error()) expect_that(tmt_rm(dat_mst, optimization="optimo"), throws_error()) expect_that(suppressWarnings(tmt_rm(dat_mst_4)), throws_error()) expect_that(suppressWarnings(tmt_rm(dat_mst_5)), throws_error()) })
register_class("tis") ts_tis_dts <- function(x) { stopifnot(requireNamespace("tis")) x.ts <- ts_ts(x) x.tis <- tis::as.tis(x.ts) colnames(x.tis) <- colnames(x.ts) x.tis } ts_dts.tis <- function(x) { stopifnot(requireNamespace("tis")) ts_dts(as.ts(x)) } ts_tis <- function(x) { stopifnot(ts_boxable(x)) if (relevant_class(x) == "tis") return(x) ts_tis_dts(ts_dts(x)) }
read.fas <- function(x, text){ if (!missing(text)){ x <- text } else { x <- scan(x, what = character(), quiet = TRUE) } if (!length(x)) stop("file is empty") start <- grep("^ {0,}>", x) h <- unlist(strsplit(x[start][1], "")) if (length(h) == 1){ taxnames <- x[start + 1] nlines_metadata <- 2 } else { nlines_metadata <- diff(start[1:2]) - 1 if (nlines_metadata > 2){ id <- lapply(start, function(start, n) start + (1:n) - 1, n = nlines_metadata) taxnames <- sapply(id, function(id, x) paste(x[id], collapse = "_"), x = x) } else { taxnames <- x[start] } taxnames <- gsub(">", "", taxnames) } ntax <- length(taxnames) start <- c(start, length(x) + 1) obj <- vector("list", ntax) for (i in 1:ntax){ obj[[i]] <- unlist(strsplit(gsub(" ", "", x[(start[i] + nlines_metadata):(start[i + 1] - 1)]), NULL)) } names(obj) <- taxnames aa_string <- c("Q","E","I","L","F","P","U","O","J","Z","X","*") if (any(toupper(unlist(obj)) %in% aa_string)){ obj <- as.AAbin(obj) } else { obj <- lapply(obj, tolower) obj <- as.DNAbin(obj) } if (length(unique(sapply(obj, length))) == 1) obj <- as.matrix(obj) return(obj) }
library(testthat) library(purrr) test_check("purrr")
app_save <- function(app, path = tempfile(), env = parent.frame()) { if (!is_installed("globals")) { abort(c( "globals package required to test app object", i = "Do you need to run `install.packages('globals')`" )) } if (!dir.exists(path)) { dir.create(path) } file.copy( system.file("app-template.R", package = "shinytest"), file.path(path, "app.R") ) data <- app_data(app, env) saveRDS(data, file.path(path, "data.rds")) path } app_data <- function(app, env = parent.frame()) { server <- app$serverFuncSource() globals <- app_server_globals(server, env) data <- globals$globals data$ui <- environment(app$httpHandler)$ui data$server <- server data$resources <- shiny::resourcePaths() data$packages <- globals$packages data } app_server_globals <- function(server, env = parent.frame()) { env <- new.env(parent = env) env$output <- NULL globals <- globals::globalsOf(server, envir = env, recursive = FALSE) globals <- globals::cleanup(globals) pkgs <- globals::packagesOf(globals) in_package <- vapply( attr(globals, "where"), function(x) !is.null(attr(x, "name")), logical(1) ) globals <- globals[!in_package] attributes(globals) <- list(names = names(globals)) globals$output <- NULL list( globals = globals, packages = pkgs ) }
context("Testing 'efetch()'") if (getOption('reutils.test.remote')) { test_that("Fetch PMIDs 17284678 and 9997 as text abstracts", { a <- efetch(uid = c(17284678, 9997), db = 'pubmed', rettype = 'abstract') expect_equal(retmode(a), "text") expect_equal(rettype(a), "abstract") expect_is(content(a), 'character') expect_is(content(a, "text"), 'character') expect_error(content(a, 'xml'), "Cannot return data of retmode.+") expect_error(content(a, 'json'), "Cannot return data of retmode.+") expect_is(content(a, 'parsed'), 'character') expect_is(content(a, 'textConnection'), 'textConnection') }) test_that("Fetch PMIDs 17284678 and 9997 as XML", { a <- efetch(c(17284678, 9997), 'pubmed', retmode = 'xml') expect_equal(retmode(a), "xml") expect_equal(rettype(a), "") expect_is(content(a), 'XMLInternalDocument') expect_is(content(a, "text"), 'character') expect_is(content(a, 'xml'), "XMLInternalDocument") expect_error(content(a, 'json'), "Cannot return data of retmode.+") expect_is(content(a, 'parsed'), 'XMLInternalDocument') expect_error(content(a, 'textConnection'), "Cannot return data of retmode.+") }) test_that("Fetch 100 bases of the minus strand of GI 21614549", { a <- efetch('21614549', 'nuccore', strand = 1, seqstart = 1, seqstop = 100, rettype = "fasta", retmode = "text") expect_equal(retmode(a), "text") expect_equal(rettype(a), "fasta") expect_equal(nchar(paste0(strsplit(content(a), '\n')[[1]][-1], collapse = "")), 100) }) test_that("efetch works with UIDs provided as character or numeric vectors", { a <- efetch(c(28800982, 28628843), "protein", "fasta") if (!all(is.na(a$xmlName("//TSeqSet/*")))) { expect_equal(a$xmlName("//TSeqSet/*"), c("TSeq", "TSeq")) } }) test_that("efetch works with an esearch object as input", { x <- esearch("erythroid associated factor AND Homo sapiens", 'protein', retmax = 2) a <- efetch(x, rettype = "fasta") if (!all(is.na(a$xmlValue("//TSeq_taxid")))) { expect_equal(a$xmlValue("//TSeq_taxid"), c("9606", "9606")) } }) }
expected <- eval(parse(text="2L")); test(id=0, code={ argv <- eval(parse(text="list(c(-167.089651989438, -122.420302709026))")); do.call(`length`, argv); }, o=expected);
test_that("vld_unused", { expect_true(vld_unused()) expect_false(vld_unused(1)) }) test_that("chk_unused", { expect_null(chk_unused()) expect_invisible(chk_unused()) expect_chk_error(chk_unused(1), "^`...` must be unused[.]$") }) test_that("vld_used", { expect_true(vld_used(1)) expect_false(vld_used()) }) test_that("chk_used", { expect_null(chk_used(1)) expect_invisible(chk_used(1)) expect_chk_error(chk_used(), "^`...` must be used[.]$") })
expected <- eval(parse(text="c(1-0i, 1+0i, 1+0i, 9.99999999999989e-01-5e-15i, 1+0i, 1+0i, 1-0i, 1e+00+9e-16i, 9.99999999999999e-01+3e-15i, 9.99999999999997e-01-3e-15i, 1e+00-1e-15i, 1+0i, 1+0i, 1e+00+1e-15i, 1+0i, 1+0i, 1+0i, 1-0i, 1+0i, 1e+00-5e-15i, 1-0i, 1+0i, 1+0i, 1+0i)")); test(id=0, code={ argv <- eval(parse(text="list(c(1-0i, 1+0i, 1+0i, 9.99999999999989e-01-5e-15i, 1+0i, 1+0i, 1-0i, 1e+00+9e-16i, 9.99999999999999e-01+3e-15i, 9.99999999999997e-01-3e-15i, 1e+00-1e-15i, 1+0i, 1+0i, 1e+00+1e-15i, 1+0i, 1+0i, 1+0i, 1-0i, 1+0i, 1e+00-5e-15i, 1-0i, 1+0i, 1+0i, 1+0i))")); do.call(`(`, argv); }, o=expected);
mkDummy <- function(x) { xN <- deparse(substitute(x)) if (!inherits(x,"factor")) stop("x should be a factor") lev <- levels(x) result <- lapply(lev,function(l) as.integer(x==l)) names(result) <- paste(xN,".",lev,sep="") result }
read_filet <- function(file_name,col_types=NULL,col_names=NULL,na_strings=NULL){ raw_lines <- readLines(file_name) experiment <- raw_lines %>% str_subset('\\*EXP\\. *DATA *\\([AT]\\): *') %>% str_remove('\\*EXP\\. *DATA *\\([AT]\\): *') comments <- extract_comments(raw_lines) col_types <- cols(` TRNO `=col_double()) %>% {.$cols <- c(.$cols,col_types$cols);.} filet <- read_tier(raw_lines = raw_lines, col_types = col_types, col_names = c(col_names,' TRNO '), na_strings=na_strings) trno_date_cols <- intersect(c('TRNO','DATE'),colnames(filet)) if(length(trno_date_cols) > 0 ){ filet <- filet %>% arrange_at(trno_date_cols) } attr(filet,'experiment') <- experiment attr(filet,'comments') <- comments filet <- as_DSSAT_tbl(filet) return(filet) }
"COL"
maxlikec <- function(z, x, data=NULL, effects=NULL, returnChains=FALSE, byGroup=FALSE, byWave=FALSE, returnDataFrame=FALSE, returnLoglik=FALSE, onlyLoglik=FALSE) { f <- FRANstore() callGrid <- z$callGrid if (nrow(callGrid) == 1) { if (byGroup) { theta <- z$thetaMat[1,] } else { theta <- z$theta } ans <- .Call(C_mlPeriod, PACKAGE=pkgname, z$Deriv, f$pData, f$pModel, f$myeffects, theta, 1, 1, z$nrunMH, z$addChainToStore, z$returnDataFrame, z$returnDeps, z$returnChains, returnLoglik, onlyLoglik) if (!onlyLoglik) { ans[[6]] <- list(ans[[6]]) ans[[7]] <- list(ans[[7]]) if (byGroup) { ans[[8]] <- list(ans[[8]]) ans[[9]] <- list(ans[[9]]) ans[[10]] <- list(ans[[10]]) ans[[11]] <- list(ans[[11]]) } } else { ans[[2]] <- list(ans[[2]]) ans[[3]] <- list(ans[[3]]) ans[[4]] <- list(ans[[4]]) } if (z$returnDeps) { sims <- ans[[12]] } else { sims <- 'there are no simulated dependent variables' } } else { if (z$int2 == 1) { anss <- apply(cbind(callGrid, 1:nrow(callGrid)), 1, doMLModel, z$Deriv, z$thetaMat, z$nrunMH, z$addChainToStore, z$returnDataFrame, z$returnDeps, z$returnChains, byGroup, z$theta, returnLoglik, onlyLoglik) } else { use <- 1:(min(nrow(callGrid), z$int2)) anss <- parRapply(z$cl[use], cbind(callGrid, 1:nrow(callGrid)), doMLModel, z$Deriv, z$thetaMat, z$nrunMH, z$addChainToStore, z$returnDataFrame, z$returnDeps, z$returnChains, byGroup, z$theta, returnLoglik, onlyLoglik) } ans <- list() if (!onlyLoglik) { ans[[1]] <- sapply(anss, "[[", 1) ans[[2]] <- NULL ans[[3]] <- NULL ans[[4]] <- NULL ans[[5]] <- NULL if (z$returnChains) { fff <- lapply(anss, function(x) x[[6]][[1]]) fff <- split(fff, callGrid[, 1 ]) ans[[6]] <- fff } ans[[7]] <- lapply(anss, "[[", 7) ans[[8]] <- lapply(anss, "[[", 8) ans[[9]] <- lapply(anss, "[[", 9) ans[[10]] <- lapply(anss, "[[", 10) if (!byGroup) { ans[[8]] <- Reduce("+", ans[[8]]) ans[[9]] <- Reduce("+", ans[[9]]) ans[[10]] <- Reduce("+", ans[[10]]) } ans[[11]] <- sapply(anss, "[[", 11) if (z$returnDeps) { fff <- lapply(anss, function(x) x[[12]]) sims <- split(fff, callGrid[, 1 ]) } else { sims <- 'no simulated dependent variables' } } else { ans[[1]] <- sum(sapply(anss, '[[', 1)) ans[[2]] <- lapply(anss, "[[", 2) ans[[3]] <- lapply(anss, "[[", 3) ans[[4]] <- lapply(anss, "[[", 4) } } FRANstore(f) if (z$Deriv && !onlyLoglik) { resp <- reformatDerivs(z, f, ans[[7]]) dff <- resp[[1]] dff2 <- resp[[2]] } else { dff <- NULL dff2 <- NULL } if (!onlyLoglik) { fra <- -t(ans[[1]]) list(fra = fra, ntim0 = NULL, feasible = TRUE, OK = TRUE, sims=sims, dff=dff, dff2=dff2, chain = ans[[6]], accepts=ans[[8]], rejects= ans[[9]], aborts=ans[[10]], loglik=ans[[11]]) } else { list(loglik=ans[[1]], accepts=ans[[2]], rejects= ans[[3]], aborts=ans[[4]]) } } doMLModel <- function(x, Deriv, thetaMat, nrunMH, addChainToStore, returnDataFrame, returnDeps, returnChains, byGroup, theta, returnLoglik, onlyLoglik) { f <- FRANstore() if (byGroup) { theta <- thetaMat[x[1], ] } else { theta <- theta } .Call(C_mlPeriod, PACKAGE=pkgname, Deriv, f$pData, f$pModel, f$myeffects, theta, as.integer(x[1]), as.integer(x[2]), nrunMH[x[3]], addChainToStore, returnDataFrame, returnDeps, returnChains, returnLoglik, onlyLoglik) } reformatDerivs <- function(z, f, derivList) { dff <- as(matrix(0, z$pp, z$pp), "dsyMatrix") nPeriods <- length(derivList) dff2 <- vector("list", nPeriods) if (z$byWave) { tmp <- as(matrix(0, z$pp, z$pp), "dsyMatrix") dff2[] <- tmp } for (period in 1:nPeriods) { dffraw <- derivList[[period]] start <- 1 rawsub <- 1 for (i in 1:length(f$myeffects)) { dffPeriod <- matrix(0, nrow=z$pp, ncol=z$pp) rows <- nrow(f$myeffects[[i]]) nRates <- sum(f$myeffects[[i]]$type == 'rate') nonRates <- rows - nRates dffPeriod[cbind(start:(start + nRates -1), start:(start + nRates - 1))] <- dffraw[rawsub:(rawsub + nRates - 1)] start <- start + nRates rawsub <- rawsub + nRates dffPeriod[start : (start + nonRates - 1 ), start : (start + nonRates - 1)] <- dffraw[rawsub:(rawsub + nonRates * nonRates - 1)] start <- start + nonRates rawsub <- rawsub + nonRates * nonRates dffPeriod <- dffPeriod + t(dffPeriod) diag(dffPeriod) <- diag(dffPeriod) / 2 if (z$byWave) { dff2[[period]] <- dff2[[period]] - dffPeriod } dff <- dff - dffPeriod } } list(dff, dff2) }
fixParents <- function (id, dadid, momid, sex, missid = 0) { n <- length(id) if (length(momid) != n) stop("Mismatched lengths, id and momid") if (length(dadid) != n) stop("Mismatched lengths, id and momid") if (length(sex) != n) stop("Mismatched lengths, id and sex") if (is.factor(sex)) sex <- as.character(sex) codes <- c("male", "female", "unknown", "terminated") if (is.character(sex)) { sex <- charmatch(casefold(sex, upper = FALSE), codes, nomatch = 3) } sex <- as.integer(sex) if (min(sex) == 0) { warning("Sex values contain 0, but expected codes 1-4.\n Setting 0=male, 1=female, 2=unknown, 3=terminated. \n") sex <- sex + 1 } sex <- ifelse(sex < 1 | sex > 4, 3, sex) if (all(sex > 2)) stop("Invalid values for 'sex'") else if (mean(sex == 3) > 0.25) warning("More than 25% of the gender values are 'unknown'") if (missing(missid)) { if (is.numeric(id)) missid <- 0 else missid <- "" } if (any(is.na(id))) stop("Missing value for the id variable") if (!is.numeric(id)) { id <- as.character(id) addids <- paste("addin", 1:length(id), sep = "-") dadid <- as.character(dadid) momid <- as.character(momid) missid <- as.character(missid) if (length(grep("^ *$", id)) > 0) stop("A blank or empty string is not allowed as the id variable") } else { addids <- seq(max(id, na.rm = TRUE) + 1, max(id, na.rm = TRUE) + length(id)) } nofather <- (is.na(dadid) | dadid == missid) nomother <- (is.na(momid) | momid == missid) if (any(duplicated(id))) { duplist <- id[duplicated(id)] msg.n <- min(length(duplist), 6) stop(paste("Duplicate subject id:", duplist[1:msg.n])) } findex <- match(dadid, id, nomatch = 0) mindex <- match(momid, id, nomatch = 0) if (any(findex == 0 & !nofather)) { dadnotfound <- unique(dadid[which(findex == 0 & !nofather)]) id <- c(id, dadnotfound) sex <- c(sex, rep(1, length(dadnotfound))) dadid <- c(dadid, rep(0, length(dadnotfound))) momid <- c(momid, rep(0, length(dadnotfound))) } if (any(mindex == 0 & !nomother)) { momnotfound <- unique(momid[which(mindex == 0 & !nomother)]) id <- c(id, momnotfound) sex <- c(sex, rep(2, length(momnotfound))) dadid <- c(dadid, rep(0, length(momnotfound))) momid <- c(momid, rep(0, length(momnotfound))) } if (any(sex[mindex] != 1)) { dadnotmale <- unique((id[findex])[sex[findex] != 1]) sex[id %in% dadnotmale] <- 1 } if (any(sex[mindex] != 2)) { momnotfemale <- unique((id[mindex])[sex[mindex] != 2]) sex[id %in% momnotfemale] <- 2 } findex <- match(dadid, id, nomatch = 0) mindex <- match(momid, id, nomatch = 0) addids <- addids[!(addids %in% id)] if (any(findex == 0 & mindex != 0)) { nodad.idx <- which(findex == 0 & mindex != 0) dadid[nodad.idx] <- addids[1:length(nodad.idx)] id <- c(id, addids[1:length(nodad.idx)]) sex <- c(sex, rep(1, length(nodad.idx))) dadid <- c(dadid, rep(0, length(nodad.idx))) momid <- c(momid, rep(0, length(nodad.idx))) } addids <- addids[!(addids %in% id)] if (any(mindex == 0 & findex != 0)) { nomom.idx <- which(mindex == 0 & findex != 0) momid[nomom.idx] <- addids[1:length(nomom.idx)] id <- c(id, addids[1:length(nomom.idx)]) sex <- c(sex, rep(2, length(nomom.idx))) dadid <- c(dadid, rep(0, length(nomom.idx))) momid <- c(momid, rep(0, length(nomom.idx))) } return(data.frame(id = id, momid = momid, dadid = dadid, sex = sex)) }
boolSkip=F test_that("Check 14.1 - weightedMajorityGameValue ",{ if(boolSkip){ skip("Test was skipped") } S=c(1,2) w=c(1,2,2) q = 4 result=weightedVotingGameValue(S, w, q) expect_equal(result,0) }) test_that("Check 14.2 - weightedMajorityGameValue ",{ if(boolSkip){ skip("Test was skipped") } S=c(1,2) w=c(1:5) q = 4 result=weightedVotingGameValue(S, w, q) expect_equal(result,0) }) test_that("Check 14.3 - weightedMajorityGameValue ",{ if(boolSkip){ skip("Test was skipped") } S=c(1,2) w=c(1:5) q = 4 result=weightedVotingGameValue(S, w, q) expect_equal(result,0) })
minimal.cover <- function(z) minimal.incidence(cover2incidence(z))
ROCscore<-function(xobs, yobs, type="output") { n1<-nrow(xobs) p.input<-ncol(xobs) if(n1!=nrow(yobs)) stop("xobs and yobs have not the same number of observations") match.arg(type,c("output","input","hyper")) alpha=seq(0.01,1,by=0.01) m=c(1,5,8,11,14,17,20,23,26,29,32,35,40,45,50,55,60,65,70,75,80,85,90,95,seq(100,2500,length.out=76)) perf1=NULL perf2=NULL for(k in 1:length(alpha)) { res1<-alphascore(xobs,yobs, alpha=alpha[k])[,type] res2<-ordermscore(xobs,yobs, m=m[k])[,type] perf1=c(perf1,length(which(res1>1))/n1) perf2=c(perf2,length(which(res2>1))/n1) } plot(alpha,perf1,type='l',xlab="alpha",ylab="Percentage of super-efficiency firms",ylim=c(0,1),col='royalblue') par(new=TRUE) plot(m, perf2,type='l',lty=2, ann = FALSE, yaxt = "n", xaxt="n",yaxt="n",ylim=c(0,1),col='red') axis(3) mtext(side=3,"m") legend("topright",legend=c("f(alpha)","f(m)"),lty=1:2,col=c("royalblue","red")) res<-data.frame(alpha,perf1,m,perf2) names(res)=c("alpha","f(alpha)","m","f(m)") return(res) }
GADAG_Run <- function(X, lambda, threshold=0.1, GADAG.control = list(n.gen=100, tol.Shannon=1e-6, max.eval=1e4,pop.size=10, p.xo=.25, p.mut=.05), grad.control = list(tol.obj.inner=1e-6, max.ite.inner=50), ncores=1,print.level=0, return.level=0) { if (is.null(GADAG.control$n.gen)){ n.gen <- 100 } else { n.gen <- GADAG.control$n.gen } if (is.null(GADAG.control$max.eval)){ max.eval <- 1e4 } else { max.eval <- GADAG.control$max.eval } if (is.null(GADAG.control$tol.Shannon)){ tol.Shannon <- 1e-6 } else { tol.Shannon <- GADAG.control$tol.Shannon } if (is.null(GADAG.control$pop.size)){ pop.size <- 10 } else { pop.size <- GADAG.control$pop.size } if (is.null(GADAG.control$p.xo)){ p.xo <- 0.25 } else { p.xo <- GADAG.control$p.xo } if (is.null(GADAG.control$p.mut)){ p.mut <- 0.05 } else { p.mut <- GADAG.control$p.mut } if (is.null(grad.control$tol.obj.inner)){ grad.control$tol.obj.inner <- 1e-6 } else { grad.control$tol.obj.inner <- grad.control$tol.obj.inner } if (is.null(grad.control$max.ite.inner)){ grad.control$max.ite.inner <- 50 } else { grad.control$max.ite.inner <- grad.control$max.ite.inner } if (grad.control$max.ite.inner < 0){ stop("grad.control$max.ite.inner should be non-negative.") } n <- dim(X)[1] p <- dim(X)[2] XtX <- crossprod(X) Pop <- create.population(p, pop.size) evalTandf <- evaluation(Pop, X, XtX, lambda, grad.control = grad.control, ncores=ncores) f.pop <- evalTandf$f T.pop <- evalTandf$Tpop f.count <- pop.size Shannon.val <- rep(0,p) for (j in (1:p)){ frac <- colMeans(Pop==j) h <- frac*log(frac) h[is.nan(h)] <- 0 Shannon.val[j] <- -sum(h) } pop.best <- which.min(f.pop) f.best.alltimes <- min(f.pop) P.best.alltimes <- Pop[pop.best,] T.best.alltimes <- T.pop[pop.best,] if (return.level != 0) { fmin.pop.save <- rep(0, n.gen) fmean.pop.save <- rep(0, n.gen) fp10.pop.save <- rep(0, n.gen) fp90.pop.save <- rep(0, n.gen) fmin.pop.save[1] <- min(f.pop) fmean.pop.save[1] <- mean(f.pop) fp10.pop.save[1] <- quantile(f.pop, probs = .1) fp90.pop.save[1] <- quantile(f.pop, probs = .9) f.best.alltimes.save <- rep(0, n.gen) P.best.alltimes.save <- matrix(data = 0, nrow = n.gen, ncol = p) T.best.alltimes.save <- matrix(data = 0, nrow = n.gen, ncol = p^2) f.best.alltimes.save[1] <- f.best.alltimes P.best.alltimes.save[1,] <- P.best.alltimes T.best.alltimes.save[1,] <- T.best.alltimes Shannon.save <- matrix(data = 0, nrow = n.gen, ncol = p) Shannon.save[1,] <- Shannon.val } k <- 1 if ((print.level != 0) ) cat("Nb gen | best f | average (sd) f in pop | Shannon | f count \n") while (k < n.gen && sum(Shannon.val) > tol.Shannon && f.count<max.eval){ if (print.level != 0) cat(k, f.best.alltimes, mean(f.pop), "(", sd(f.pop), ")", sum(Shannon.val), f.count, "\n") I <- selection(Pop, f.pop) Results.crossover <- crossover(Pop=Pop[I,],p.xo=p.xo) Children <- Results.crossover$Children I.cross <- Results.crossover$I.cross if (length(I.cross)>1){ Children <- mutation(Children, p.mut=p.mut) evalTandfe <- evaluation(Pop=Children, X=X, XtX=XtX, lambda=lambda, grad.control=grad.control, ncores=ncores) I.cross <- I[I.cross] Pop[I.cross,] <- Children f.pop[I.cross] <- evalTandfe$f T.pop[I.cross,] <- evalTandfe$Tpop } pop.worst <- which.max(f.pop) f.pop[pop.worst] <- f.best.alltimes Pop[pop.worst,] <- P.best.alltimes T.pop[pop.worst,] <- T.best.alltimes f.count <- f.count + length(I.cross) + p-1 k <- k + 1 Shannon.val <- rep(0,p) for (j in (1:p)){ frac <- colMeans(Pop==j) h <- frac*log(frac) h[is.nan(h)] <- 0 Shannon.val[j] <- -sum(h) } pop.best <- which.min(f.pop) if (min(f.pop) < f.best.alltimes) { f.best.alltimes <- min(f.pop) P.best.alltimes <- Pop[pop.best,] T.best.alltimes <- T.pop[pop.best,] } if (return.level != 0) { fmin.pop.save[k] <- min(f.pop) fmean.pop.save[k] <- mean(f.pop) fp10.pop.save[k] <- quantile(f.pop, probs = .1) fp90.pop.save[k] <- quantile(f.pop, probs = .9) f.best.alltimes.save[k] <- f.best.alltimes P.best.alltimes.save[k,] <- P.best.alltimes T.best.alltimes.save[k,] <- T.best.alltimes Shannon.save[k,] <- Shannon.val } } if (print.level != 0) cat(k, f.best.alltimes, mean(f.pop), "(", sd(f.pop), ")", sum(Shannon.val), f.count, "\n") P <- chrom(P.best.alltimes) T <- matrix(T.best.alltimes,p,p) T[T<threshold] <- 0 G.best <- P %*% T %*% t(P) Gbest.bin <- G.best*0 Gbest.bin[(abs(G.best)>0)] <- 1 if (return.level > 0) { return(list(f.best=f.best.alltimes, P.best=P.best.alltimes, T.best=T.best.alltimes,G.best=G.best, f.best.evol=f.best.alltimes.save[1:k], P.best.evol=P.best.alltimes.save[1:k,], T.best.evol=T.best.alltimes.save[1:k,], fmin.evol=fmin.pop.save[1:k], fmean.evol=fmean.pop.save[1:k], fp10.evol=fp10.pop.save[1:k], fp90.evol=fp90.pop.save[1:k], Shannon.evol=Shannon.save[1:k,])) } else { return(list(f.best=f.best.alltimes, P.best=P.best.alltimes, T.best=T.best.alltimes, G.best=G.best)) } }
S_soft <- function(z,lambda){ return((abs(z) - lambda)*(abs(z) - lambda > 0)*sign(z)) }
fred_tags <- function(key=NULL, args=list()){ if (is.null(key)) key <- .use_default_key() other <- .args_parse(args) .fred_tags(key, other) } fred_related_tags <- function(..., key=NULL, args = list()){ if (is.null(key)) key <- .use_default_key() other <- .args_parse(args) ids <- parse_search(...) .fred_related_tags(ids, key, other) } fred_tags_series <- function(..., key=NULL, args = list()){ if (is.null(key)) key <- .use_default_key() other <- .args_parse(args) ids <- parse_search(...) .fred_tags_series(ids, key, other) }
knitr::opts_chunk$set( warning = FALSE, message = FALSE, collapse = TRUE, comment = " suppressPackageStartupMessages(library(ggplot2)) theme_set(theme_light()) library(dplyr) library(janeaustenr) library(tidytext) library(stringr) tidy_bigrams <- austen_books() %>% unnest_tokens(bigram, text, token="ngrams", n = 2, to_lower = FALSE) %>% filter(!str_detect(bigram, "[A-Z]")) bigram_counts <- tidy_bigrams %>% count(book, bigram, sort = TRUE) bigram_counts library(tidylo) bigram_log_odds <- bigram_counts %>% bind_log_odds(book, bigram, n) bigram_log_odds %>% arrange(-log_odds_weighted) library(ggplot2) bigram_log_odds %>% group_by(book) %>% top_n(10) %>% ungroup %>% mutate(bigram = reorder(bigram, log_odds_weighted)) %>% ggplot(aes(bigram, log_odds_weighted, fill = book)) + geom_col(show.legend = FALSE) + facet_wrap(~book, scales = "free") + coord_flip() + labs(x = NULL) gear_counts <- mtcars %>% count(vs, gear) gear_counts regularized <- gear_counts %>% bind_log_odds(vs, gear, n) regularized unregularized <- gear_counts %>% bind_log_odds(vs, gear, n, uninformative = TRUE, unweighted = TRUE) unregularized
library(testthat) library(hms) test_check("hms")
tidy.mle2 <- function(x, conf.int = FALSE, conf.level = .95, ...) { co <- bbmle::coef(bbmle::summary(x)) ret <- ret <- as_tidy_tibble( co, new_names = c("estimate", "std.error", "statistic", "p.value") ) if (conf.int) { ci <- bbmle::confint(x, level = conf.level) if (is.null(dim(ci))) { ci <- matrix(ci, nrow = 1) } colnames(ci) <- c("conf.low", "conf.high") ci <- as_tibble(ci) ret <- dplyr::bind_cols(ret, ci) } as_tibble(ret) }
local({ gui.file<-function(){ tcltk::tclvalue(file.name) <- tcltk::tcl("tk_getOpenFile") } gui.mask<-function(){ tcltk::tclvalue(mask) <- tcltk::tcl("tk_getOpenFile") } gui.save<-function(...){ assign(tcltk::tclvalue(save.r), tmp.ica.obj, envir = .GlobalEnv) } gui.ica<-function(...){ if(tcltk::tclvalue(mask) == "" && tcltk::tclvalue(create.mask) == 0){ err1 <- tcltk::tktoplevel() err1.f1 <- tcltk::tkframe(err1, relief="groove", borderwidth = 2) err1.label <- tcltk::tklabel(err1.f1, text = "Either select a mask file or select create mask", bg = " tcltk::tkgrid(err1.label) tcltk::tkgrid(err1.f1) return() } if(tcltk::tclvalue(mask) != "" && tcltk::tclvalue(create.mask) == 0) msk <- tcltk::tclvalue(mask) if(tcltk::tclvalue(mask) == "" && tcltk::tclvalue(create.mask) == 1) msk <- NULL v.norm <- 1 if(tcltk::tclvalue(var.norm) == 0) v.norm <- 0 sl <- NULL if(tcltk::tclvalue(slices) == 0) sl <- "all" tmp.ica.obj <<- f.ica.fmri(tcltk::tclvalue(file.name), n.comp = as.numeric(tcltk::tclvalue(n.comp)), norm.col = v.norm, fun = "logcosh", maxit = 100, alg.type = "parallel", alpha = 1, tol = 0.0001, mask.file.name = msk, sl) print("done") } gui.jpeg<-function(...){ f.plot.ica.fmri.jpg(tmp.ica.obj, tcltk::tclvalue(jpeg), width = 700, height = 700)} gui.end<-function(...){ rm(tmp.ica.obj, envir = .GlobalEnv) tcltk::tkdestroy(base.ica) } gui.plot.ica<-function(...){ f.plot.ica.fmri(tmp.ica.obj, as.numeric(tcltk::tclvalue(comp)))} file.name <- tcltk::tclVar() mask <- tcltk::tclVar() n.comp <- tcltk::tclVar("30") var.norm <- tcltk::tclVar("0") slices <- tcltk::tclVar("0") create.mask <- tcltk::tclVar("0") save.r <- tcltk::tclVar() jpeg <- tcltk::tclVar() comp <- tcltk::tclVar() if(.Platform$OS.type == "windows") flush.console() base.ica <- tcltk::tktoplevel(bg=" tcltk::tkwm.title(base.ica, "Spatial ICA for fMRI datasets") ica.f1 <- tcltk::tkframe(base.ica, relief = "groove", borderwidth = 2, bg = " ica.file.entry <- tcltk::tkentry(ica.f1, textvariable = file.name, width = 50, bg = " ica.file.find.but <- tcltk::tkbutton(ica.f1, text = "Select File", width = 15, command = gui.file, bg = " tcltk::tkgrid(ica.file.find.but, ica.file.entry, pady = 10, padx = 10) ica.mask.entry <- tcltk::tkentry(ica.f1, textvariable = mask, width = 50, bg = " ica.mask.find.but <- tcltk::tkbutton(ica.f1, text = "Select Mask File", width = 15, command = gui.mask, bg = " tcltk::tkgrid(ica.mask.find.but, ica.mask.entry, padx = 10, pady = 10) tcltk::tkgrid(ica.f1) ica.f2 <- tcltk::tkframe(base.ica, relief = "groove", borderwidth = 2, bg = " ica.n.comp.label <- tcltk::tklabel(ica.f2, text = "Number of components to extract", bg = " ica.n.comp.entry <- tcltk::tkentry(ica.f2, textvariable = n.comp, width = 5, bg = " tcltk::tkgrid(ica.n.comp.label, ica.n.comp.entry, padx = 10, pady = 10) tcltk::tkgrid(ica.f2, sticky = "ew") ica.f3 <- tcltk::tkframe(base.ica, relief = "groove", borderwidth = 2, bg = " ica.normalise.but <- tcltk::tkcheckbutton(ica.f3, text = "Variance Normalize", bg = " ica.slices.but <- tcltk::tkcheckbutton(ica.f3, text = "Exclude top/bottom slices", bg = " ica.create.mask.but <- tcltk::tkcheckbutton(ica.f3, text = "Create Mask", bg = " tcltk::tkgrid(ica.normalise.but, ica.slices.but, ica.create.mask.but, padx = 30, pady = 10) tcltk::tkgrid(ica.f3, sticky = "ew") ica.f4 <- tcltk::tkframe(base.ica, relief = "groove", borderwidth = 2, bg = " ica.save.entry <- tcltk::tkentry(ica.f4, textvariable = save.r, width = 40, bg = " ica.save.but <- tcltk::tkbutton(ica.f4, text = "Save to R object", width = 15, command = gui.save, bg = " tcltk::tkgrid(ica.save.but, ica.save.entry, padx = 10, pady = 10) tcltk::tkgrid(ica.f4,sticky = "ew") ica.f5 <- tcltk::tkframe(base.ica, relief = "groove", borderwidth = 2, bg = " ica.jpeg.entry <- tcltk::tkentry(ica.f5, textvariable = jpeg, width = 40, bg = " ica.jpeg.but <- tcltk::tkbutton(ica.f5, text = "Save to jpeg files", width = 15, command = gui.jpeg, bg = " tcltk::tkgrid(ica.jpeg.but, ica.jpeg.entry, padx = 10, pady = 10) tcltk::tkgrid(ica.f5, sticky = "ew") ica.f6 <- tcltk::tkframe(base.ica, relief = "groove", borderwidth = 2, bg = " ica.plot.entry <- tcltk::tkentry(ica.f6, textvariable = comp, width = 5, bg = " ica.plot.but <- tcltk::tkbutton(ica.f6, text = "Plot component", width = 15, command = gui.plot.ica, bg = " tcltk::tkgrid(ica.plot.but, ica.plot.entry, padx = 10, pady = 10) tcltk::tkgrid(ica.f6, sticky = "ew") fr3 <- tcltk::tkframe(base.ica, borderwidth = 2, bg = " go.but<- tcltk::tkbutton(fr3, text = "Start", bg = " q.but <- tcltk::tkbutton(fr3, text = "Quit", command = gui.end, bg = " tcltk::tkgrid(go.but, q.but, padx = 30, pady = 20) tcltk::tkgrid(fr3) })
knitr::opts_chunk$set( collapse = TRUE, comment = ' eval = FALSE ) options(scipen = 9999) library(irg) library(data.table) ndvi <- fread(system.file('extdata', 'sampled-ndvi-MODIS-MOD13Q1.csv', package = 'irg')) ?ndvi knitr::kable(ndvi[90:95]) library(DiagrammeR) g <- grViz( " digraph irg_functions { graph [rankdir=LR, compound=TRUE, fontsize = 28] node[shape=none, fontsize=28] subgraph cluster_filt{ label= '1)'; labeljust='l'; Filtering -> filter_ndvi [dir=none] filter_ndvi -> filter_qa [dir=none] filter_ndvi -> filter_winter [dir=none] filter_ndvi -> filter_roll [dir=none] filter_ndvi -> filter_top [dir=none] filter_top -> filter_roll -> filter_winter -> filter_qa [dir=back] {rank=same; filter_qa; filter_winter; filter_roll; filter_top} } subgraph cluster_scal{ label= '2)' labeljust='l'; Scaling -> scale_doy [dir=none] Scaling -> scale_ndvi [dir=none] } subgraph cluster_mod{ label= '3)' labeljust='l'; Modeling -> model_start [dir=none] Modeling -> model_params [dir=none] Modeling -> model_ndvi [dir=none] model_ndvi -> model_params -> model_start [dir=back] {rank=same; model_ndvi; model_params; model_start} } subgraph cluster_irg{ label= '4)' labeljust='l'; IRG -> calc_irg [dir=none] } Filtering -> Scaling -> Modeling -> IRG } ", width = 700, height = 600) g fs <- data.table(functions = as.character(lsf.str('package:irg')))[, arguments := paste(unlist(formalArgs(functions)), collapse = ', ' ), by = functions] out <- irg(ndvi) knitr::kable(out[between(t, 0.4, 0.5)][1:5, .(id, yr, t, fitted, irg)]) knitr::kable(fs[grepl('filter', functions), .(functions, arguments)])
context("test-any") test_that("returns a single value with shaped arrays", { expect_equal(any(rray(c(TRUE, FALSE), c(2, 2))), rray(TRUE)) expect_equal(any(rray(c(FALSE, FALSE), c(2, 2))), rray(FALSE)) }) test_that("`na.rm` propagates", { expect_equal(any(rray(c(NA, 0L)), na.rm = FALSE), rray(NA)) expect_equal(any(rray(c(NA, 0L)), na.rm = TRUE), rray(FALSE)) }) context("test-all") test_that("returns a single value with shaped arrays", { expect_equal(all(rray(c(TRUE, FALSE), c(2, 2))), rray(FALSE)) expect_equal(all(rray(c(TRUE, TRUE), c(2, 2))), rray(TRUE)) }) test_that("`na.rm` propagates", { expect_equal(all(rray(c(NA, 1L)), na.rm = FALSE), rray(NA)) expect_equal(all(rray(c(NA, 1L)), na.rm = TRUE), rray(TRUE)) }) context("test-prod") test_that("returns same values as base R", { x <- rray(c(5, 6), c(2, 2)) expect_equal(prod(x), rray(prod(vec_data(x)))) expect_equal(prod(x, x), rray(prod(vec_data(x), vec_data(x)))) }) test_that("broadcasts input using vctrs", { x <- rray(c(5, 6), c(2, 2)) expect_equal(prod(x, 5), prod(x, matrix(5, c(1, 2)))) }) test_that("`na.rm` propagates", { expect_equal(prod(rray(c(NA, 1L)), na.rm = FALSE), rray(NA_real_)) expect_equal(prod(rray(c(NA, 1L)), na.rm = TRUE), rray(1)) }) context("test-sum") test_that("returns same values as base R", { x <- rray(c(5, 6), c(2, 2)) expect_equal(sum(x), rray(sum(vec_data(x)))) expect_equal(sum(x, x), rray(sum(vec_data(x), vec_data(x)))) }) test_that("broadcasts input using vctrs", { x <- rray(c(5, 6), c(2, 2)) expect_equal(sum(x, 5), rray(sum(x, matrix(5, c(1, 2))))) }) test_that("`na.rm` propagates", { expect_equal(sum(rray(c(NA, 1L)), na.rm = FALSE), rray(NA_integer_)) expect_equal(sum(rray(c(NA, 1L)), na.rm = TRUE), rray(1L)) }) context("test-cummax") test_that("vctrs dispatch works", { x <- rray(5:1) expect_equal(cummax(x), rray(cummax(vec_data(x)))) }) test_that("flattens 2D+ arrays", { x <- rray(5:1, c(5, 1)) expect_equal(cummax(x), rray(rep(5L, 5))) }) test_that("keeps names if x is 1D", { x <- rray(5:1, dim_names = list(letters[1:5])) expect_equal(rray_dim_names(cummax(x)), rray_dim_names(x)) }) context("test-cummin") test_that("vctrs dispatch works", { x <- rray(1:5) expect_equal(cummin(x), rray(cummin(vec_data(x)))) }) test_that("flattens 2D+ arrays", { x <- rray(1:5, c(5, 1)) expect_equal(cummin(x), rray(rep(1L, 5))) }) test_that("keeps names if x is 1D", { x <- rray(1:5, dim_names = list(letters[1:5])) expect_equal(rray_dim_names(cummin(x)), rray_dim_names(x)) }) context("test-cumsum") test_that("vctrs dispatch works", { x <- rray(1:5) expect_equal(cumsum(x), rray(cumsum(vec_data(x)))) }) test_that("flattens 2D+ arrays", { x <- rray(1:5, c(5, 1)) expect_equal(cumsum(x), rray(cumsum(1:5))) }) test_that("keeps names if x is 1D", { x <- rray(1:5, dim_names = list(letters[1:5])) expect_equal(rray_dim_names(cumsum(x)), rray_dim_names(x)) }) test_that("integer overflow throws a warning", { x <- rray(c(2147483647L, 1L)) expect_warning(cumsum(x), "integer overflow") }) context("test-cumprod") test_that("vctrs dispatch works", { x <- rray(1:5) expect_equal(cumprod(x), rray(cumprod(vec_data(x)))) }) test_that("flattens 2D+ arrays", { x <- rray(1:5, c(5, 1)) expect_equal(cumprod(x), rray(cumprod(1:5))) }) test_that("keeps names if x is 1D", { x <- rray(1:5, dim_names = list(letters[1:5])) expect_equal(rray_dim_names(cumprod(x)), rray_dim_names(x)) }) test_that("a double is returned so no integer overflow occurs", { x <- rray(c(2147483647L, 2L)) expect_equal(storage.mode(cumprod(x)), "double") }) context("test-mean") test_that("vctrs dispatch works", { x <- rray(1:5) expect_equal(mean(x), rray(mean(vec_data(x)))) }) test_that("flattens 2D+ arrays", { x <- rray(1:5, c(5, 1)) expect_equal(mean(x), rray(mean(1:5))) }) test_that("logicals become numerics", { x <- rray(TRUE, c(5, 1)) expect_equal(mean(x), rray(1)) }) context("test-is-nan") test_that("vctrs dispatch works", { nms <- list(NULL, "c1") x <- rray(c(1, NaN, 2), c(3, 1), dim_names = nms) expect <- rray(c(FALSE, TRUE, FALSE), c(3, 1), dim_names = nms) expect_equal(is.nan(x), expect) }) context("test-is-finite") test_that("vctrs dispatch works", { nms <- list(NULL, "c1") x <- rray(c(1, NaN, 2), c(3, 1), dim_names = nms) expect <- rray(c(TRUE, FALSE, TRUE), c(3, 1), dim_names = nms) expect_equal(is.finite(x), expect) y <- rray(c(1, Inf, 2), c(3, 1), dim_names = nms) expect_equal(is.finite(y), expect) }) context("test-is-infinite") test_that("vctrs dispatch works", { nms <- list(NULL, "c1") x <- rray(c(1, NaN, 2), c(3, 1), dim_names = nms) expect <- rray(c(FALSE, FALSE, FALSE), c(3, 1), dim_names = nms) expect_equal(is.infinite(x), expect) y <- rray(c(1, Inf, 2), c(3, 1), dim_names = nms) expect <- rray(c(FALSE, TRUE, FALSE), c(3, 1), dim_names = nms) expect_equal(is.infinite(y), expect) }) context("test-math-unary") .fs <- c( abs, sign, ceiling, floor, trunc, round, signif, exp, expm1, log, log2, log10, log1p, sin, cos, tan, asin, acos, atan, sinpi, cospi, tanpi, sinh, cosh, tanh, asinh, acosh, atanh, gamma, lgamma, digamma, trigamma ) .f_names <- c( "abs", "sign", "ceiling", "floor", "trunc", "round", "signif", "exp", "expm1", "log", "log2", "log10", "log1p", "sin", "cos", "tan", "asin", "acos", "atan", "sinpi", "cospi", "tanpi", "sinh", "cosh", "tanh", "asinh", "acosh", "atanh", "gamma", "lgamma", "digamma", "trigamma" ) for (i in seq_along(.fs)) { .f <- .fs[[i]] .f_name <- .f_names[[i]] test_that(glue::glue("vctrs dispatch works - {.f_name}"), { expect_equal(.f(rray(1)), rray(.f(1))) expect_equal(.f(rray(1L)), rray(.f(1L))) }) } context("test-unary-math-extra") test_that("vctrs dispatch passes `base` through", { expect_equal(log(rray(2), base = 2), rray(log(2, base = 2))) }) test_that("vctrs dispatch passes `digits` through", { expect_equal(round(rray(1)), rray(round(1))) expect_equal(round(rray(1.5), digits = 0), rray(round(1.5, digits = 0))) }) test_that("vctrs dispatch passes `digits` through", { expect_equal(signif(rray(1.5), digits = 1), rray(signif(1.5, digits = 1))) }) context("test-binary-math") test_that(glue::glue("atan2() keeps class of `y` (first argument)"), { expect_equal(atan2(rray(1), 2), rray(atan2(1, 2))) expect_equal(atan2(1, rray(2)), atan2(1, 2)) })
plotCalibration <- function(x, models, times, method="nne", cens.method, round=TRUE, bandwidth=NULL, q=10, bars=FALSE, hanging=FALSE, names="quantiles", pseudo=FALSE, rug, show.frequencies=FALSE, plot=TRUE, add=FALSE, diag=!add, legend=!add, auc.in.legend, brier.in.legend, axes=!add, xlim=c(0,1), ylim=c(0,1), xlab=ifelse(bars,"Risk groups","Predicted risk"), ylab, col, lwd, lty, pch, type, percent=TRUE, na.action=na.fail, cex=1, ...){ if (x$response.type!="binary" && missing(cens.method)){ cens.method <- "local" message("The default method for estimating calibration curves based on censored data has changed for riskRegression version 2019-9-8 or higher\nSet cens.method=\"jackknife\" to get the estimate using pseudo-values.\nHowever, note that the option \"jackknife\" is sensititve to violations of the assumption that the censoring is independent of both the event times and the covariates.\nSet cens.method=\"local\" to suppress this message.") } model=risk=event=status=NULL if (missing(ylab)){ if (bars==TRUE){ ylab="" } else{ if (x$cens.type=="rightCensored"){ ylab="Estimated actual risk" } else{ ylab="Observed frequency" } } } if (missing(auc.in.legend)) auc.in.legend <- ("auc" %in% tolower(x$metrics)) if (missing(brier.in.legend)) brier.in.legend <- ("auc" %in% tolower(x$metrics)) if (missing(pseudo) & missing(rug)) if (x$cens.type=="rightCensored"){ showPseudo <- FALSE showRug <- FALSE } else{ showPseudo <- FALSE showRug <- TRUE } else{ if (missing(pseudo) || pseudo[[1]]==FALSE) showPseudo <- FALSE else showPseudo <- TRUE if (missing(rug) || rug[[1]]==FALSE) showRug <- FALSE else showRug <- TRUE } pframe <- x$Calibration$plotframe if (is.null(pframe)) stop("Object has no information for calibration plot.\nYou should call the function \"riskRegression::Score\" with plots=\"calibration\".") Rvar <- grep("^(ReSpOnSe|pseudovalue)$",names(pframe),value=TRUE) if (!missing(models)){ fitted.models <- pframe[,unique(model)] if (all(models%in%fitted.models)){ pframe <- pframe[model%in%models] } else{ if (all(is.numeric(models)) && (max(models)<=length(fitted.models))){ models <- fitted.models[models] pframe <- pframe[model%in%models] }else{ stop(paste0("The requested models: ", models, "\ndo not all match the fitted models: ", paste0(fitted.models,collapse=", "))) } } } data.table::setkey(pframe,model) if (x$response.type!="binary"){ if (missing(times)){ tp <- max(pframe[["times"]]) if (length(unique(pframe$times))>1) warning("Time point not specified, use max of the available times: ",tp) } else{ tp <- times[[1]] if (!(tp%in%unique(pframe$times))) stop(paste0("Requested time ",times[[1]]," is not in object")) } pframe <- pframe[times==tp] }else tp <- NULL NF <- pframe[,length(unique(model))] if (bars){ method="quantile" if (!(NF==1)) stop(paste0("Barplots work only for one risk prediction model at a time. Provided are ",NF, "models.")) } if (missing(lwd)) lwd <- rep(3,NF) if (missing(col)) { if (bars) col <- c("grey90","grey30") else{ cbbPalette <- c(" if (NF>length(cbbPalette)) col <- 1:NF else col <- cbbPalette[1:NF] } } if (missing(type)){ if (method=="quantile"){ type <- rep("b",length.out=NF) } else{ type <- rep("l",length.out=NF) } } if (missing(lty)) lty <- rep(1, length.out=NF) if (missing(pch)) pch <- rep(1, length.out=NF) if (length(lwd) < NF) lwd <- rep(lwd, length.out=NF) if (length(type) < NF) type <- rep(type,length.out=NF) if (length(lty) < NF) lty <- rep(lty,length.out=NF) if (length(col) < NF) col <- rep(col,length.out=NF) if (length(pch) < NF) pch <- rep(pch,length.out=NF) modelnames <- pframe[,unique(model)] axis1.DefaultArgs <- list(side=1,las=1,at=seq(0,xlim[2],xlim[2]/4)) axis2.DefaultArgs <- list(side=2,las=2,at=seq(0,ylim[2],ylim[2]/4),mgp=c(4,1,0)) if (is.character(legend[[1]])|| legend[[1]]==TRUE||auc.in.legend==TRUE|| brier.in.legend==TRUE){ legend.data <- getLegendData(object=x, models=models, times=tp, auc.in.legend=auc.in.legend, brier.in.legend=brier.in.legend, drop.null.model=TRUE) if (is.character(legend)) legend.text <- legend else{ legend.text <- unlist(legend.data[,1]) } nrows.legend <- NROW(legend.data) if (nrows.legend==1){ legend.lwd <- NA } else{ legend.lwd <- lwd } legend.DefaultArgs <- list(legend=legend.text,lwd=legend.lwd,col=col,ncol=1,lty=lty,cex=cex,bty="n",y.intersp=1,x="topleft",title="") if (NCOL(legend.data)>1){ addtable2plot.DefaultArgs <- list(yjust=1.18, cex=cex, table=legend.data[,-1,drop=FALSE]) }else{ addtable2plot.DefaultArgs <- NULL } }else{ legend.DefaultArgs <- NULL addtable2plot.DefaultArgs <- NULL } if (bars){ legend.DefaultArgs <- list(legend=modelnames,col=col,cex=cex,bty="n",x="topleft") names.DefaultArgs <- list(cex=.7*par()$cex,y=c(-abs(diff(ylim))/15,-abs(diff(ylim))/25)) frequencies.DefaultArgs <- list(cex=.7*par()$cex,percent=FALSE,offset=0) } else{ if (length(modelnames)<=1 && sum(auc.in.legend+brier.in.legend)==0){ legend=FALSE } } if(bars){ if (x$cens.type=="rightCensored") legend.DefaultArgs$legend <- c("Predicted risk", "Estimated actual risk") else legend.DefaultArgs$legend <- c("Predicted risk", "Observed frequency") } lines.DefaultArgs <- list(pch=pch,type=type,cex=cex,lwd=lwd,col=col,lty=lty) abline.DefaultArgs <- list(lwd=1,col="red") if (missing(ylim)){ if (showPseudo[1] && !bars[1]){ ylim <- range(pframe[[Rvar]]) } else ylim <- c(0,1) } if (missing(xlim)){ xlim <- c(0,1) } plot.DefaultArgs <- list(x=0, y=0, type = "n", ylim = ylim, xlim = xlim, ylab=ylab, xlab=xlab) rug.DefaultArgs <- list(col=col,lwd=lwd,side=1,ticksize=0.03) pseudo.DefaultArgs <- list(col=col,cex=cex,density=55) barplot.DefaultArgs <- list(ylim = ylim, col=col, axes=FALSE, ylab=ylab, xlab=xlab, beside=TRUE, legend.text=NULL, cex.axis=cex, cex.lab=par()$cex.lab, cex.names=cex) if (bars){ control <- prodlim::SmartControl(call= list(...), keys=c("barplot","legend","addtable2plot","axis2","abline","names","frequencies"), ignore=NULL, ignore.case=TRUE, defaults=list("barplot"=barplot.DefaultArgs, "addtable2plot"=addtable2plot.DefaultArgs, "abline"=abline.DefaultArgs, "legend"=legend.DefaultArgs, "names"=names.DefaultArgs, "frequencies"=frequencies.DefaultArgs, "axis2"=axis2.DefaultArgs), forced=list("abline"=list(h=0)), verbose=TRUE) }else{ control <- prodlim::SmartControl(call= list(...), keys=c("plot","rug","pseudo","lines","legend","addtable2plot","axis1","axis2"), ignore=NULL, ignore.case=TRUE, defaults=list("plot"=plot.DefaultArgs,"pseudo"=pseudo.DefaultArgs,"rug"=rug.DefaultArgs, "addtable2plot"=addtable2plot.DefaultArgs, "lines"=lines.DefaultArgs, "legend"=legend.DefaultArgs, "axis1"=axis1.DefaultArgs, "axis2"=axis2.DefaultArgs), forced=list("plot"=list(axes=FALSE), "axis1"=list(side=1)), verbose=TRUE) } method <- match.arg(method,c("quantile","nne")) getXY <- function(f){ risk=NULL p <- pframe[model==f,risk] jackF <- pframe[model==f][[Rvar]] switch(method, "quantile"={ if (length(q)==1) groups <- quantile(p,seq(0,1,1/q)) else{ groups <- q } xgroups <- (groups[-(length(groups))]+groups[-1])/2 pcut <- cut(p,groups,include.lowest=TRUE) if (x$response.type=="binary"){ plotFrame=data.frame(Pred=tapply(p,pcut,mean), Obs=pmin(1,pmax(0,tapply(jackF,pcut,mean)))) }else{ if(x$response.type=="survival"){ censcode <- pframe[status==0,status[1]] qfit <- prodlim::prodlim(prodlim::Hist(time,status,cens.code=censcode)~pcut,data=pframe) plotFrame=data.frame(Pred=tapply(p,pcut,mean), Obs=predict(qfit, newdata=data.frame(pcut=levels(pcut)), cause=1, mode="matrix", times=tp,type="cuminc")) }else{ censcode <- pframe[status==0,event[1]] qfit <- prodlim::prodlim(prodlim::Hist(time,event,cens.code=censcode)~pcut,data=pframe) n.cause <- match(x$cause,x$states) plotFrame=data.frame(Pred=tapply(p,pcut,mean), Obs=predict(qfit, newdata=data.frame(pcut=levels(pcut)), cause=n.cause, mode="matrix", times=tp,type="cuminc")) } } attr(plotFrame,"quantiles") <- groups plotFrame }, "nne"={ if (round==TRUE){ if (!is.null(bandwidth) && bandwidth[1]>=1){ } else{ p <- round(p,2) } } p <- na.omit(p) if (no <- length(attr(p,"na.action"))) warning("calPlot: removed ",no," missing values in risk prediction.",call.=FALSE,immediate.=TRUE) if (is.null(bandwidth)){ if (length(unique(p))==1) bw <- 1 else bw <- prodlim::neighborhood(p)$bandwidth } else{ bw <- bandwidth } if (bw>=1){ plotFrame <- data.frame(Pred=mean(p),Obs=mean(jackF)) } else{ if (x$response.type=="binary"){ nbh <- prodlim::meanNeighbors(x=p,y=jackF,bandwidth=bw) plotFrame <- data.frame(Pred=nbh$uniqueX,Obs=nbh$averageY) }else{ if (cens.method=="local"){ if(x$response.type=="survival"){ censcode <- pframe[status==0,status[1]] pfit <- prodlim::prodlim(prodlim::Hist(time,status,cens.code=censcode)~p,data=pframe,bandwidth=bandwidth) plotFrame=data.frame(Pred=sort(unique(p)), Obs=predict(pfit, newdata=data.frame(p=sort(unique(p))), cause=1, mode="matrix", times=tp,type="cuminc")) }else{ censcode <- pframe[status==0,event[1]] pfit <- prodlim::prodlim(prodlim::Hist(time,event,cens.code=censcode)~p,data=pframe,bandwidth=bandwidth) n.cause <- match(x$cause,x$states) plotFrame=data.frame(Pred=sort(unique(p)), Obs=predict(pfit, newdata=data.frame(p=sort(unique(p))), cause=n.cause, mode="matrix", times=tp,type="cuminc")) } } else{ nbh <- prodlim::meanNeighbors(x=p,y=jackF,bandwidth=bw) plotFrame <- data.frame(Pred=nbh$uniqueX,Obs=nbh$averageY) } } } attr(plotFrame,"bandwidth") <- bw plotFrame }) } plotFrames <- lapply(modelnames,function(f){getXY(f)}) names(plotFrames) <- modelnames if (bars){ if ((is.logical(names[[1]]) && names[[1]]==TRUE)|| names[[1]] %in% c("quantiles.labels","quantiles")){ qq <- attr(plotFrames[[1]],"quantiles") if (names[1]=="quantiles.labels"){ pp <- seq(0,1,1/q) names <- paste0("(", sprintf("%1.0f",100*pp[-length(pp)]),",", sprintf("%1.0f",100*pp[-1]), ")\n", sprintf("%1.1f",100*qq[-length(qq)])," - ", sprintf("%1.1f",100*qq[-1])) } else names <- paste0(sprintf("%1.1f",100*qq[-length(qq)])," - ", sprintf("%1.1f",100*qq[-1])) } } out <- list(plotFrames=plotFrames, times=tp, control=control, legend=legend, bars=bars, diag=diag, add=add, names=names, method=method, axes=axes, percent=percent, hanging=hanging, show.frequencies=show.frequencies, col=col, ylim=ylim, xlim=xlim, ylab=ylab, xlab=xlab, lwd=lwd, lty=lty, pch=pch, lty=lty, type=type, NF=NF) if (method=="nne") out <- c(out,list(bandwidth=sapply(plotFrames, function(x)attr(x,"bandwidth")))) if (plot){ if (out$add[1]==FALSE && !out$bars[1]){ do.call("plot",control$plot) } if (out$diag[1] && !out$bars[1]){ segments(x0=0,y0=0,x1=1,y1=1,col="gray77",lwd=2,xpd=FALSE) } if (out$diag[1] && !out$bars[1]){ segments(x0=0,y0=0,x1=1,y1=1,col="gray77",lwd=2,xpd=FALSE) } if (out$bars[1]) { stopifnot(NF==1) pf <- na.omit(plotFrames[[1]]) Pred <- pf$Pred Obs <- pf$Obs if (is.character(legend[[1]]) || legend[[1]]==FALSE){ control$barplot$legend.text <- NULL }else{ if (is.null(control$barplot$legend.text)){ control$barplot$legend.text <- control$legend$legend } control$barplot$args.legend <- control$legend } if (is.null(control$barplot$space)) control$barplot$space <- rep(c(1,0),length(Pred)) PredObs <- c(rbind(Pred,Obs)) control$barplot$height <- PredObs if (out$hanging){ control$barplot$offset <- c(rbind(0,Pred-Obs)) minval <- min(Pred-Obs) if (minval<0) negY.offset <- 0.05+seq(0,1,0.05)[prodlim::sindex(jump.times=seq(0,1,0.05),eval.times=abs(minval))] else negY.offset <- 0 control$barplot$ylim[1] <- min(control$barplot$ylim[1],-negY.offset) control$names$y <- control$names$y-negY.offset } coord <- do.call("barplot",control$barplot) if (length(out$names)>0 && (out$names[[1]]!=FALSE) && is.character(out$names)){ if (out$names[[1]]!=FALSE && length(out$names)==(length(coord)/2)){ mids <- rowMeans(matrix(coord,ncol=2,byrow=TRUE)) text(x=mids, y=control$names$y, out$names, xpd=NA, cex=control$names$cex) } } if (out$hanging){ do.call("abline",control$abline) } if (out$show.frequencies){ if(out$hanging){ text(x=coord, cex=control$frequencies$cex, pos=3, y=(as.vector(rbind(Pred,Pred)) +rep(control$frequencies$offset,times=length(as.vector(coord))/2)), paste(round(100*c(rbind(Pred,Obs)),0),ifelse(control$frequencies$percent,"%",""),sep=""),xpd=NA) }else{ text(coord, pos=3, c(rbind(Pred,Obs))+control$frequencies$offset, cex=control$frequencies$cex, paste(round(100*c(rbind(Pred,Obs)),0),ifelse(control$frequencies$percent,"%",""),sep=""),xpd=NA) } } coords <- list(xcoord=coord[,1],ycoord=PredObs,offset=control$barplot$offset) out <- c(out,coords) }else{ nix <- lapply(1:NF,function(f){ pf <- out$plotFrames[[f]] pf <- na.omit(pf) if (showRug){ do.call(graphics::rug,c(list(x=pf$Pred,col=control$rug$col[f],lwd=control$rug$lwd[f]*0.5))) } if (showPseudo) { if (!is.null(control$pseudo$density) & control$pseudo$density>0){ control$pseudo$col <- prodlim::dimColor(control$pseudo$col[f], control$pseudo$density) } if ((gotcha <- match("density",names(control$pseudo),nomatch=0))>0){ control$pseudo <- control$pseudo[-gotcha] } do.call(points, c(list(x=pframe[model==modelnames[f]][,risk],y=pframe[model==modelnames[f]][[Rvar]]),control$pseudo)) } lineF <- lapply(control$lines,function(x)x[[min(f,length(x))]]) lineF$x <- pf$Pred lineF$y <- pf$Obs do.call("lines",lineF) }) if (is.character(out$legend[[1]]) || out$legend[[1]]==TRUE){ legend.coords <- do.call("legend",control$legend) if (!is.null(addtable2plot.DefaultArgs)){ if (is.null(control$addtable2plot[["x"]])) control$addtable2plot[["x"]] <- legend.coords$rect$left+legend.coords$rect$w if (is.null(control$addtable2plot[["y"]])) control$addtable2plot[["y"]] <- legend.coords$rect$top-legend.coords$rect$h do.call(plotrix::addtable2plot,control$addtable2plot) } } } if (out$axes){ if (out$percent){ if (is.null(control$axis1$labels)){ control$axis1$labels <- paste(100*control$axis1$at,"%") } if (is.null(control$axis2$labels)){ control$axis2$labels <- paste(100*control$axis2$at,"%") } } if (!out$bars) do.call("axis",control$axis1) do.call("axis",control$axis2) } } class(out) <- "calibrationPlot" invisible(out) }
zdifference_ordinal<-function(x,ref,w=NULL,na.rm=TRUE,r=10){ if(is.null(w)){ w<-rep(1,length(x)) } if(na.rm==TRUE){ exclna<-which(is.na(x)==TRUE |is.na(w)==TRUE | is.na(ref)==TRUE) if(length(exclna)!=0){ x<-x[-exclna] w<-w[-exclna] ref<-ref[-exclna] } } else{ if(any(is.na(x)==TRUE |is.na(w)==TRUE | is.na(ref)==TRUE)) warning("NA in the data and NAs not removed") } if(any(w<0)){ stop("negative weights are not allowed") } if(length(unique(na.omit(ref)))!= 2){ stop("reference variable is not binomial") } if(class(x)=="integer"){ x<-as.numeric(as.character(x)) } if(class(x)=="factor"){ x<-as.numeric(x) } x0<-x[which(ref==(sort(unique(ref)))[1])] x1<-x[-which(ref==(sort(unique(ref)))[1])] w0<-w[which(ref==(sort(unique(ref)))[1])]/sum(w[which(ref==sort(unique(ref))[1])],na.rm=na.rm) w1<-w[which(ref==sort((unique(ref)))[2])]/sum(w[which(ref==sort(unique(ref))[2])],na.rm=na.rm) x<-c(x0,x1) w<-c(w0,w1) d<-length(which(ref==sort(unique(ref))[1])) ran<-rank(x,ties.method="average") t<-unlist(lapply(1:length(unique(ran)),function(i) length(which(ran==unique(ran)[i])))) if(length(unique(ran))==length(x)){ nenner<-sum(w0^2+w1^2)*((length(x)^2-1)/12+(length(x)+1)/12) } else{ rs<-unique(ran) N<-length(ran) cvv<-sum(rs^2*t*(t-1))/(N*(N-1))+(sum(rs*t*sum(rs*t)-rs^2*t^2))/(N*(N-1))-((N+1)/2)^2 v<-c(-sum(t^3-t)/12/length(ran)+(length(ran)^2-1)/12) nenner<-sum(w0^2)*v+(-sum(w0^2))*cvv+sum(w1^2)*v +(-sum(w1^2))*cvv } return(round((sum(w0*ran[1:d])-sum(w1*ran[-c(1:d)]))/sqrt(nenner),r)) }
NULL NULL .onAttach <- function(libname, pkgname) { packageStartupMessage("Notice: Formerly the gendistance() function scaled the Mahalanobis distances into large integers, as required by the nonbimatch() function. Starting in version 1.5.0, gendistance() will return unscaled distances. This facilitates comparison to an appropriate F distribution for multivariate normal data. Any required scaling will happen invisibly within nonbimatch(). This notice will be removed in a future version of nbpMatching.") }
KIR <- function(level){ x <- NULL if(level==1){ x1 <- github.cssegisanddata.covid19(country = "Kiribati") x2 <- ourworldindata.org(id = "KIR") x <- full_join(x1, x2, by = "date") } return(x) }
extractMass <- function(mass,F,g=NULL,S=NULL,method,crit=NULL,Kmat=NULL,trace=NULL, D=NULL,W=NULL,J=NULL,param=NULL){ n<-nrow(mass) c<-ncol(F) if(any(F[1,]==1)){ F<-rbind(rep(0,c),F) mass<-cbind(rep(0,n),mass) } f<-nrow(F) card<-rowSums(F) conf<-mass[,1] C<- 1/(1-conf) mass.n<- C*mass[,2:f] pl<- mass%*% F pl.n<- C*pl p <-pl/rowSums(pl) bel<- mass[,card==1] bel.n<-C*bel y.pl<-max.col(pl) y.bel<-max.col(bel) Y<-F[max.col(mass),] Ynd<-matrix(0,n,c) for (i in 1:n){ ii<-which(pl[i,]>= bel[i,y.bel[i]]) Ynd[i,ii]<-1 } P<-F/card P[1,]<- rep(0,c) betp<- mass %*% P betp.n<- C* betp lower.approx<-vector(mode='list',length=c) upper.approx<-vector(mode='list',length=c) lower.approx.nd<-vector(mode='list',length=c) upper.approx.nd<-vector(mode='list',length=c) nclus<-rowSums(Y) outlier<-which(nclus==0) nclus.nd<-rowSums(Ynd) for(i in 1:c){ upper.approx[[i]]<- which(Y[,i]==1) lower.approx[[i]]<- which((Y[,i]==1) & (nclus==1)) upper.approx.nd[[i]]<- which(Ynd[,i]==1) lower.approx.nd[[i]]<- which((Ynd[,i]==1) & (nclus.nd==1)) } card<-c(c,card[2:f]) Card<-matrix(card,n,f,byrow=TRUE) N <- sum(log(Card)*mass)/log(c)/n clus<-list(conf=conf,F=F,mass=mass,mass.n=mass.n,pl=pl,pl.n=pl.n,bel=bel,bel.n=bel.n,y.pl=y.pl, y.bel=y.bel,Y=Y,betp=betp,betp.n=betp.n,p=p,upper.approx=upper.approx, lower.approx=lower.approx,Ynd=Ynd,upper.approx.nd=upper.approx.nd, lower.approx.nd=lower.approx.nd,N=N,outlier=outlier,g=g,S=S, crit=crit,Kmat=Kmat,trace=trace,D=D,method=method,W=W,J=J,param=param) class(clus)<-"credpart" return(clus) }