code
stringlengths
1
13.8M
protect_smooth <- function( x , bw = raster::res(x$value) , ... ){ assert_sdc_raster(x) r <- x$value w <- raster::focalWeight(r$count, d = bw, type="Gaus") x$scale <- x$scale * w[ceiling(nrow(w)/4), ceiling(ncol(w)/4)] r$count <- smooth_raster(r$count, bw = bw, ...) r$sum <- smooth_raster(r$sum, bw = bw, ...) r$mean <- r$sum / r$count if (x$type == "numeric"){ r$max <- smooth_raster(r$max, bw = bw, ...) r$max2 <- smooth_raster(r$max2, bw = bw, ...) } x$value <- r x }
pcplot <- function(data, clusters, barColor = "steelblue", colorScheme = "schemeCategory10", width = NULL, height = NULL, labelSizes = NULL, dotSize = NULL, pcGridlines = FALSE, barGridlines = FALSE) { if (typeof(colorScheme) != "character" && typeof(colorScheme) != "list") { stop("colorScheme must be of type character or a list of colors") } if (!is.null(labelSizes) && typeof(labelSizes) != "list" && typeof(labelSizes) != "double") { stop("labelSizes must be of type double or a list of arguments") } PC <- getPC(data, clusters) if (typeof(labelSizes) == "double") { labelSizes <- list(yaxis = labelSizes, xaxis = labelSizes, yticks = labelSizes, xticks = labelSizes, legend = labelSizes, tooltip = labelSizes, title = labelSizes) } PC$PC <- PC$PC[order(clusters),] json_PC <- jsonlite::toJSON(x = PC$PC, dataframe = "rows") json_PVE <- jsonlite::toJSON(x = PC$PVE) json_idx <- jsonlite::toJSON(x = PC$idxs) json_cont <- jsonlite::toJSON(x = PC$cont, dataframe = "rows") json_thresh <- jsonlite::toJSON(x = PC$thresh) json_colorScheme <- jsonlite::toJSON(x = colorScheme) json_labelSizes <- jsonlite::toJSON(x = labelSizes) x = list( PC = json_PC, PVE = json_PVE, idxs = json_idx, cont = json_cont, thresh = json_thresh, barColor = barColor, colorScheme = json_colorScheme, labelSizes = json_labelSizes, dotSize = dotSize, pcGridlines = pcGridlines, barGridlines = barGridlines ) htmlwidgets::createWidget( name = 'pcplot', x, width = width, height = height, package = 'klustR', sizingPolicy = htmlwidgets::sizingPolicy( viewer.padding = 0, browser.fill = TRUE ) ) } pcplotOutput <- function(outputId, width = '100%', height = '400px'){ htmlwidgets::shinyWidgetOutput(outputId, 'pcplot', width, height, package = 'klustR') } renderpcplot <- function(expr, env = parent.frame(), quoted = FALSE) { if (!quoted) { expr <- substitute(expr) } htmlwidgets::shinyRenderWidget(expr, pcplotOutput, env, quoted = TRUE) }
getOutliersI <- function(y, rho=c(1,1), FLim=c(0.1,0.9), distribution="normal") { if ( !is.vector(y) ) stop("First argument is not of type vector") if ( sum(y < 0) > 0 & !(distribution == "normal") ) stop("First argument contains nonpositive values") if ( sum( rho <= 0, na.rm=TRUE ) > 0 ) stop("Values of rho must be positive") if ( FLim[2] <= FLim[1] | sum( FLim < 0 | FLim > 1) >0 ) stop("Invalid range in FLim: 0<=FLim[1]<FLim[2]<=1") if ( ! distribution %in% c("lognormal", "pareto", "exponential", "weibull", "normal") ) stop("Invalid distribution (lognormal, pareto, exponential, weibull, normal).") Y <- y; y <- sort(y); N <- length(y) P <- (1:N)/(N+1) Lambda <- P >= FLim[1] & P<=FLim[2] y <- y[Lambda]; p <- P[Lambda]; out <- switch(distribution, lognormal = getLognormalLimit(y, p, N, rho), pareto = getParetoLimit(y, p, N, rho), exponential = getExponentialLimit(y, p, N, rho), weibull = getWeibullLimit(y, p, N, rho), normal = getNormalLimit(y, p, N, rho) ) out$method <- "Method I" out$distribution=distribution out$iRight = which( Y > out$limit[2] ) out$iLeft = which( Y < out$limit[1] ) out$nOut = c(Left=length(out$iLeft), Right=length(out$iRight)) out$yMin <- y[1] out$yMax <- tail(y,1) out$rho = c(Left=rho[1], Right=rho[2]) out$Fmin = FLim[1] out$Fmax = FLim[2] return(out); }
binary_3bit_T7 <- function(seqs,binaryType="numBin",label=c(),outFormat="mat",outputFileDist="") { if(length(seqs)==1&&file.exists(seqs)){ seqs<-fa.read(seqs,alphabet="aa") seqs_Lab<-alphabetCheck(seqs,alphabet = "aa",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else if(is.vector(seqs)){ seqs<-sapply(seqs,toupper) seqs_Lab<-alphabetCheck(seqs,alphabet = "aa",label) seqs<-seqs_Lab[[1]] label<-seqs_Lab[[2]] } else { stop("ERROR: Input sequence is not in the correct format. It should be a FASTA file or a string vector.") } lenSeqs<-sapply(seqs,nchar) numSeqs=length(seqs) Group=list("Buried"=c("A","L","F","C","G","I","V","W"),"Exposed"=c("R","K","Q","E","N","D"),"Intermediate"=c("M","S","P","T","H","Y")) grps<-unlist(Group) dict<-vector() numGrp=3 for (i in 1:numGrp) { vect<-rep(i,length(Group[[i]])) dict<-c(dict,vect) } names(dict)<-grps aa<-grps if(outFormat=="mat"){ if(length(unique(lenSeqs))>1){ stop("ERROR: All sequences should have the same length in 'mat' mode. For sequences with different lengths, please use 'txt' for outFormat parameter") } if(binaryType=="strBin"){ binary<-rep(strrep(0,3),20) names(binary)=aa for(i in 1:length(dict)) { pos<-dict[i] substr(binary[i],pos,pos)<-"1" } featureMatrix<-matrix("",nrow = numSeqs, ncol = lenSeqs[1]) for(n in 1:numSeqs){ seq<-seqs[n] charSeq<-unlist(strsplit(seq,split = "")) vect<-unlist(binary[charSeq]) featureMatrix[n,]<-vect } colnames(featureMatrix)<-paste("pos",1:lenSeqs[1],sep = "") } else if(binaryType=="logicBin"){ featureMatrix<-matrix(FALSE,nrow = numSeqs, ncol = (lenSeqs[1]*3)) rng<-(0:(lenSeqs[1]-1))*3 for(n in 1:numSeqs){ seq<-seqs[n] charSeq<-unlist(strsplit(seq,split = "")) pos1<-as.numeric(dict[charSeq]) pos1<-rng+pos1 featureMatrix[n,pos1]<-TRUE } colnames(featureMatrix)<-paste0("pos",rep(1:lenSeqs[1],each=3),"-",rep(names(Group),lenSeqs[1])) } else if(binaryType=="numBin"){ featureMatrix<-matrix(0,nrow = numSeqs, ncol = (lenSeqs[1]*3)) rng<-(0:(lenSeqs[1]-1))*3 for(n in 1:numSeqs){ seq<-seqs[n] charSeq<-unlist(strsplit(seq,split = "")) pos1<-as.numeric(dict[charSeq]) pos1<-rng+pos1 featureMatrix[n,pos1]<-1 } colnames(featureMatrix)<-paste0("pos",rep(1:lenSeqs[1],each=3),"-",rep(names(Group),lenSeqs[1])) } else{ stop("ERROR! Choose one of 'strBin', 'logicBin', or 'numBin' for binaryFormat") } if(length(label)==numSeqs){ featureMatrix<-as.data.frame(featureMatrix) featureMatrix<-cbind(featureMatrix,label) } row.names(featureMatrix)<-names(seqs) return(featureMatrix) } else if(outFormat=="txt"){ vect<-vector() nameSeq<-names(seqs) binary<-rep(strrep(0,3),20) names(binary)=aa for(i in 1:length(dict)) { pos<-dict[i] substr(binary[i],pos,pos)<-"1" } for(n in 1:numSeqs){ seq<-seqs[n] charSeq<-unlist(strsplit(seq,split = "")) temp<-c(nameSeq[n],binary[charSeq]) temp<-paste(temp,collapse = "\t") write(temp,outputFileDist,append = TRUE) } } else{ stop("ERROR: outFormat should be 'mat' or 'txt' ") } }
knitr::opts_chunk$set(echo = TRUE) options( width=100 ) library(munsellinterpol) MunsellToxyY( '4.2RP 5.5/8' ) xyY = MunsellToxyY( '4.2RP 5.5/8' )$xyY xyYtoMunsell( xyY ) par( omi=c(0,0,0,0), mai=c(0.6,0.7,0.4,0.2) ) plotPatchesH( "10GY", back=' par( omi=c(0,0,0,0), mai=c(0.6,0.7,0.4,0.2) ) plotPatchesH( "10GY", space='AdobeRGB', back=' par( omi=c(0,0,0,0), mai=c(0.6,0.7,0.6,0.2) ) plotLociHC( value=8 ) par( omi=c(0,0,0,0), mai=c(0.6,0.7,0.6,0.2) ) plotLociHC( value=8, coords='ab' ) path = system.file( 'extdata/PantoneCoY.txt', package='munsellinterpol' ) pantone = read.table( path, header=TRUE, sep='\t', strings=FALSE ) pantone pantone$Year = NULL ; pantone$Code = NULL RGB = as.matrix( pantone[ , c('R','G','B') ] ) HVC = RGBtoMunsell( RGB, space='sRGB' ) pantone$Munsell = MunsellNameFromHVC( HVC ) block = ColorBlockFromMunsell( HVC ) pantone[[ "ISCC-NBS Name" ]] = block$Name pantone[[ "ISCC-NBS Centroid" ]] = block$Centroid pantone color.pant = rgb( RGB, max=255 ) color.cent = rgb( MunsellToRGB( block$Centroid, space='sRGB' )$RGB, max=255 ) tbl = data.frame( row.names=1:nrow(pantone) ) tbl[[ "Pantone Name" ]] = pantone$Name tbl[[ "Pantone Color" ]] = '' ; tbl[[ "Centroid Color" ]] = '' tbl[[ "ISCC-NBS Name" ]] = block$Name library( flextable ) myrt <- regulartable( tbl ) myrt <- align( myrt, j=4, align='left', part='all' ) myrt <- align( myrt, j=2:3, align='center', part='all' ) myrt <- height( myrt, height=1 ) myrt <- width( myrt, j=c(1,4), width=2 ) ; myrt <- width( myrt, j=2:3, width=2.5 ) myrt <- fontsize( myrt, size=14, part='all' ) ; myrt <- fontsize( myrt, size=16, part='header' ) for( i in 1:nrow(tbl) ) { myrt <- bg(myrt, i=i, j=2, bg=color.pant[i]) ; myrt <- bg(myrt, i=i, j=3, bg=color.cent[i]) } myrt sessionInfo()
dfp_getLineItemTemplatesByStatement <- function(request_data, as_df=TRUE, verbose=FALSE){ request_body <- form_request_body(service='LineItemTemplateService', root_name='getLineItemTemplatesByStatement', data=request_data) httr_response <- execute_soap_request(request_body=request_body, verbose=verbose) result <- parse_soap_response(httr_response=httr_response, resp_element='getLineItemTemplatesByStatementResponse', as_df=as_df) return(result) }
lowfhCopula <- function(dim = 2L) { if(dim != 2) stop("The lower Frechet-Hoeffding bound copula is only available in the bivariate case") cdfExpr <- function(d) { uis <- c(paste0("u", 1:d, "-1"), "1") expr <- paste(uis, collapse = "+") expr <- paste0("max(", expr, ",0)") parse(text = expr) } new("lowfhCopula", dimension = as.integer(dim), exprdist = c(cdf = cdfExpr(dim), pdf = expression())) } setMethod("pCopula", signature("matrix", "lowfhCopula"), function(u, copula, log.p = FALSE) { d <- ncol(u) stopifnot(d == copula@dimension) res <- pmax(rowSums(u) - d + 1, 0) if(log.p) log(res) else res }) setMethod("rCopula", signature("numeric", "lowfhCopula"), function(n, copula) { U <- runif(n) cbind(U, 1-U) }) setMethod("tau", signature("lowfhCopula"), function(copula) -1) setMethod("rho", signature("lowfhCopula"), function(copula) -1) setMethod("lambda", signature("lowfhCopula"), function(copula) c(lower = 0, upper = 0))
library(testthat) library(osmplotr) test_check("osmplotr")
fitted.cpd <- function(object, ...){ nmode <- length(object$A) xdims <- sapply(object$A, nrow) Z <- krprod(object$A[[3]], object$A[[2]]) if(nmode > 3L) for(n in 4:nmode) Z <- krprod(object$A[[n]], Z) array(tcrossprod(object$A[[1]], Z), dim = xdims) }
model.pro <- function(spike, flash, fixed=NULL, kv=F) { findInd <- function(sn, tf, first=T) { tmp <- sn[tf] if (sum(tf) == 0) { return(NA) } else { if (first) { return(tmp[1]) } else { return(tmp[length(tmp)]) } } } fixedflashspacing <- function(ff) { re <- 0 sff <- sum(ff) fseq <- 1:length(ff) if (sff == 0 ) { return(length(ff)^2) } else if (sff == 1) { af <- fseq[ff==1] return(af^2 + (length(ff)-af)^2) } else { fftimes <- fseq[ff==1] return(sum(diff(fftimes)^2) + fftimes[1]^2 + (length(ff)-fftimes[length(fftimes)])^2) } } nsf <- length(spike) t0 <- 1:nsf t0 <- t0[spike==1] if (length(t0) < 2 ) { warning("only one spike in sweep!") return(NULL) } if (is.null(fixed)) { t0 <- t0[1] } else { t0 <- fixed } tmp <- flash[1:t0] if (sum(tmp)> 0) { f0 <- findInd(seq_along(tmp), tmp==1, first=F) } else { f0 <- 1 } nout <- nsf-t0 re <- matrix(0, nrow=nout, ncol=7) curspike <- t0 curflash <- f0 curflashspike <- t0 cumflash <- 0 cumpftime <- 0 cumsqpf <- 0 sqcount <- 0 curcount <- 0 zeroout <- 1 if (!is.null(fixed)) { fixedcumspike <- sum(spike[1:t0]) fixedcumflash <- sum(flash[1:t0]) fixedcumsqcount <- fixedflashspacing(flash[1:t0]) } for (j in (t0+1):nsf) { if(zeroout) { cumflash <- 0 cumpftime <- 0 zeroout <- 0 sqcount <- 0 curcount <- 0 } pstime <- j-curspike if (spike[j] ==1) { curspike <- j if (kv) curflashspike <- j zeroout <- 1 } if (flash[j] ==1) { curflash <- j curflashspike <- j cumflash <- cumflash+1 } cumpftime <- cumpftime+j-curflash if (j-curflash == 0) sqcount <- sqcount+curcount if (kv) { curcount <- (j-curflashspike)^2 } else { curcount <- (j-curflash)^2 } cumsqpf <- sqcount+curcount if (is.null(fixed)) { re[j-t0,] <- c(spike[j], flash[j], pstime, j-curflash, cumflash, cumpftime, cumsqpf) } else { re[j-t0,] <- c(spike[j], flash[j], pstime, j-curflash, sum(flash[(j-fixed):j]), cumpftime, fixedflashspacing(flash[(j-fixed):j]) ) } } re <- as.data.frame(re) names(re) <- c("spike", "flash", "pstime", "pftime", "cumflash", "cumpftime", "cumsqpf") re <- data.frame(re, logpf=log(re$pftime+1), logcumf=log(re$cumflash+1), logcumpf=log(re$cumpftime+1), logcumsqpf=log(re$cumsqpf+1)) re$loglogcumsqpf <- log(1 +re$logcumsqpf) return(re) }
import_pattern <- function(filepath) { if (nchar(readChar(filepath, file.info(filepath)$size)) == 0) { warning(paste(filepath, "imported 0 characters.")) } readChar(filepath, file.info(filepath)$size) }
"thregIcure" <- function (formula,data) { cl <- match.call() indx <- match(c("formula", "data"), names(cl), nomatch=0) if (indx[1] ==0) stop("A formula argument is required") mf<- cl[c(1, indx)] f <- Formula(formula) f1<-formula(f,lhs=1) f1<-Formula(f1) mf[[1]] <- as.name("model.frame") mf$formula <- if(missing(data)) terms(f1) else terms(f1, data=data) mf$formula <- f1 mf <- eval(mf, parent.frame()) if (nrow(mf) ==0) stop("No (non-missing) observations") Terms <- terms(mf) Y <- model.extract(mf, "response") if (!inherits(Y, "Surv")) stop("Response must be a survival object") type <- attr(Y, "type") if (type!='interval') stop(paste("thregI package only support \"", type, "\" survival data", sep='')) f2<-formula(f1, lhs = 0) if (length(f2[[2]])!=3) stop(paste("Predictors for both lny0 and mu should be specified")) x_lny0<-model.matrix(f1, data, rhs=1) x_mu<-model.matrix(f1, data, rhs=2) x_lamda<-model.matrix(f1, data, rhs=3) k<-dim(x_lamda)[2] left<-Y[,1] right<-Y[,2] delta<-Y[,3] delta3=matrix(0,length(left),1) for (i in 1 :length(left)) { if (delta[i]==1) {right[i]=left[i] delta3[i]=1} } right_max=10*max(right) delta1=matrix(0,length(left),1) delta2=matrix(0,length(left),1) for (i in 1 :length(left)){ if (delta[i]==0) {right[i]=right_max} else if (left[i]==0) { delta1[i]=1 } else if (delta[i]==3){ delta2[i]=1 } } lny0<-function(para_lny0){x_lny0%*%para_lny0} mu<-function(para_mu){x_mu%*%para_mu} lamda<-function(para_lamda){x_lamda%*%para_lamda} d<-function(para) { para_lny0=para[1:length(dimnames(x_lny0)[[2]])] para_mu=para[(length(dimnames(x_lny0)[[2]])+1):(length(dimnames(x_lny0)[[2]])+length(dimnames(x_mu)[[2]]))] -mu(para_mu)/exp(lny0(para_lny0)) } v<-function(para) { para_lny0=para[1:length(dimnames(x_lny0)[[2]])] exp(-2*lny0(para_lny0)) } su<-function(para){ pnorm((1-d(para)*left)/sqrt(v(para)*left))-exp(2*d(para)/v(para))*pnorm(-(1+d(para)*left)/sqrt(v(para)*left)) } sv<-function(para){ pnorm((1-d(para)*right)/sqrt(v(para)*right))-exp(2*d(para)/v(para))*pnorm(-(1+d(para)*right)/sqrt(v(para)*right)) } cu<-function(para){ para_lamda=para[(length(dimnames(x_lny0)[[2]])+length(dimnames(x_mu)[[2]])+1):(length(dimnames(x_lny0)[[2]])+length(dimnames(x_mu)[[2]])+length(dimnames(x_lamda)[[2]]))] exp(lamda(para_lamda))/(1+exp(lamda(para_lamda))) } logdf<-function(para){ -.5*(log(2*pi*v(para)*(right^3))+(d(para)*right-1)^2/(v(para)*right)) } logf0<-function(para) { -sum(delta1*log(1-sv(para)))-sum(delta2*log(su(para)-sv(para)), na.rm = TRUE)-sum((1-delta1-delta2-delta3)*log(su(para)))-sum(delta3*logdf(para)) } p0<-rep(0,(length(dimnames(x_lny0)[[2]])+length(dimnames(x_mu)[[2]]))) est0<-nlm(logf0, p0, hessian = TRUE) loglik0 = (-1)*est0$minimum logf<-function(para) { -sum(delta1*log(cu(para)*(1-sv(para))))-sum(delta2*log(cu(para)*(su(para)-sv(para))), na.rm = TRUE)-sum((1-delta1-delta2-delta3)*log((1-cu(para))+cu(para)*su(para)))-sum(delta3*logdf(para))-sum(delta3*log(cu(para))) } p<-rep(0,(length(dimnames(x_lny0)[[2]])+length(dimnames(x_mu)[[2]])+length(dimnames(x_lamda)[[2]]))) est<-nlm(logf, p, hessian = TRUE) names(est$estimate) <-c(paste("lny0:",dimnames(x_lny0)[[2]]),paste("mu:",dimnames(x_mu)[[2]]),paste("logit(p):",dimnames(x_lamda)[[2]])) loglik = (-1)*est$minimum fit<-list(coefficients = est$estimate, var = solve(est$hessian), loglik = loglik, AIC = (-2)*loglik+2*(length(dimnames(x_lny0)[[2]])+length(dimnames(x_mu)[[2]])+length(dimnames(x_lamda)[[2]])), Pvalue = 1-pchisq(2*(loglik-loglik0),df=k), iter = est$iterations, call = cl, mf = mf, lny0 = dimnames(x_lny0)[[2]], mu = dimnames(x_mu)[[2]], lamda = dimnames(x_lamda)[[2]]) class(fit) <- 'thregIcure' fit }
"cells10"
test_that("MCMC: exponential", { n_chains <- 2 data <- dreamer_data_linear(n_cohorts = c(10, 20, 30), c(1, 3, 5), 1, 2, 2) mcmc <- dreamer_mcmc( data, mod = model_exp( mu_b1 = 0, sigma_b1 = 1, mu_b2 = 0, sigma_b2 = 1, mu_b3 = 0, sigma_b3 = 1, shape = 1, rate = .01 ), n_iter = 5, silent = TRUE, convergence_warn = FALSE, n_chains = n_chains ) assert_mcmc_format(mcmc, n_chains) test_posterior( mcmc, doses = c(1, 3, 2), prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, true_responses = rlang::expr(b1 + b2 * (1 - exp(- b3 * dose))) ) test_posterior( mcmc, doses = c(1, 3, 2), reference_dose = .5, prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, true_responses = rlang::expr( b1 + b2 * (1 - exp(- b3 * dose)) - (b1 + b2 * (1 - exp(- b3 * reference_dose))) ) ) }) test_that("MCMC: exponential long linear", { n_chains <- 2 t_max <- 4 times <- c(0, 2, 4) data <- dreamer_data_linear( n_cohorts = c(10, 20, 30), dose = c(1, 3, 5), b1 = 1, b2 = 2, sigma = 2, longitudinal = "linear", a = .5, times = times, t_max = t_max ) mcmc <- dreamer_mcmc( data, mod = model_exp( mu_b1 = 0, sigma_b1 = 1, mu_b2 = 0, sigma_b2 = 1, mu_b3 = 0, sigma_b3 = 1, shape = 1, rate = .01, longitudinal = model_longitudinal_linear(0, 1, t_max) ), n_iter = 5, silent = TRUE, convergence_warn = FALSE, n_chains = n_chains ) assert_mcmc_format(mcmc, n_chains, times) test_posterior( mcmc, doses = c(1, 3, 2), times = c(1, 5, 2), prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, a = 10:1, true_responses = rlang::expr( a + time / !!t_max * (b1 + b2 * (1 - exp(- b3 * dose))) ) ) test_posterior( mcmc, doses = c(1, 3, 2), times = c(1, 5, 2), reference_dose = .5, prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, a = 10:1, true_responses = rlang::expr( a + (time / !!t_max) * (b1 + b2 * (1 - exp(- b3 * dose))) - (a + (time / !!t_max) * (b1 + b2 * (1 - exp(- b3 * reference_dose)))) ) ) }) test_that("MCMC: exponential long ITP", { n_chains <- 2 t_max <- 4 times <- c(0, 2, 4) data <- dreamer_data_linear( n_cohorts = c(10, 20, 30), dose = c(1, 3, 5), b1 = 1, b2 = 2, sigma = 2, longitudinal = "linear", a = .5, times = times, t_max = t_max ) mcmc <- dreamer_mcmc( data, mod = model_exp( mu_b1 = 0, sigma_b1 = 1, mu_b2 = 0, sigma_b2 = 1, mu_b3 = 0, sigma_b3 = 1, shape = 1, rate = .01, longitudinal = model_longitudinal_itp(0, 1, t_max = t_max) ), n_iter = 5, silent = TRUE, convergence_warn = FALSE, n_chains = n_chains ) assert_mcmc_format(mcmc, n_chains, times) test_posterior( mcmc, doses = c(1, 3, 2), times = c(1, 5, 2), prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, a = 10:1, c1 = seq(.1, 3, length = 10), true_responses = rlang::expr( a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) * (b1 + b2 * (1 - exp(- b3 * dose))) ) ) test_posterior( mcmc, doses = c(1, 3, 2), times = c(1, 5, 2), reference_dose = .5, prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, a = 10:1, c1 = seq(.1, 3, length = 10), true_responses = rlang::expr( a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) * (b1 + b2 * (1 - exp(- b3 * dose))) - (a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) * (b1 + b2 * (1 - exp(- b3 * reference_dose)))) ) ) }) test_that("MCMC: exponential long IDP", { n_chains <- 2 t_max <- 4 times <- c(0, 2, 4) data <- dreamer_data_linear( n_cohorts = c(10, 20, 30), dose = c(1, 3, 5), b1 = 1, b2 = 2, sigma = 2, longitudinal = "linear", a = .5, times = times, t_max = t_max ) mcmc <- dreamer_mcmc( data, mod = model_exp( mu_b1 = 0, sigma_b1 = 1, mu_b2 = 0, sigma_b2 = 1, mu_b3 = 0, sigma_b3 = 1, shape = 1, rate = .01, longitudinal = model_longitudinal_idp(0, 1, t_max = t_max) ), n_iter = 5, silent = TRUE, convergence_warn = FALSE, n_chains = n_chains ) assert_mcmc_format(mcmc, n_chains, times) test_posterior( mcmc, doses = c(1, 3, 2), times = c(1, 5, 2), prob = c(.25, .75), b1 = 1:10, b2 = 2:11, b3 = 3:12, a = 10:1, c1 = seq(.1, 3, length = 10), c2 = seq(-.1, -.02, length = 10), d1 = seq(3, 4, length = 10), d2 = seq(4, 5, length = 10), gam = seq(.2, .33, length = 10), true_responses = rlang::expr( a + (b1 + b2 * (1 - exp(- b3 * dose))) * ( (1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) + (1 - gam * (1 - exp(- c2 * (time - d1))) / (1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) + (1 - gam) * (time > d2) ) ) ) test_posterior( mcmc, doses = c(1, 3, 2), times = c(1, 5, 2), reference_dose = .5, prob = c(.25, .75), a = 10:1, b1 = 1:10, b2 = 2:11, b3 = 3:12, c1 = seq(.1, 3, length = 10), c2 = seq(-.1, -.02, length = 10), d1 = seq(3, 4, length = 10), d2 = seq(4, 5, length = 10), gam = seq(.2, .33, length = 10), true_responses = rlang::expr( a + (b1 + b2 * (1 - exp(- b3 * dose))) * ( (1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) + (1 - gam * (1 - exp(- c2 * (time - d1))) / (1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) + (1 - gam) * (time > d2) ) - ( a + (b1 + b2 * (1 - exp(- b3 * reference_dose))) * ( (1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) + (1 - gam * (1 - exp(- c2 * (time - d1))) / (1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) + (1 - gam) * (time > d2) ) ) ) ) })
test_that("can construct and access components", { r <- new_rcrd(list(x = 1, y = 2)) expect_equal(length(r), 1) expect_equal(n_fields(r), 2) expect_equal(names(r), NULL) expect_equal(fields(r), c("x", "y")) expect_error(r$x, class = "vctrs_error_unsupported") expect_equal(field(r, "x"), 1) }) test_that("requires format method", { x <- new_rcrd(list(x = 1)) expect_error(format(x), class = "vctrs_error_unimplemented") }) test_that("vec_proxy() transforms records to data frames", { expect_identical( vec_proxy(new_rcrd(list(a = "1"))), new_data_frame(list(a = "1")) ) }) test_that("can't cast list to rcrd", { l <- list( new_rcrd(list(a = "1", b = 3L)), new_rcrd(list(b = "4", a = 2)) ) expect_error( vec_cast(l, new_rcrd(list(a = 1L, b = 2L))), class = "vctrs_error_incompatible_type" ) }) test_that("can recast rcrd from list", { r <- new_rcrd(list(x = integer(), y = numeric())) expect_equal( vec_restore(list(x = 1L, y = 1), r), new_rcrd(list(x = 1L, y = 1)) ) }) test_that("can't cast rcrd to list", { r <- new_rcrd(list(x = 1:2, y = 2:3)) expect_error(vec_cast(r, list()), class = "vctrs_error_incompatible_type") expect_error(vec_cast(r, list()), class = "vctrs_error_incompatible_type") }) test_that("default casts are implemented correctly", { r <- new_rcrd(list(x = 1, y = 1)) expect_error(vec_cast(1, r), class = "vctrs_error_incompatible_type") expect_equal(vec_cast(NULL, r), NULL) }) test_that("can't cast incompatible rcrd", { expect_error( vec_cast( new_rcrd(list(a = "1", b = 3L)), new_rcrd(list(a = "1")) ), class = "vctrs_error_cast_lossy" ) expect_error( vec_cast( new_rcrd(list(a = "1", b = 3L)), new_rcrd(list(a = "1", c = 3L)) ), class = "vctrs_error_cast_lossy" ) expect_error( vec_cast( new_rcrd(list(a = "a", b = 3L)), new_rcrd(list(a = 1, b = 3L)) ), class = "vctrs_error_incompatible_type" ) }) test_that("must be list of equal length vectors", { expect_error(new_rcrd(list()), "list of length 1") expect_error(new_rcrd(list(x = environment())), class = "vctrs_error_scalar_type") expect_error(new_rcrd(list(x = 1:2, y = 1:3)), "same size") }) test_that("names must be unique", { expect_error(new_rcrd(list(1, 2)), class = "vctrs_error_names_cannot_be_empty") expect_error(new_rcrd(list(x = 1, 2)), class = "vctrs_error_names_cannot_be_empty") expect_error(new_rcrd(list(x = 1, x = 2)), class = "vctrs_error_names_must_be_unique") expect_error(new_rcrd(setNames(list(1, 2), "x")), "can't return `NA`") }) test_that("subset assignment throws error", { x <- new_rcrd(list(x = 1)) expect_error( x$y <- 2, class = "vctrs_error_unsupported" ) }) test_that("can supply data frame as fields", { expect_identical( new_rcrd(list(x = 1)), new_rcrd(tibble(x = 1)) ) }) test_that("fields are not recycled", { expect_error( new_rcrd(list(x = 1, y = 1:2)), "must be the same size" ) }) test_that("print and str use format", { local_tuple_methods() r <- tuple(1, 1:100) expect_known_output( file = test_path("test-rcrd-format.txt"), { print(r) cat("\n") str(r[1:10]) cat("\n") str(list(list(list(r, 1:100)))) } ) }) test_that("subsetting methods applied to each field", { local_tuple_methods() x <- tuple(1:2, 1) expect_equal(x[1], tuple(1, 1)) expect_equal(x[[1]], tuple(1, 1)) expect_equal(rep(tuple(1, 1), 2), tuple(c(1, 1), 1)) length(x) <- 1 expect_equal(x, tuple(1, 1)) }) test_that("subset assignment modifies each field", { local_tuple_methods() x <- tuple(c(1, 1), c(2, 2)) expect_error(x[[]] <- tuple(), "missing") x[[1]] <- tuple(3, 3) expect_equal(x, tuple(c(3, 1), c(3, 2))) x[1] <- tuple(4, 4) expect_equal(x, tuple(c(4, 1), c(4, 2))) }) test_that("subset assignment recycles", { local_tuple_methods() x <- tuple(c(1, 1), c(2, 2)) x[1:2] <- tuple(1, 1) expect_equal(x, tuple(c(1, 1), c(1, 1))) x[] <- tuple(2, 2) expect_equal(x, tuple(c(2, 2), c(2, 2))) }) test_that("can sort rcrd", { local_tuple_methods() x <- tuple(c(1, 2, 1), c(3, 1, 2)) expect_equal(xtfrm(x), c(2, 3, 1)) expect_equal(order(x), c(3, 1, 2)) expect_equal(sort(x), tuple(c(1, 1, 2), c(2, 3, 1))) }) test_that("can use dictionary methods on a rcrd", { local_tuple_methods() x <- tuple(c(1, 2, 1), c(3, 1, 3)) expect_equal(unique(x), x[1:2]) expect_equal(duplicated(x), c(FALSE, FALSE, TRUE)) expect_equal(anyDuplicated(x), TRUE) }) test_that("cannot round trip through list", { local_tuple_methods() t <- tuple(1:2, 3:4) expect_error(vec_cast(t, list()), class = "vctrs_error_incompatible_type") }) test_that("can convert to list using as.list() or vec_chop() ( local_tuple_methods() t <- tuple(1:2, 3:4) expect <- list(tuple(1L, 3L), tuple(2L, 4L)) expect_identical(as.list(t), expect) expect_identical(vec_chop(t), expect) }) test_that("dangerous methods marked as unimplemented", { local_tuple_methods() t <- tuple() expect_error(mean(t), class = "vctrs_error_unsupported") expect_error(abs(t), class = "vctrs_error_unsupported") expect_error(is.finite(t), class = "vctrs_error_unsupported") expect_error(is.nan(t), class = "vctrs_error_unsupported") }) test_that("dots are forwarded", { expect_error(new_rcrd(list(foo = "foo"))[1, 2], "undefined columns selected") }) test_that("records are restored after slicing the proxy", { expect_identical(new_rcrd(list(x = 1:2))[1], new_rcrd(list(x = 1L))) }) test_that("can slice with df-cols fields", { x <- new_rcrd(data_frame(x = data_frame(y = 1:2))) out <- vec_slice(x, 2) expect_identical( out, new_rcrd(data_frame(x = data_frame(y = 2L))) ) expect_identical( x[2], out ) expect_identical( x[[2]], out ) }) test_that("can rep with df-cols fields", { x <- new_rcrd(data_frame(x = data_frame(y = 1:2))) expect_identical( rep(x, length.out = 4), vec_slice(x, c(1:2, 1:2)) ) }) test_that("can assign with df-cols fields", { x <- new_rcrd(data_frame(x = data_frame(y = 1:3))) y <- new_rcrd(data_frame(x = data_frame(y = FALSE))) exp <- new_rcrd(data_frame(x = data_frame(y = c(1L, 2L, 0L)))) expect_identical(vec_assign(x, 3, y), exp) out <- x out[[3]] <- y expect_identical(out, exp) }) test_that("can resize with df-cols fields", { x <- new_rcrd(data_frame(x = data_frame(y = 1:3))) length(x) <- 2 expect_identical(x, new_rcrd(data_frame(x = data_frame(y = 1:2)))) length(x) <- 4 expect_identical(x, new_rcrd(data_frame(x = data_frame(y = c(1:2, NA, NA))))) }) test_that("`[[` preserves type of record fields ( x <- new_rcrd(list(x = 1:3, a = list(1, 2:3, 4:6))) expect_identical(field(x[3], "a"), list(4:6)) expect_identical(field(x[[3]], "a"), list(4:6)) })
.newt <- function(fn,start,...,eps.p = 1e-08,eps.v = NULL, maxit = 50,verb = FALSE) { p.o <- start itno <- 1 repeat { fj <- fn(p.o,...) v <- fj$fval t1 <- if(is.null(eps.v)) NULL else sum(abs(v)) J <- as.matrix(fj$jacobian) if(qr(J)$rank < ncol(J)) { cat("Singular Jacobian.\n") rslt <- if(is.null(eps.v)) NA else if(t1 < eps.v) p.o else NA break } else { p.n <- p.o - solve(J) %*% v t2 <- max(abs(p.n - p.o)) if(verb) { tmp <- format(round(c(p.o,p.n,v,t2,t1),6)) np <- length(v) v1 <- paste(tmp[1:np],collapse = " ") v2 <- paste(tmp[(np + 1):(2 * np)],collapse = " ") v3 <- paste(tmp[(2 * np + 1):(3 * np)],collapse = " ") v4 <- tmp[3 * np + 1] v5 <- tmp[3 * np + 2] cat("\nIteration : ",itno,"\n",sep = "") cat("Old par : ",v1,"\n",sep = "") cat("New par : ",v2,"\n",sep = "") cat("Test ch.par: ",v4,"\n",sep = "") cat("Fn. vals. : ",v3,"\n",sep = "") if(!is.null(t1)) cat("Test f.val: ",v5,"\n",sep = "") } if((!is.null(t1) && t1 < eps.v) | t2 < eps.p) { rslt <- p.n break } itno <- itno + 1 if(itno > maxit) { cat("Newton's method failed to converge in\n") cat(maxit,"iterations.\n") rslt <- NA break } p.o <- p.n } } as.vector(rslt) }
colorSpec <- function( data, wavelength, quantity='auto', organization='auto', specnames=NULL ) { n = NROW(data) if( ! is.numeric(data) ) { log.string( ERROR, "data has incorrect type '%s'.", typeof(data) ) return(NULL) } if( ! is.numeric(wavelength) ) { log.string( ERROR, "wavelength has incorrect type '%s'.", typeof(wavelength) ) return(NULL) } if( length(wavelength) != n ) { log.string( ERROR, "NROW(data) = %d != %d = length(wavelength) mismatch.", n, length(wavelength) ) return(NULL) } if( is.integer(wavelength) ) wavelength = as.numeric(wavelength) if( ! isIncreasingSequence(wavelength) ) { log.string( ERROR, "wavelength is not increasing." ) return(NULL) } if( is.null( dim(data) ) ) { spectra = 1 if( is.null(specnames) ) specnames = deparse(substitute(data)) attr(data,'specname') = NULL } else if( is.matrix(data) ) { spectra = ncol(data) if( is.null(specnames) ) specnames = colnames(data) } else { log.string( ERROR, "data is numeric, but neither vector nor matrix." ) return(NULL) } dups = sum(duplicated(specnames)) ok = is.character(specnames) && length(specnames)==spectra && dups==0 if( ! ok ) { if( 0 < spectra ) { specnames = sprintf( "S%d", 1:spectra ) combo = paste(specnames,collapse=',') if( 80 < nchar(combo) ) combo = paste( substr(combo,1,76), '...', collapse='' ) if( 0 < dups ) log.string( WARN, "specnames are invalid (there are %d duplicates). Using '%s' instead.", dups, combo ) else log.string( WARN, "specnames are invalid. Using '%s' instead.", combo ) } else { specnames = character(0) } } if( quantity == "auto" ) { quantity = guessSpectrumQuantity( specnames, '' ) if( is.na( quantity ) ) { log.string( ERROR, "Cannot guess spectrum quantity from the specnames." ) return(NULL) } } if( is.na( spectrumTypeFromQuantity( quantity ) ) ) { log.string( ERROR, "quantity='%s' is invalid.", quantity ) return(NULL) } if( organization == "auto" ) organization = ifelse( is.null( dim(data) ), "vector", "matrix" ) ok = organization %in% c("df.col","df.row","matrix","vector") if( ! ok ) { log.string( ERROR, "organization='%s' is invalid\n", organization ) return(NULL) } if( organization == "vector" ) { if( spectra != 1 ) { log.string( ERROR, "organization='%s' is invalid, because there are %d spectra in data\n", organization, spectra ) return(NULL) } out = as.numeric(data) } else if( organization == "matrix" ) { out = data dim(out) = c(n,spectra) } else if( organization == "df.col" ) { out = data.frame( Wavelength=wavelength ) if( 0 < spectra ) out = cbind( out, as.data.frame(data) ) row.names(out) = NULL } else if( organization == "df.row" ) { tdata = t(data) colnames(tdata) = wavelength out = data.frame( row.names=specnames ) out$spectra = tdata } class( out ) = c( "colorSpec", class(out) ) wavelength( out ) = wavelength quantity( out ) = quantity specnames( out ) = specnames attr( out, "metadata" ) = list() return( out ) } is.colorSpec <- function(x) { if( ! "colorSpec" %in% class(x) ) { log.string( DEBUG, "'%s' class '%s' is invalid.", deparse(substitute(x)), class(x) ) return(FALSE) } if( is.na(organization(x)) ) { log.string( DEBUG, "'%s' organization '%s' is invalid.", deparse(substitute(x)), organization(x) ) return(FALSE) } if( ! type(x) %in% c("light","responsivity.light","material","responsivity.material") ) { log.string( DEBUG, "'%s' type '%s' is invalid.", deparse(substitute(x)), type(x) ) return(FALSE) } wave = wavelength(x) if( ! is.double( wave ) ) { log.string( DEBUG, "'%s' wavelengths are not double-precision.", deparse(substitute(x)) ) return(FALSE) } if( ! isIncreasingSequence(wave) ) { log.string( DEBUG, "'%s' wavelengths are not increasing.", deparse(substitute(x)) ) return(FALSE) } return(TRUE) } as.colorSpec.default <- function( ... ) { log.string( WARN, "This function is designed to be called from other packages." ) return(NULL) } isValidQuantity <- function( .quantity ) { return( ! is.na( spectrumTypeFromQuantity( .quantity ) ) ) } isValidType <- function( .type ) { return( .type %in% c("light","responsivity.light","material","responsivity.material") ) } guessSpectrumType <- function( .specnames, .header ) { pattern = "keyword[: \t]+scanner" if( any( grepl(pattern,.header,ignore.case=TRUE) ) ) return( "responsivity.material" ) pattern = "power|radian|photon" if( all( grepl(pattern,.specnames,ignore.case=TRUE) ) ) return( "light" ) if( any( grepl( "^IT8", .header ) ) ) return( "material" ) if( 1 < length(.specnames) ) { pattern_vec = c("^R","^G","^B","^X","^Y","^Z","^L","^M","^S","^V") if( allDistinctMatches( pattern_vec, .specnames, .ignore=T ) ) return( "responsivity.light" ) } else { pattern = "quantum|QE|gray" if( all( grepl(pattern,.specnames,ignore.case=TRUE) ) ) return( "responsivity.light" ) } pattern = "trans|reflect|absorb" if( all( grepl(pattern,.specnames,ignore.case=TRUE) ) ) return( "material" ) if( any( grepl(pattern,.header,ignore.case=TRUE) ) ) return( "material" ) return( as.character(NA) ) } spectrumTypeFromQuantity <- function( .quantity ) { pattern = "^(power|energy|photons|photons/sec)->(electrical|neural|action)$" if( grepl( pattern, .quantity ) ) return( "responsivity.light" ) pattern = "^material->(electrical|neural|action)$" if( grepl( pattern, .quantity ) ) return( "responsivity.material" ) pattern = "^(power|energy|photons|photons/sec)$" if( grepl( pattern, .quantity ) ) return( "light" ) pattern = "^(reflectance|transmittance|absorbance)$" if( grepl( pattern, .quantity ) ) return( "material" ) return( as.character(NA) ) } guessSpectrumQuantity <- function( .specnames, .header ) { pattern = '^ out = sub( pattern, "\\1", .header, ignore.case=T ) idx = which( nchar(out) < nchar(.header) ) if( 0 < length(idx) ) { value = tolower( out[idx[1]] ) if( isValidQuantity(value) ) return(value) pattern = "photon[- ]+|photon$" if( grepl( pattern, value ) ) return('photons') } pattern = '^MEAS_TYPE[ \t]*"?([A-Z]+)"?' out = sub( pattern, "\\1", .header, ignore.case=T ) idx = which( nchar(out) < nchar(.header) ) if( 0 < length(idx) ) { value = toupper( out[idx[1]] ) if( value == "REFLECTIVE" ) return( 'reflectance' ) if( value == "TRANSMISSIVE" ) return( 'transmittance' ) if( value=="EMISSION" || value=="AMBIENT" ) return( 'energy' ) if( value == "SENSITIVITY" ) return( 'energy->neural' ) } pattern = "keyword[: \t]+scanner" if( any( grepl(pattern,.header,ignore.case=TRUE) ) ) return( 'material->electrical' ) type = guessSpectrumType( .specnames, .header ) ; log.string( DEBUG, "guessed type=%s", type ) if( is.na(type) || type == "light" ) { if( any( grepl( "photon", .specnames, ignore.case=T ) ) ) return( "photons" ) if( any( grepl( "^(energy|power)", .specnames, ignore.case=T ) ) ) return( "energy" ) return( "energy" ) } else if( is.na(type) || type == "responsivity.light" ) { if( all( grepl( "^(quant|QE)", .specnames, ignore.case=T ) ) ) return( 'photons->electrical' ) if( any( grepl( "photon", .header, ignore.case=T ) ) ) return( "photons->action" ) if( length(.specnames)==1 && grepl( "gray", .specnames, ignore.case=T ) ) return( 'energy->electrical' ) if( allDistinctMatches( c("^R","^G","^B"), .specnames, .ignore=T ) ) return( 'energy->electrical' ) if( allDistinctMatches( c("^x","^y","^z"), .specnames, .ignore=T ) ) return( 'energy->neural' ) if( allDistinctMatches( c("^L","^M","^S"), .specnames, .ignore=T ) ) return( 'energy->neural' ) if( allDistinctMatches( "^V", .specnames, .ignore=T ) ) return( 'energy->neural' ) return( 'power->action' ) } else if( is.na(type) || type == "material" ) { if( any( grepl( "reflect", .specnames, ignore.case=T ) ) ) return( "reflectance" ) if( any( grepl( "transmit", .specnames, ignore.case=T ) ) ) return( "transmittance" ) if( any( grepl( "absorb", .specnames, ignore.case=T ) ) ) return( "absorbance" ) if( any( grepl( "IT8[.]7/1", .header ) ) ) return( "transmittance" ) if( any( grepl( "IT8[.]7/2", .header ) ) ) return( "reflectance" ) if( any( grepl( 'QUANTITY[ \t]+"?TRANSMIT', .header, ignore.case=T ) ) ) return( "transmittance" ) if( any( grepl( 'QUANTITY[ \t]+"?REFLECT', .header, ignore.case=T ) ) ) return( "reflectance" ) } else if( is.na(type) || type == "responsivity.material" ) { if( allDistinctMatches( c("^R","^G","^B"), .specnames, .ignore=T ) ) return( 'material->electrical' ) if( allDistinctMatches( c("^x","^y","^z"), .specnames, .ignore=T ) ) return( 'material->neural' ) if( allDistinctMatches( c("^L","^M","^S"), .specnames, .ignore=T ) ) return( 'material->neural' ) return( 'material->action' ) } log.object( DEBUG, .specnames ) log.string( DEBUG, "Cannot guess quantity from .specnames and .header." ) return( as.character(NA) ) } validQuantities <- function( .type ) { qvalid = as.character(NA) ; if( .type == "light" ) qvalid = c("energy","power","photons") else if( .type == "responsivity.light" ) qvalid = c("energy->electrical","energy->neural","energy->action","power->electrical","power->neural","power->action","photons->electrical","photons->neural","photons->action") else if( .type == "material" ) qvalid = c("reflectance","transmittance","absorbance") else if( .type == "responsivity.material" ) qvalid = c("electrical","neural","action") return( qvalid ) } numSpectra.colorSpec <- function(x) { org = organization.colorSpec(x) if( org == "vector" ) return(1L) else if( org == "matrix" ) return( ncol(x) ) else if( org == "df.col" ) return( ncol(x)-1L ) else if( org == "df.row" ) return( nrow(x) ) return( 0 ) } numWavelengths.colorSpec <- function(x) { org = organization.colorSpec(x) if( org == "df.row" ) return( ncol( x[[ ncol(x) ]] ) ) else return( NROW(x) ) } organization.colorSpec <- function(x) { if( is.null(dim(x)) ) return( "vector" ) if( is.matrix(x) ) return( "matrix" ) if( is.data.frame(x) ) { if( is.matrix( x[[ncol(x)]] ) ) return( "df.row" ) else if( grepl( "^wave|^wl|nm$", colnames(x)[1], ignore.case=T ) ) return( "df.col" ) } log.object( ERROR, x, 'str' ) log.string( ERROR, "cannot determine organization of object x." ) return( as.character(NA) ) } "organization<-.colorSpec" <- function( x, value ) { ok = value %in% c("vector","matrix","df.row","df.col") if( ! ok ) { log.string( ERROR, "organization='%s' is invalid.", value ) return(x) } org = organization(x) if( org == value ) return( x ) m = numSpectra(x) if( value == "vector" && m != 1 ) { log.string( ERROR, "cannot reorganize to vector because return( x ) } out = colorSpec( as.matrix(x), wavelength(x), quantity=quantity(x), organization=value ) if( ! is.null(out) ) { for( a in c('metadata','sequence','calibrate','emulate') ) attr(out,a) = attr(x,a) } return(out) } coredata.colorSpec <- function( x, forcemat=FALSE ) { wave = wavelength(x) if( numSpectra(x) == 0 ) { out = matrix( 0, length(wave), 0 ) rownames(out) = as.character(wave) return( out ) } org = organization.colorSpec(x) if( org == "vector" ) { out = as.double(x) if( forcemat ) dim(out) = c(length(wave),1) else names(out) = as.character(wave) } else if( org == "matrix" ) { out = x } else if( org == "df.col" ) { out = as.matrix.data.frame( x[ , 2:ncol(x), drop=F ] ) } else if( org == "df.row" ) { out = t( x[[ncol(x)]] ) } else { log.string( FATAL, "Internal error. organization='%s' is unknown.", org ) return(NULL) } class( out ) = 'numeric' for( a in c( "wavelength","step.wl","quantity","metadata","sequence","calibrate","specname",'emulate') ) attr(out,a) = NULL if( is.matrix(out) ) { colnames(out) = specnames(x) rownames(out) = as.character(wave) } return(out) } as.matrix.colorSpec <- function( x, ... ) { return( coredata(x,forcemat=TRUE) ) } as.data.frame.colorSpec <- function( x, row.names=NULL, optional=FALSE, organization='auto', ... ) { if( organization == 'auto' ) { organization = ifelse( organization(x)=='df.row', 'row', 'col' ) } out = x if( organization == 'col' ) organization(out) = 'df.col' else if( organization == 'row' ) organization(out) = 'df.row' else { log.string( ERROR, "organization='%s' is invalid.", organization ) return(NULL) } class(out) = 'data.frame' return( out ) } extradata.colorSpec <- function( x ) { org = organization(x) if( org != "df.row" ) { return( data.frame( row.names=specnames(x) ) ) } m = ncol(x) if( m == 1 ) { return( data.frame( row.names=row.names(x) ) ) } out = x[ 1:(m-1) ] class(out) = 'data.frame' return( out ) } "extradata<-.colorSpec" <- function( x, add=FALSE, value ) { if( ! is.null(value) && ! is.data.frame(value) ) { log.string( ERROR, "RHS object '%s' is not a data.frame, and not NULL.", deparse(substitute(value))[1] ) return(x) } if( is.null(value) && add ) { return(x) } if( is.data.frame(value) && ncol(value)==0 ) { return(x) } org = organization(x) if( org != "df.row" ) { log.string( ERROR, "organization(x) = '%s' is invalid. Please change to 'df.row' first.", org ) return(x) } if( is.data.frame(value) ) { if( nrow(value) != nrow(x) ) { log.string( ERROR, "Row count mismatch. LHS %d != %d RHS.", nrow(x), nrow(value) ) return(x) } if( add ) { namevec = unlist( sapply( list(value,x), colnames ) ) idx = which( duplicated(namevec) ) if( 0 < length(idx) ) { log.string( ERROR, "Cannot add new extradata, because one of its column names already appears in the current extradata, e.g. '%s'.", namevec[idx[1]] ) return(x) } if( ncol(x) == 1 ) out = cbind( value, x ) else out = cbind( x[1:(ncol(x)-1)], value, x[ncol(x)] ) } else { out = cbind( value, x[ncol(x)] ) } } else { out = x[ncol(x)] } class(out) = class(x) for( a in c('wavelength','step.wl','quantity','metadata','sequence','calibrate','emulate') ) { attr( out, a ) = attr( x, a ) } specnames(out) = specnames(x) return( out ) } wavelength.colorSpec <- function(x) { wave = attr(x,"wavelength") if( is.null(wave) && is.data.frame(x) ) { wave = x[[1]] if( is.null(wave) ) log.string( FATAL, "Internal Error. Cannot determine wavelength of object '%s'", deparse(substitute(x)) ) } return( wave ) } "wavelength<-.colorSpec" <- function( x, value ) { n = numWavelengths.colorSpec( x ) if( length(value) != n ) { log.string( ERROR, "length(wavelength)=%d is invalid.", length(value) ) return(x) } if( ! isIncreasingSequence( value ) ) { log.string( ERROR, "wavelength sequence is not increasing." ) return(x) } org = organization.colorSpec( x ) if( org == "df.col" ) { x[[1]] = as.numeric(value) } else if( org == "df.row" ) { wavecurrent = as.numeric( colnames( x[[ncol(x)]] ) ) if( any( 0.5 < abs(wavecurrent - value) ) ) colnames( x[[ncol(x)]] ) = as.character( value ) } if( org != "df.col" ) attr( x, "wavelength" ) = as.numeric(value) if( isRegularSequence(value) ) step = ifelse( 1 < n, (value[n] - value[1])/(n-1), 0 ) else step = NULL attr( x,"step.wl") = step return( x ) } type.colorSpec <- function(x) { return( spectrumTypeFromQuantity( quantity(x) ) ) } quantity.colorSpec <- function(x) { return( attr(x,"quantity") ) } "quantity<-.colorSpec" <- function( x, value ) { if( ! isValidQuantity( value ) ) { log.string( ERROR, "quantity=%s is invalid\n", value ) return(x) } attr(x,"quantity") = value return(x) } specnames.colorSpec <- function(x) { spectra = numSpectra.colorSpec(x) if( spectra == 0 ) return( character(0) ) org = organization.colorSpec(x) if( org == "vector" ) return( attr( x, "specname" ) ) else if( org == "matrix" ) return( colnames(x,do.NULL=F) ) else if( org == "df.col" ) { cname = colnames(x,do.NULL=F) return( cname[ 2:ncol(x) ] ) } else if( org == "df.row" ) { return( row.names(x) ) } return( rep(as.character(NA),spectra) ) } "specnames<-.colorSpec" <- function(x, value) { n = numSpectra.colorSpec(x) if( length(value) != n ) { log.string( ERROR, "length(value) = %d is invalid. It is not equal to numSpectra = %d", length(value), n ) return(x) } if( n == 0 ) return(x) count = sum(duplicated(value)) if( 0 < count ) { log.string( ERROR, "The %d names for the spectra have %d duplicates. Names are ignored.", n, count) return(x) } org = organization.colorSpec(x) if( org == "vector" ) { attr( x, "specname" ) = value } else if( org == "matrix" ) colnames(x) = value else if( org == "df.col" ) colnames(x)[ 2:ncol(x) ] = value else if( org == "df.row" ) row.names(x) = value return(x) } is.regular.colorSpec <- function(x) { return( ! is.null( attr(x,"step.wl") ) ) } step.wl.colorSpec <- function(x) { out = attr(x,"step.wl") if( ! is.null(out) ) return(out) wave = wavelength(x) n = length(wave) range.wl = range( wave ) out = ifelse( 2<=n, (range.wl[2]-range.wl[1])/(n-1), 1 ) return(out) } metadata.colorSpec <- function( x, ... ) { dots <- c(...) metadata = attr( x, "metadata" ) if (length (dots) == 0L) metadata else if( length (dots) == 1L) metadata[dots][[1]] else metadata[dots] } "metadata<-.colorSpec" <- function( x, add=FALSE, value ) { mask = nzchar( names(value) ) if( ! all (mask) ) log.string( WARN, "options without name are discarded: %d", which(!mask) ) if( add ) { metadata = attr( x, "metadata" ) attr(x,"metadata") <- modifyList( metadata, value[mask] ) } else { attr(x,"metadata") <- value[mask] } return( x ) } if( 0 ) { isHuman.colorSpec <- function(x) { m = numSpectra(x) if( m<1 || 3<m ) return(FALSE) if( ! grepl( 'neural$', quantity(x) ) ) return(FALSE) theNames = tolower(specnames(x)) return( all( theNames %in% c('x','y','z') ) || all( theNames %in% c('l','m','s') ) ) } } regularizeWavelength <- function( .wavelength ) { n = length( .wavelength ) if( n <= 1 ) return( .wavelength ) return( seq( .wavelength[1], .wavelength[n], length.out=n ) ) } isRegularSequence <- function( x, epsilon=1.e-6 ) { if( length(x) <= 1 ) return(TRUE) xr = regularizeWavelength(x) return( max( abs(x - xr) ) <= epsilon ) } isIncreasingSequence <- function( x ) { n = length(x) if( n <= 1 ) return(TRUE) sdiff = diff(x) if( n == 2 ) return( 0 < sdiff ) if( any( sdiff < 0 ) ) return(FALSE) if( n == 3 ) return( sum(sdiff==0) <= 1 ) sdiff = sdiff[ 2:(n-2) ] return( all( 0 < sdiff ) ) } isStrictlyIncreasingSequence <- function( x ) { n = length(x) if( n <= 1 ) return(TRUE) return( all( 0 < diff(x) ) ) } is.regular <- function(x) { UseMethod("is.regular") } step.wl <- function(x) { UseMethod("step.wl") } numSpectra <- function(x) { UseMethod("numSpectra") } numWavelengths <- function(x) { UseMethod("numWavelengths") } coredata <- function( x, forcemat=FALSE ) { UseMethod("coredata") } extradata <- function( x ) { UseMethod("extradata") } "extradata<-" <- function( x, add=FALSE, value ) { UseMethod("extradata<-") } if( FALSE ) { isValid <- function( x ) { UseMethod("isValid") } } wavelength <- function(x) { UseMethod("wavelength") } "wavelength<-" <- function( x, value ) { UseMethod("wavelength<-") } type <- function(x) { UseMethod("type") } quantity <- function(x) { UseMethod("quantity") } "quantity<-" <- function( x, value ) { UseMethod("quantity<-") } organization <- function(x) { UseMethod("organization") } "organization<-" <- function(x, value) { UseMethod("organization<-") } specnames <- function(x) { UseMethod("specnames") } "specnames<-" <- function(x, value) { UseMethod("specnames<-") } metadata <- function(x,...) { UseMethod("metadata") } "metadata<-" <- function(x,add=FALSE,value) { UseMethod("metadata<-") } as.colorSpec <- function(...) { UseMethod("as.colorSpec") }
plot_threshold <- function(beta_threshold, est_eff) { beta_threshold <- abs(beta_threshold) est_eff <- abs(est_eff) if (est_eff > beta_threshold) { dd <- dplyr::tibble( est_eff = est_eff, beta_threshold = beta_threshold ) dd <- dplyr::mutate(dd, `Above Threshold` = est_eff - beta_threshold) dd <- dplyr::rename(dd, `Below Threshold` = beta_threshold) dd <- dplyr::select(dd, -est_eff) dd <- tidyr::gather(dd, key, val) dd <- dplyr::mutate(dd, inference = "group") y_thresh <- dplyr::filter(dd, key == "Below Threshold") y_thresh <- dplyr::pull(dplyr::select(y_thresh, val)) y_thresh_text <- y_thresh + sqrt(.005 * abs(y_thresh)) effect_text <- est_eff + (.025 * est_eff) cols <- c(" } else if (est_eff < beta_threshold) { dd <- dplyr::tibble(est_eff = est_eff, beta_threshold = beta_threshold) dd <- dplyr::mutate(dd, `Above Estimated Effect, Below Threshold` = abs(est_eff - beta_threshold)) dd <- dplyr::mutate(dd, `Below Threshold` = est_eff) dd <- dplyr::select(dd, -beta_threshold) dd <- dplyr::select(dd, -est_eff) dd <- tidyr::gather(dd, key, val) dd <- dplyr::mutate(dd, inference = "group") y_thresh <- sum(abs(dd$val)) if (est_eff < 0) { y_thresh <- y_thresh * -1 } y_thresh_text <- y_thresh + sqrt(.005 * abs(y_thresh)) effect_text <- est_eff + sqrt(.025 * abs(est_eff)) cols <- c("lightgray", " } p <- ggplot2::ggplot(dd, ggplot2::aes(x = inference, y = val, fill = key)) + ggplot2::geom_col(position = "stack") + ggplot2::geom_hline(yintercept = est_eff, color = "black") + ggplot2::annotate("text", x = 1, y = effect_text, label = "Estimated Effect") + ggplot2::geom_hline(yintercept = y_thresh, color = "red") + ggplot2::annotate("text", x = 1, y = y_thresh_text, label = "Threshold") + ggplot2::scale_fill_manual("", values = cols) + ggplot2::theme_bw() + ggplot2::theme(axis.text.x = ggplot2::element_blank(), axis.ticks = ggplot2::element_blank()) + ggplot2::xlab(NULL) + ggplot2::ylab("Effect (abs. value)") + ggplot2::theme(legend.position = "top") return(p) }
data(tortoise) data(whale) data(teasel) x <- splitA(whale) whaleT <- x$T whaleF <- x$F mp <- function(A, pow) { if (pow == 1) { A } else { x <- A for (i in (2:pow)) { A <- x %*% A } } A } surv <- matrix(numeric(150 * 4), ncol = 4) for (x in 1:150) { surv[x, ] <- colSums(mp(whaleT, x)) } plot(surv[, 1] / surv[1, 1], type = "l", ylim = c(0, 1), las = 1, main = "Fig 5.1", xlab = "Age (years)", ylab = expression(paste("Survivorship ", italic(l(x)))) ) T20 <- mp(whaleT, 20) whaleF %*% T20 %*% diag(1 / colSums(T20)) fert <- numeric(200) for (x in 1:200) { T20 <- mp(whaleT, x) phi <- whaleF %*% T20 %*% diag(1 / colSums(T20)) fert[x] <- phi[1, 1] } op <- par(mar = c(5, 5, 4, 1)) plot(fert, type = "l", ylim = c(0, 0.07), las = 1, main = "Fig 5.2", xlab = "Age (years)", ylab = "" ) mtext("Age-specific fertility", 2, 3.5) par(op) A <- tortoise[["med.high"]] sens <- sensitivity(A) def.par <- par(no.readonly = TRUE) par(mfrow = c(3, 1), mar = c(1.5, 4.5, 1, 2), oma = c(1.5, 0, 1.5, 0), cex = 1.2) ep <- barplot(sens[1, ], ylim = c(0, .4), col = "white", las = 1, ylab = expression(paste("to ", italic(F[i]))), names = "" ) box() text(ep, -.05, 1:8, xpd = TRUE) ep <- barplot(diag(sens), ylim = c(0, .4), col = "white", las = 1, ylab = expression(paste("to ", italic(P[i]))), names = "" ) box() text(ep, -.05, 1:8, xpd = TRUE) barplot(c(sens[row(sens) == col(sens) + 1], 0), ylim = c(0, .4), col = "white", las = 1, ylab = expression(paste("to ", italic(G[i]))) ) box() text(ep, -.05, c(1:7, NA), xpd = TRUE) mtext(expression(paste("Fig 9.3. Sensitivity of ", lambda, "...")), 3, outer = TRUE, cex = 1.4) mtext(expression(paste("Size class ", italic(i))), 1, outer = TRUE, cex = 1.2) par(def.par) sens <- sensitivity(teasel) plot(log10(c(sens)), type = "s", las = 1, ylim = c(-5, 2), xlab = "Stage at time t", xaxt = "n", ylab = expression(paste(Log[10], " sensitivity of ", lambda)), main = "Fig 9.4c Stair step plot" ) axis(1, seq(1, 36, 6), 1:6) text(log10(c(sens)), cex = .7, adj = c(0, -.3), labels = paste(" ", 1:6, rep(1:6, each = 6), sep = "") ) elas <- elasticity(tortoise[[3]]) el <- c(F = sum(elas[1, ]), P = sum(diag(elas)), G = sum(elas[row(elas) == col(elas) + 1])) plot(c(0, 1, 2, 0), c(0, sqrt(3), 0, 0), type = "l", lwd = 2, main = "Fig 9.11 Triangle plot", xlab = "Tortoise summed elasticities", ylab = "", axes = FALSE ) text(c(0, 2, 1), c(0, 0, sqrt(3)), names(el), cex = 1.5, pos = c(1, 1, 3), xpd = TRUE) points(2 - 2 * el[1] - el[3], el[3] * sqrt(3), cex = 1.5, pch = 16, col = "blue") pods <- c( 0, 0.0067, 0.1632, 0, 0.9535, 0.8827, 0, 0, 0, 0.0802, 0.9586, 0, 0, 0, 0.0414, 0.9752, 0, 0.0062, 0.1737, 0, 1, 0.9020, 0, 0, 0, 0.0694, 0.9582, 0, 0, 0, 0.0418, 0.9855, 0, 0.0037, 0.0988, 0, 0.9562, 0.9030, 0, 0, 0, 0.0722, 0.9530, 0, 0, 0, 0.0406, 0.9798, 0, 0.0043, 0.1148, 0, 1, 0.9015, 0, 0, 0, 0.0727, 0.9515, 0, 0, 0, 0.0485, 0.9667, 0, 0.0042, 0.1054, 0, 0.8165, 0.8903, 0, 0, 0, 0.0774, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0027, 0.0732, 0, 1, 0.9123, 0, 0, 0, 0.0730, 0.9515, 0, 0, 0, 0.0485, 0.9545, 0, 0.0025, 0.0651, 0, 1, 0.9254, 0, 0, 0, 0.0746, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0047, 0.1159, 0, 1, 0.9200, 0, 0, 0, 0.0800, 0.9706, 0, 0, 0, 0.0294, 0.9608, 0, 0.0068, 0.1761, 0, 1, 0.9241, 0, 0, 0, 0.0759, 0.9562, 0, 0, 0, 0.0438, 1, 0, 0.0061, 0.1418, 0, 1, 0.9167, 0, 0, 0, 0.0833, 0.9286, 0, 0, 0, 0.0714, 1, 0, 0.0050, 0.1251, 0, 1, 0.9216, 0, 0, 0, 0.0784, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0021, 0.0542, 0, 1, 0.9254, 0, 0, 0, 0.0746, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0027, 0.0732, 0, 1, 0.9286, 0, 0, 0, 0.0714, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0045, 0.1220, 0, 1, 0.9286, 0, 0, 0, 0.0714, 0.9515, 0, 0, 0, 0.0485, 1, 0, 0.0052, 0.1428, 0, 1, 0.9286, 0, 0, 0, 0.0714, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0037, 0.0998, 0, 1, 0.9286, 0, 0, 0, 0.0714, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0047, 0.1273, 0, 1, 0.9286, 0, 0, 0, 0.0714, 0.9515, 0, 0, 0, 0.0485, 0.9810, 0, 0.0024, 0.0797, 0, 1, 0.8929, 0, 0, 0, 0.0595, 0.9515, 0, 0, 0, 0.0485, 1 ) p1 <- matrix(pods, nrow = 18, byrow = TRUE) colnames(p1) <- paste("a", rep(1:4, each = 4), 1:4, sep = "") x <- order(paste("a", 1:4, rep(1:4, each = 4), sep = "")) p1 <- p1[, x] covmat <- cov(p1) persp(covmat, theta = 45, phi = 15, box = FALSE, main = expression("Fig 10.10a Killer Whale Covariances") ) w1 <- matrix(apply(p1, 2, mean), nrow = 4) wS <- sensitivity(w1) contmat <- covmat * c(wS) %*% t(c(wS)) persp(contmat, theta = 45, phi = 15, box = FALSE, main = expression(paste("Fig 10.10b Contributions to V(", lambda, ")")) ) A <- matrix(apply(contmat, 2, mean), nrow = 4) dimnames(A) <- dimnames(whale) round(A / sum(A), 3)
context("question-checkbox") test_that("correct messages are not included", { q <- question( "test", answer("A", correct = TRUE, message = "msg **1**"), answer("B", correct = TRUE, message = "msg _2_"), answer("C", correct = FALSE, message = "msg **3**"), answer("D", correct = FALSE, message = "msg _4_"), answer("E", correct = FALSE, message = "msg **5**") ) ans <- question_is_correct(q, c("A", "B", "C")) expect_equivalent(ans$correct, FALSE) expect_equivalent(as.character(ans$messages), "msg <strong>3</strong>") ans <- question_is_correct(q, c("A", "B", "C", "D")) expect_equivalent(ans$correct, FALSE) expect_equivalent(as.character(ans$messages), "msg <strong>3</strong>\nmsg <em>4</em>") ans <- question_is_correct(q, c("A")) expect_equivalent(ans$correct, FALSE) expect_equivalent(ans$messages, NULL) ans <- question_is_correct(q, c("A", "B")) expect_equivalent(ans$correct, TRUE) expect_equivalent(as.character(ans$messages), "msg <strong>1</strong>\nmsg <em>2</em>") })
"pCBB3" <- function(theta,delta,s,t) { pc<-pcopula1(theta,delta,psiKS,phiBB3,ivpsiKS,ivphiBB3,s,t); resu<-pc }
NULL fit_two_distr <- function(data, ...) UseMethod("fit_two_distr") fit_two_distr.default <- function(data, random, aggregated, ...) { call <- match.call() name_random <- attr(random, "name") name_aggregated <- attr(aggregated, "name") random <- random(data) aggregated <- aggregated(data) llr <- NULL if (!is.null(random$full_output) && !is.null(aggregated$full_output)) { llr <- llrtest(random, aggregated) } structure(list(call = call, name = list(random = name_random, aggregated = name_aggregated), model = list(random = random, aggregated = aggregated), llr = llr), class = "fit_two_distr") } fit_two_distr.count <- function(data, random = smle_pois, aggregated = smle_nbinom, n_est = c(random = 1, aggregated = 2), ...) { call <- match.call() mapped_data <- map_data(data) ind <- mapped_data[["i"]] N <- nrow(mapped_data) res <- fit_two_distr.default(data, random = random, aggregated = aggregated, ...) res$call <- call res$data_class <- class(data) param <- list(random = NULL, aggregated = NULL) if (!is.null(res$model$random$full_output)) { param$random <- coef(summary(res$model$random)) param$random <- param$random[sort(rownames(param$random)),, drop = FALSE] } if (!is.null(res$model$aggregated$full_output)) { param$aggregated <- coef(summary(res$model$aggregated)) new_param <- list( prob = estimate_param(res$model$aggregated, quote(x2/(x1 + x2)), "norm") ) param$aggregated <- rbind_param(param$aggregated, new_param) param$aggregated <- param$aggregated[sort(rownames(param$aggregated)),, drop = FALSE] } range_ind <- 0:max(ind) freq <- setNames(as.data.frame(table(ind)), c("category", "observed")) freq$category <- as.numeric(levels(freq$category))[freq$category] freq <- merge(x = data.frame(category = range_ind), y = freq, by = "category", all = TRUE) freq[is.na(freq)] <- 0 freq$random <- NA if (!is.null(res$model$random$full_output)) { freq$random <- N * dpois(x = range_ind, lambda = coef(res$model$random)[["lambda"]]) } freq$aggregated <- NA if (!is.null(res$model$aggregated$full_output)) { freq$aggregated <- N * dnbinom(x = range_ind, mu = coef(res$model$aggregated)[["mu"]], size = coef(res$model$aggregated)[["k"]]) } gof <- list(random = NULL, aggregated = NULL) if (!is.null(res$model$random$full_output)) { gof$random <- chisq.test2(freq$observed, freq$random, n_est = n_est[["random"]], rescale.p = TRUE) } if (!is.null(res$model$aggregated$full_output)) { gof$aggregated <- chisq.test2(freq$observed, freq$aggregated, n_est = n_est[["aggregated"]], rescale.p = TRUE) } res$param <- param res$freq <- freq res$gof <- gof res } fit_two_distr.incidence <- function(data, random = smle_binom, aggregated = smle_betabinom, n_est = c(random = 1, aggregated = 2), ...) { call <- match.call() mapped_data <- map_data(data) ind <- mapped_data[["i"]] N <- nrow(mapped_data) n <- unique(mapped_data[["n"]]) if (length(n) != 1) stop(paste0("Current implementation only deals ", "with equal size sampling units.")) res <- fit_two_distr.default(mapped_data, random = random, aggregated = aggregated, ...) res$call <- call res$data_class <- class(data) param <- list(random = NULL, aggregated = NULL) if (!is.null(res$model$random$full_output)) { param$random <- coef(summary(res$model$random)) param$random <- param$random[sort(rownames(param$random)),, drop = FALSE] } if (!is.null(res$model$aggregated$full_output)) { param$aggregated <- coef(summary(res$model$aggregated)) new_param <- list( rho = estimate_param(res$model$aggregated, quote(x2/(x2 + 1)), "norm"), alpha = estimate_param(res$model$aggregated, quote(x1/x2), "norm"), beta = estimate_param(res$model$aggregated, quote((1 - x1)/x2), "norm") ) param$aggregated <- rbind_param(param$aggregated, new_param) param$aggregated <- param$aggregated[sort(rownames(param$aggregated)),, drop = FALSE] } range_ind <- 0:n freq <- setNames(as.data.frame(table(ind)), c("category", "observed")) freq$category <- as.numeric(levels(freq$category))[freq$category] freq <- merge(x = data.frame(category = range_ind), y = freq, by = "category", all = TRUE) freq[is.na(freq)] <- 0 if (!is.null(res$model$random$full_output)) { freq$random <- N * dbinom(x = range_ind, size = n, prob = coef(res$model$random)[["prob"]]) } if (!is.null(res$model$aggregated$full_output)) { freq$aggregated <- N * dbetabinom(x = range_ind, size = n, prob = coef(res$model$aggregated)[["prob"]], theta = coef(res$model$aggregated)[["theta"]]) } gof <- list(random = NULL, aggregated = NULL) if (!is.null(res$model$random$full_output)) { gof$random <- chisq.test2(freq$observed, freq$random, n_est = n_est[["random"]], rescale.p = TRUE) } if (!is.null(res$model$aggregated$full_output)) { gof$aggregated <- chisq.test2(freq$observed, freq$aggregated, n_est = n_est[["aggregated"]], rescale.p = TRUE) } res$param <- param res$freq <- freq res$gof <- gof res } print.fit_two_distr <- function(x, ...) { cat("Fitting of two distributions by maximum likelihood\n", "for '", x$data_class[1L], "' data.\n", "\nParameter estimates:\n", "\n(1) ", x$name$random, " (random):\n", sep = "") if (!is.null(x$param$random)) { print(x$param$random[, 1:2, drop = FALSE]) } else { cat("Maximum likelihood procedure did not succeed.\n") } cat("\n(2) ", x$name$aggregated, " (aggregated):\n", sep = "") if (!is.null(x$param$aggregated)) { print(x$param$aggregated[, 1:2, drop = FALSE]) } else { cat("Maximum likelihood procedure did not succeed.\n") } invisible(x) } summary.fit_two_distr <- function(object, ...) { res <- object structure(res, class = "summary.fit_two_distr") } print.summary.fit_two_distr <- function(x, ...) { cat("Fitting of two distributions by maximum likelihood\n", "for '", x$data_class[1L], "' data.\n", "Parameter estimates:\n", "\n(1) ", x$name$random, " (random):\n", sep = "") if (!is.null(x$param$random)) { printCoefmat(x$param$random) } else { cat("Maximum likelihood procedure did not succeed.\n") } cat("\n(2) ", x$name$aggregated, " (aggregated):\n", sep = "") if (!is.null(x$param$aggregated)) { printCoefmat(x$param$aggregated) } else { cat("Maximum likelihood procedure did not succeed.\n") } invisible(x) } plot.fit_two_distr <- function(x, ..., breaks = NULL) { if (!is.null(breaks)) { stopifnot(is.numeric(breaks)) stopifnot(is.wholenumber(breaks)) stopifnot(breaks > 0) fac <- rep(0:ceiling(nrow(x$freq)/breaks), each = breaks)[1:nrow(x$freq)] tmp <- split(x$freq, fac, drop = TRUE) x$freq <- do.call(rbind, lapply(tmp, function(xx) { res <- xx[0, ] res[1,1] <- paste0(xx[1, 1], "-", xx[nrow(xx), 1]) res[1, 2:ncol(res)] <- colSums(xx[2:ncol(xx)]) res })) } rownames(x$freq) <- x$freq$category freq_long <- setNames(as.data.frame.table(as.matrix(x$freq[-1])), c("Number per sampling unit", "key", "Frequency")) freq_long$key <- factor(tocamel(freq_long$key), levels = c("Observed", "Aggregated", "Random")) gg <- ggplot(freq_long, aes(x = `Number per sampling unit`, y = Frequency, fill = key)) gg <- gg + geom_bar(stat = "identity", position = "dodge", color = "black", size = 0.5) gg <- gg + scale_fill_manual(values = c(Observed = "black", Aggregated = "grey", Random = "white")) gg <- gg + theme_bw() gg <- gg + theme(legend.justification = c(0.98, 0.98), legend.position = c(0.98, 0.98), legend.background = element_rect(size = 0.5, linetype = "solid", color = "black"), legend.title = element_blank()) print(gg) invisible(NULL) }
context("Users/groups") tenant <- Sys.getenv("AZ_TEST_TENANT_ID") user <- Sys.getenv("AZ_TEST_USERPRINCIPALNAME") admin_user <- Sys.getenv("AZ_TEST_ADMINUSERPRINCIPALNAME") if(tenant == "" || user == "") skip("User method tests skipped: login credentials not set") if(!interactive()) skip("User method tests skipped: must be in interactive session") scopes <- c("https://graph.microsoft.com/.default", "openid", "offline_access") token <- AzureAuth::get_azure_token(scopes, tenant, .az_cli_app_id, version=2) gr <- ms_graph$new(token=token) test_that("User/group read functionality works", { me <- gr$get_user() expect_equal(me$properties$userPrincipalName, admin_user) me2 <- gr$get_user(user) expect_equal(me2$properties$userPrincipalName, user) email <- me2$properties$mail me3 <- gr$get_user(email=email) expect_equal(me3$properties$userPrincipalName, user) name <- me2$properties$displayName me4 <- gr$get_user(name=name) expect_equal(me4$properties$userPrincipalName, user) users <- gr$list_users() expect_true(is.list(users) && all(sapply(users, is_user))) objs <- me$list_object_memberships() expect_true(is.character(objs)) grps1 <- me$list_group_memberships() expect_true(is.character(grps1)) grps3 <- me$list_direct_memberships() expect_true(all(sapply(grps3, function(x) is_group(x) || is_directory_role(x)))) expect_true(all(sapply(grps3, function(g) !is.null(g$properties$id)))) grp <- gr$get_group(grps1[1]) expect_true(is_group(grp) && !is.null(grp$properties$id)) grps <- gr$list_groups() expect_true(is.list(grps) && all(sapply(grps, is_group))) owned <- me$list_owned_objects() expect_true(is.list(owned) && all(sapply(owned, inherits, "az_object"))) owned_apps <- me$list_owned_objects(type="application") expect_true(is.list(owned_apps) && all(sapply(owned_apps, is_app))) created <- me$list_created_objects() expect_true(is.list(created) && all(sapply(owned, inherits, "az_object"))) created_apps <- me$list_created_objects(type="application") expect_true(is.list(created_apps) && all(sapply(created_apps, is_app))) })
kRp.cluster <- function(txts, lang, TT.path, TT.preset){ num.texts <- length(txts) analysis.res <- sapply(1:num.texts, function(txt.idx){ txt <- txts[txt.idx] message(paste0("Analyzing text: ", txt, " [", txt.idx, "/", num.texts, "]...\n")) POS.analysis.res <- treetag(txt, treetagger="manual", lang=lang, TT.options=list(path=TT.path, preset=TT.preset)) frq.analysis.res <- freq.analysis(POS.analysis.res) frq.vector <- c(describe(frq.analysis.res)[["freq.token"]]) / sum(describe(frq.analysis.res)[["freq.token"]]) hyph.analysis.res <- hyphen(POS.analysis.res) rdb.vector <- c( describe(POS.analysis.res)[["avg.sentc.length"]], describe(POS.analysis.res)[["avg.word.length"]], describe(hyph.analysis.res)[["avg.syll.word"]] ) lxd.analysis.res <- lex.div(frq.analysis.res, measure=c("MATTR", "HD-D", "MTLD"), char=c()) res.vector.names <- c(names(frq.vector), "avg.sntc.len", "avg.word.len", "avg.syll.word", "MATTR", "HDD", "MTLD") all.res <- c( as.numeric(frq.vector), as.numeric(rdb.vector), lxd.analysis.res@MATTR[["MATTR"]], lxd.analysis.res@HDD[["HDD"]], lxd.analysis.res@MTLD[["MTLD"]]) names(all.res) <- res.vector.names return(all.res) }) return(t(analysis.res)) }
sgnht = function( logLik, dataset, params, stepsize, logPrior = NULL, minibatchSize = 0.01, a = 0.01, nIters = 10^4L, verbose = TRUE, seed = NULL ) { sgnht = sgnhtSetup( logLik, dataset, params, stepsize, logPrior, minibatchSize, a, seed ) options = list( "nIters" = nIters, "verbose" = verbose ) paramStorage = runSGMCMC( sgnht, params, options ) return( paramStorage ) } sgnhtSetup = function( logLik, dataset, params, stepsize, logPrior = NULL, minibatchSize = 0.01, a = 0.01, seed = NULL ) { sgnht = createSGMCMC( logLik, logPrior, dataset, params, stepsize, minibatchSize, seed ) sgnht$ranks = getRanks( params ) sgnht$a = convertList( a, sgnht$params ) class(sgnht) = c( "sgnht", "sgmcmc" ) sgnht$dynamics = declareDynamics( sgnht, seed ) return( sgnht ) }
test_that("Multivariate normal distribution", { mu <- c(1,2) sigma <- matrix(c(4,2,2,3), ncol=2) dist <- dist_multivariate_normal(mu = list(mu), sigma = list(sigma)) dimnames(dist) <- c("a", "b") expect_equal(format(dist), "MVN[2]") expect_equal( mean(dist), matrix(c(1,2), nrow = 1, dimnames = list(NULL, c("a", "b"))) ) expect_equal(covariance(dist), list(sigma)) expect_equal( quantile(dist, 0.1), matrix(c(qnorm(0.1, mu[1], sqrt(sigma[1,1])), qnorm(0.1, mu[2], sqrt(sigma[2,2]))), nrow = 1, dimnames = list(NULL, c("a", "b"))) ) skip_if_not_installed("mvtnorm") expect_equivalent(quantile(dist, 0.1, type = "equicoordinate"), mvtnorm::qmvnorm(0.1, mean = mu, sigma = sigma)$quantile) expect_equal(density(dist, cbind(1, 2)), mvtnorm::dmvnorm(c(1, 2), mean = mu, sigma = sigma)) expect_equal(density(dist, cbind(-3, 4)), mvtnorm::dmvnorm(c(-3, 4), mean = mu, sigma = sigma)) expect_equivalent(cdf(dist, cbind(1, 2)), mvtnorm::pmvnorm(upper = c(1,2), mean = mu, sigma = sigma)) expect_equivalent(cdf(dist, cbind(-3, 4)), mvtnorm::pmvnorm(c(-3, 4), mean = mu, sigma = sigma)) })
context("frequencyStats") test_that("inputs are correct", { expect_error(frequencyStats("string"), "frequencyStats expects a Wave object") expect_error(frequencyStats(1), "frequencyStats expects a Wave object") }) test_that("plotting is ok", { data(sheep, package="seewave") expect_silent(frequencyStats(sheep, plot=TRUE)) })
source("ESEUR_config.r") plot_layout(2, 1) lnd=read.csv(paste0(ESEUR_dir, "developers/like-n-dis.csv.xz"), as.is=TRUE) plot(lnd$Number, lnd$Like, type="l", col=point_col, xaxs="i", xlab="Number", ylab="Like\n") lines(loess.smooth(lnd$Number, lnd$Like, span=0.3), col=loess_col) spectrum(lnd$Like, main="Spectrum density", sub="", col=point_col, xlab="Frequency", ylab="Density\n") lnd$l_0=grepl("0$", lnd$Number) lnd$l_1=grepl("1$", lnd$Number) lnd$l_2=grepl("2$", lnd$Number) lnd$l_3=grepl("3$", lnd$Number) lnd$l_4=grepl("4$", lnd$Number) lnd$l_5=grepl("5$", lnd$Number) lnd$l_6=grepl("6$", lnd$Number) lnd$l_7=grepl("7$", lnd$Number) lnd$l_8=grepl("8$", lnd$Number) lnd$l_9=grepl("9$", lnd$Number) lnd$f_1=grepl("^1", lnd$Number) lnd$f_2=grepl("^2", lnd$Number) lnd$f_3=grepl("^3", lnd$Number) lnd$f_4=grepl("^4", lnd$Number) lnd$f_5=grepl("^5", lnd$Number) lnd$f_6=grepl("^6", lnd$Number) lnd$f_7=grepl("^7", lnd$Number) lnd$f_8=grepl("^8", lnd$Number) lnd$f_9=grepl("^9", lnd$Number) like_mod=glm(Like ~ log(Number)+ (l_0+ l_2+ l_4+l_5+ l_6+ l_8) +( f_3+ f_4+f_5+ f_6+ f_7 ) , data=lnd) summary(like_mod) dislike_mod=glm(Dislike ~ log(Number)+ (l_0+ l_2+ l_4+l_5+ l_6+ l_8) +( f_3+ f_4+f_5+ f_6+ f_7 ) , data=lnd) summary(dislike_mod)
filter_fact_rows <- function(st, name = NULL, ...) { UseMethod("filter_fact_rows") } filter_fact_rows.star_schema <- function(st, name = NULL, ...) { stopifnot(!is.null(name)) stopifnot(name %in% get_dimension_names(st)) dimension <- get_dimension(st, name) key <- dplyr::filter(tibble::as_tibble(dimension), ...)[[1]] st$fact[[1]] <- st$fact[[1]][st$fact[[1]][[sprintf("%s_key", name)]] %in% key, ] st }
print.fmdsd <- function(x, mean.print=FALSE, var.print=FALSE, cor.print=FALSE, skewness.print=FALSE, kurtosis.print=FALSE, digits=2, ...) { cat("group variable: ",x$group, "\n") cat("variables: ", x$variables, "\n") cat("---------------------------------------------------------------\n") cat("inertia\n"); print(x$inertia, digits=3, ...) cat("---------------------------------------------------------------\n") cat("scores\n"); print(x$scores, ...) if (mean.print) {n.group <- length(x$means) n.var <- length(x$means[[1]]) Means <- matrix(unlist(x$means), nrow = n.group, ncol = n.var, byrow = TRUE, dimnames = list(NULL, paste("mean", names(x$means[[1]]), sep = "."))) Means <- data.frame(group=names(x$means), Means, stringsAsFactors = TRUE) colnames(Means)[1]=colnames(x$scores)[1] st.dev <- unlist(lapply(lapply(x$variances, diag), sqrt)) Means <- data.frame(Means, matrix(st.dev, nrow = n.group, ncol = n.var, byrow = TRUE, dimnames = list(NULL, paste("sd", names(x$means[[1]])))), stringsAsFactors = TRUE) cat("---------------------------------------------------------------\n") cat("means, standard deviations and norm by group\n") print(Means, digits=digits, ...) } if (var.print) {cat("---------------------------------------------------------------\n") cat("variances/covariances by group\n"); print(x$variances, digits=digits, ...) } if (cor.print) {cat("---------------------------------------------------------------\n") cat("correlations by group\n"); print(x$correlations, digits=digits, ...) } if (skewness.print) {cat("---------------------------------------------------------------\n") cat("skewness coefficients by group\n"); print(x$skewness, digits=digits, ...) } if (kurtosis.print) {cat("---------------------------------------------------------------\n") cat("kurtosis coefficients by group\n"); print(x$kurtosis, digits=digits, ...) } return(invisible(x)) }
setClass(Class="mtkDesignerResult", representation=representation( main="data.frame" ), contains=c("mtkResult"), prototype(main=data.frame()) ) mtkDesignerResult <- function(main=data.frame(), information=list()) { res <- new("mtkDesignerResult", main=main, information=information) return(res) } setMethod(f="summary", signature="mtkDesignerResult", definition=function(object,...){ cat("ABOUT THE PARAMETERS USED : \n") if(length(object@information)>0) show(summary(object@information, ...)) else cat(" none") cat("\n") cat("ABOUT THE GENERATED EXPERIMENT DESIGN :\n\n") cat(" number of simulations :",nrow(object@main),"\n\n") show(summary(object@main,...)) } ) setMethod(f="plot", signature="mtkDesignerResult", definition=function(x,y, ...){ if(!missing(y))plot(x@main, y, ...) else plot(x@main, ...) } ) setMethod(f="print", signature="mtkDesignerResult", definition=function(x,...){ cat("USED PARAMETERS : \n") if(length(x@information)>0) print(x@information,...) else cat(" none") cat("\n") cat("EXPERIMENTS DESIGN :\n\n") print(x@main,...) } )
context('lcMethod') rngReset() setClass('lcMethodTest', contains = 'lcMethod') m = new( 'lcMethodTest', null = NULL, vNA = NA, vNaN = NaN, logical = TRUE, int = -3L, num = -2.5, char = 'a', fac = factor('b', levels = c('a', 'b')), form = A~B, call = 1 + 2 * 3, name = xvar ) test_that('name', { name = getName(m) expect_equal(name, 'undefined') }) test_that('shortname', { name = getShortName(m) expect_equal(name, 'undefined') }) test_that('length', { expect_length(new('lcMethodTest'), 0) expect_length(new('lcMethodTest', a = 1), 1) expect_length(new('lcMethodTest', a = 1, b = NULL), 2) }) test_that('method argument values', { expect_equivalent(m$null, NULL) expect_equivalent(m[['vNA']], NA) expect_equivalent(m$vNA, NA) expect_equivalent(m$vNaN, NaN) expect_equivalent(m$logical, TRUE) expect_equivalent(m$int, -3L) expect_equivalent(m$num, -2.5) expect_equivalent(m$char, 'a') expect_equivalent(m$fac, factor('b', levels = c('a', 'b'))) expect_equivalent(m$form, A ~ B) expect_equivalent(m$call, 1 + 2 * 3) expect_equivalent(m[['name', eval = FALSE]], quote(xvar)) expect_error(m$name, 'xvar') expect_error(m$missing) expect_error(m[['missing']]) xvar = 2 expect_equivalent(m$name, xvar) }) test_that('take local over global scope', { m = new('lcMethodTest', a = 1, var = globalVar) assign('globalVar', value = 5, envir = .GlobalEnv) globalVar = 2 expect_equal(m$var, 2) rm('globalVar', envir = .GlobalEnv) }) test_that('argument value in global scope', { m = new('lcMethodTest', a = 1, var = globalVar) assign('globalVar', value = 7, envir = .GlobalEnv) expect_equal(m$var, 7) rm('globalVar', envir = .GlobalEnv) }) test_that('unevaluated values', { expect_null(m[['null', eval = FALSE]]) expect_true(is.na(m[['vNA', eval = FALSE]])) expect_true(is.nan(m[['vNaN', eval = FALSE]])) expect_true(isTRUE(m[['logical', eval = FALSE]])) expect_is(m[['int', eval = FALSE]], 'call') expect_is(m[['num', eval = FALSE]], 'call') expect_is(m[['char', eval = FALSE]], 'character') expect_is(m[['fac', eval = FALSE]], 'call') expect_is(m[['form', eval = FALSE]], 'call') expect_is(m[['form', eval = FALSE]], 'call') expect_equivalent(deparse(m[['call', eval = FALSE]]), '1 + 2 * 3') expect_is(m[['name', eval = FALSE]], 'name') expect_error(m[['missing', eval = FALSE]]) }) test_that('dependency function evaluation', { method = lcMethodTestKML() expect_is(method$centerMethod, 'function') }) test_that('local variables', { f = function() { xvar = 2 new('lcMethodTest', name = xvar) } expect_error(f()$name) g = function() { xvar = 2 method = new('lcMethodTest', name = xvar) xvar = 3 method$name } expect_equal(g(), 3) }) test_that('internal variable reference', { method = new('lcMethodTest', iter = 1e3, warmup = floor(iter / 2)) expect_equal(method$warmup, floor(method$iter / 2)) }) test_that('variable of argument name', { warmup = 3 method = new('lcMethodTest', iter = 1e3, warmup = warmup) expect_equal(method$warmup, warmup) }) test_that('formula', { method = new('lcMethodTest', formula = A ~ B, formula.sigma = ~C) expect_is(formula(method), 'formula') expect_error(formula(method, 'missing')) expect_equal(formula(method), A ~ B) expect_equal(formula(method, 'sigma'), ~ C) }) test_that('empty update', { m2 = update(m) expect_equal(names(m2), names(m)) }) test_that('update add single argument', { srcNames = names(m) m2 = update(m, new = 1) expect_equal(names(m), srcNames) expect_equal(m2$new, 1) expect_equal(setdiff(names(m2), 'new'), names(m)) expect_equal(update(m, a = 2)$a, 2) expect_null(update(m, a = NULL)$a) expect_equal(update(m, c = 2)$c, 2) m3 = update(m, newf = A ~ B) expect_named(m3, c('newf', names(m)), ignore.order = TRUE) expect_equal(m3$newf, A ~ B) }) test_that('update with eval', { xvar = 2 m0 = new('lcMethodTest', a = 1, b = 'a', c = NULL, d = NA, e = xvar) m1 = update(m0, new = xvar, .eval = TRUE) expect_equal(deparse(m0[['e', eval = FALSE]]), 'xvar') expect_equal(m1$new, xvar) }) test_that('update with formula eval', { xvar = ~ 1 m0 = new('lcMethodTest', a = 1, f = A ~ 0) m1 = update(m0, f = xvar, .eval = TRUE) expect_equal(m1$f, A ~ 1) }) test_that('update formula', { method = new('lcMethodTest', a = 1, f = A ~ 1) expect_equal(update(method, f = . ~ B)$f, A ~ B) }) test_that('update.lcMethod with local variables', { xvar = 2 method = new('lcMethodTest', e = xvar) u = update(method, e = xvar) xvar = 3 expect_equal(u$e, 3) }) test_that('environment()', { envir = new.env() envir$xvar = 3 expect_error(m$name) environment(m) = envir expect_equal(m$name, envir$xvar) }) test_that('variable from custom environment', { method = new('lcMethodTest', name = xvar) expect_error(method$name) envir = new.env() envir$xvar = 5 expect_error(method$name) expect_equal(method[['name', envir = envir]], 5) }) test_that('evaluate', { expect_error(m$name) m2 = evaluate(m) expect_equal(names(m2), names(m)) expect_error(m$name) envir = new.env() envir$xvar = 9 m3 = evaluate(m, envir = envir) expect_equal(m3$name, 9) expect_error(m$name) }) test_that('substitute', { xvar = 2 method = new('lcMethodTest', a = 1, b = 'a', c = NULL, d = NA, e = xvar) method2 = evaluate.lcMethod(method) expect_equal(method2[['a', eval = FALSE]], 1) expect_null(method2[['c', eval = FALSE]]) expect_equal(method2[['e', eval = FALSE]], 2) }) test_that('.arg error', { expect_error(new('lcMethodTest', a = 1, .b = 'a'), '\\.') }) test_that('negative nClusters error', { expect_error(new('lcMethodTest', nClusters = -1)) }) test_that('print', { expect_output(print(m)) }) test_that('show', { expect_output(show(m)) }) test_that('as.data.frame(eval=FALSE)', { refDf = data.frame( null = NA, vNA = NA, vNaN = NaN, logical = TRUE, int = '-3L', num = '-2.5', char = 'a', fac = 'factor(\"b\", levels = c(\"a\", \"b\"))', form = 'A ~ B', call = '1 + 2 * 3', name = 'xvar', stringsAsFactors = FALSE ) df = as.data.frame(m, eval = FALSE) expect_length(df, length(m)) expect_named(df, names(m)) expect_equal(df, refDf) }) test_that('as.data.frame(eval=TRUE)', { refDf = data.frame( null = NA, vNA = NA, vNaN = NaN, logical = TRUE, int = -3L, num = -2.5, char = 'a', fac = factor('b', levels = c('a', 'b')), form = 'A ~ B', call = 7, name = 'xvar', stringsAsFactors = FALSE ) df = as.data.frame(m, eval = TRUE) expect_length(df, length(m)) expect_named(df, names(m)) expect_equal(df, refDf) }) test_that('as.data.frame with symbols', { xvar = 2 df = as.data.frame(m, eval = TRUE) expect_length(df, length(m)) expect_named(df, names(m)) expect_equal(df$name, xvar) }) test_that('as.list', { xvar = 2 method = new('lcMethodTest', a = 1, b = 'a', c = NULL, d = NA, e = xvar) xvar = 3 expect_equal(as.list(method), list(a = 1, b = 'a', c = NULL, d = NA, e = xvar)) expect_length(as.list(method, eval = FALSE), length(method)) }) test_that('as.list with function', { method = lcMethodTestKML() lis = as.list(method, args = kml::parALGO) expect_length(setdiff(names(lis), formalArgs(kml::parALGO)), 0) }) test_that('as.list with two functions', { method = lcMethodTestKML() funs = c(kml::parALGO, kml::kml) lis = as.list(method, args = funs) expect_length(setdiff(names(lis), union(formalArgs(funs[[1]]), formalArgs(funs[[2]]))), 0) })
LM13=function(trat, resp, ylab="Dependent", error="SE", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, pointshape = 21, round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~trat+I(trat^3)) mods=summary(moda)$coefficients modm=lm(media~dose+I(dose^3)) if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} if(r2=="all"){r2=round(summary(moda)$r.squared,2)} coef1=coef(moda)[1] coef2=coef(moda)[2] coef3=coef(moda)[3] s1 = s = sprintf("~~~%s == %e %s %e*%s %s %e*%s^3 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")} data1=data.frame(trat=unique(trat), resp=media, media=media, desvio) xp=seq(min(trat),max(trat),length.out = 1000) preditos=data.frame(x=xp, y=predict(moda,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y predesp=predict(moda) predobs=resp if(point=="mean"){ graph=ggplot(data1,aes(x=trat,y=media)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill="gray")} grafico=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize)+ scale_color_manual(name="",values=1,label=parse(text = s1))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){grafico=grafico+scale_x_log10()} models=mods model=moda r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} vif=vif.test(moda) predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=5000) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "VIF"=vif, grafico) print(graficos) }
UnitSimplex <- function( n, k=1 ) { n <- as.integer( n ) k <- as.integer( k ) T <- EdgeSubdivision( n=n-1, k=k ) S <- diag( rep(1.0,n) ) subS <- array( 0.0, dim=c(n,n,k^(n-1)) ) if (k==1) { subS[,,1] <- S } else { for (i in 1:k^(n-1)) { subS[,,i] <- SimplexCoord(S,T[,,i]) } } a <- SVIFromColor(S,T) mesh <- list(type="UnitSimplex",mvmesh.type=1L,n=n,m=n-1L,vps=n,S=subS,V=a$V,SVI=a$SVI,k=k) class(mesh) <- "mvmesh" return(mesh) } SolidSimplex <- function( n, k=1 ) { n <- as.integer( n ) k <- as.integer( k ) T <- EdgeSubdivision( n=n, k=k ) M <- dim(T)[3] S <- rbind( diag( rep(1,n) ), rep(0,n) ) subS <- array( 0.0, c(n+1,n,M) ) if (k==1) { subS[,,1] <- S } else { for (i in 1:M) { subS[,,i] <- SimplexCoord(S,T[,,i]) } } a <- SVIFromColor(S,T) mesh <- list(type="SolidSimplex",mvmesh.type=2L,n=n,m=n,vps=n+1L,S=subS,V=a$V,SVI=a$SVI,k=k) class(mesh) <- "mvmesh" return(mesh) } UnitSphere <- function( n, k=1, method="dyadic", p=2, positive.only=FALSE ) { n <- as.integer( n ) k <- as.integer( k ) stopifnot( n > 1, k >= 0, method %in% c("dyadic","edgewise"), length(p)==1, p > 0, is.logical(positive.only) ) if (method=="edgewise") { a <- UnitSphereEdgewise( n=n, k=k, p=p, positive.only=positive.only ) } else { a <- UnitSphereDyadic( n=n, k=k, p=p, positive.only=positive.only ) } return(a) } UnitSphereEdgewise <- function( n, k, p, positive.only ) { n <- as.integer( n ) k <- as.integer( k ) stopifnot(k > 0) a <- UnitSimplex( n=n, k=k ) V <- a$V M <- nrow(V) SVI <- a$SVI if (p != 1.0) { r <- LpNorm( V, p ) for (i in 1:M) { V[i,] <- V[i,]/r[i] } } if (!positive.only ) { newptr <- rep( 0L, M ) for (i in 1:((2^n)-1)) { y <- ConvertBase( i, 2, n ) signs <- (-1)^y newM <- nrow(V) newV <- rbind( V, matrix(NA,nrow=M, ncol=n ) ) for (j in 1:M) { tmp <- signs*V[j,] l <- MatchRow( tmp, newV ) if ( length(l) == 0 ) { newM <- newM + 1 newV[newM,] <- tmp newptr[j] <- newM } else { newptr[j] <- l[1] } } V <- newV[1:newM,] newSVI <- matrix( 0L, nrow=n, ncol=ncol(a$SVI) ) for (j in 1:ncol(newSVI)) { for (m in 1:n) { newSVI[m,j] <- newptr[ SVI[m,j] ] } } SVI <- cbind(SVI,newSVI) } } nSVI <- ncol(SVI) subS <- array( 0.0, c(n,n,nSVI) ) for (i in 1:nSVI) { for (j in 1:n) { subS[j,,i] <- V[ SVI[j,i], ] } } mesh <- list( type="UnitSphere, edgewise",mvmesh.type=3L,n=n,m=n-1L,vps=n, S=subS, V=V, SVI=SVI, k=k, p=p , positive.only=positive.only) class(mesh) <- "mvmesh" return( mesh ) } UnitSphereDyadic <- function( n, k, start="diamond", p, positive.only ) { n <- as.integer(n) k <- as.integer(k) stopifnot( n > 1, k >= 0, p > 0, is.logical(positive.only), start %in% c("diamond","icos3d" ) ) if (start=="diamond") { a <- UnitSphereEdgewise( n=n, k=1, p=2, positive.only=positive.only ) } else { if (start=="icos3d") { if (n == 3) { if (!positive.only) { a <- Icosahedron( ) } else { stop("start='icos3d' not allowed when positive.only=TRUE") } } else { stop('Starting shape "icos3d" is only allowed in 3-dimensions') } } } V <- a$V SVI <- a$SVI if (k > 0) { for (i in 1:k) { b <- EdgeSubdivisionMulti( V, SVI, k=2, normalize=TRUE, p=p ) V <- b$V SVI <- b$SVI } } nS <- ncol(SVI) S <- array( 0.0, dim=c(n,n,nS)) for (j in 1:nS) { S[,,j] <- V[SVI[,j], ] } mesh <- list( type="UnitSphere, dyadic", mvmesh.type=4L, n=n, m=n-1L, vps=n, S=S, V=V, SVI=SVI, k=k, p=p, start=start, positive.only=positive.only ) class(mesh) <- "mvmesh" return(mesh) } UnitBall <- function( n, k=1, method="dyadic", p=2, positive.only=FALSE ) { n <- as.integer( n ) k <- as.integer( k ) sphere <- UnitSphere( n=n, k=k, method=method, p=p, positive.only=positive.only ) origin <- rep(0.0,n) newV <- rbind( sphere$V, origin, deparse.level=0 ) nV <- nrow(newV) nS <- dim(sphere$S)[3] newS <- array( 0.0, dim=c(n+1,n,nS) ) for (i in 1:nS) { newS[,,i] <- rbind( sphere$S[,,i], origin ) } newSVI <- rbind( sphere$SVI, rep( nV, nS ) ) mesh <- list(type=paste("UnitBall,",method),mvmesh.type=ifelse(method=="edgewise",5L,6L), n=n,m=n,vps=n+1L,S=newS,V=newV,SVI=newSVI, k=k,method=method,p=p,positive.only=positive.only) class(mesh) <- "mvmesh" return(mesh) } PolarSphere <- function( n, breaks=c(rep(4,n-2),8), p=2, positive.only=FALSE ) { n <- as.integer( n ) stopifnot( n >= 2 ) rect.mesh <- SolidRectangle( a=rep(0.0,n-1), b=c(rep(pi,n-2),2*pi), breaks=breaks) nV <- nrow(rect.mesh$V) V <- Polar2Rectangular( r=rep(1.0,nV), theta=rect.mesh$V ) nS <- dim(rect.mesh$S)[3] vps <- as.integer(2^(n-1)) S <- array( 0.0, dim=c(vps,n,nS) ) for (k in 1:nS) { for (j in 1:vps) { S[j,,k] <- V[ rect.mesh$SVI[j,k], ] } } mesh <- list(type="PolarSphere",mvmesh.type=9L, n=n,m=n-1L,vps=vps,S=S,V=V,SVI=rect.mesh$SVI, breaks=breaks,p=p,positive.only=positive.only) class(mesh) <- "mvmesh" return(mesh) } PolarBall <- function( n, breaks=c(rep(4,n-2),8), p=2, positive.only=FALSE ) { n <- as.integer( n ) sphere <- PolarSphere( n=n, breaks=breaks, p=p, positive.only=positive.only ) origin <- rep(0.0,n) newV <- rbind( sphere$V, origin, deparse.level=0 ) nV <- nrow(newV) nS <- dim(sphere$S)[3] vps <- as.integer(2^(n-1)+1) newS <- array( 0.0, dim=c(vps,n,nS) ) for (k in 1:nS) { newS[,,k] <- rbind( sphere$S[,,k], origin ) } newSVI <- rbind( sphere$SVI, rep( nV, nS ) ) mesh <- list(type="PolarBall",mvmesh.type=10L, n=n,m=n,vps=vps,S=newS,V=newV,SVI=newSVI, breaks=breaks,p=p,positive.only=positive.only) class(mesh) <- "mvmesh" return(mesh) } rmvmesh <- function( n, mesh, weights=rep(1,ncol(mesh$SVI)) ) { stopifnot( n >= 1, class(mesh)=="mvmesh", length(weights)==ncol(mesh$SVI) ) dimS <- dim(mesh$S) vps <- mesh$vps; d <- mesh$n; nS <- dimS[3] x <- matrix( 0.0, nrow=n, ncol=d ) which.splx <- sample.int( n=nS, size=n, replace=TRUE, prob=weights ) if ( mesh$m+1 == mesh$vps ) { u <- matrix( rexp( n*vps),nrow=vps,ncol=n ) u.sum <- colSums(u) for (i in 1:n) { u[,i] <- u[,i]/u.sum[i] } for (i in 1:n) { j <- which.splx[i] x[i,] <- u[,i] %*% mesh$S[,,j] } return(x) } a <- rep(0.0,d); b <- a if ( mesh$type %in% c("SolidRectangle","HollowRectangle") ) { u <- matrix( runif( n*d ), nrow=n ,ncol=d ) for (i in 1:n) { j <- which.splx[i] for (k in 1:d) { a[k] <- min( mesh$S[,k,j] ) b[k] <- max( mesh$S[,k,j] ) } x[i,] <- a + u[i, ]*(b-a) } return(x) } stop( "Cannot currently simulate from a mesh of type ", mesh$type ) } SolidRectangle <- function( a, b, breaks=5, silent=FALSE ) { breaks <- mvmeshRectBreaks( a, b, breaks, silent ) n <- length(a) ngrid <- as.integer(sapply(breaks,length)) nbins <- ngrid - 1L nV <- prod(ngrid) V <- matrix( 0.0, ncol=n, nrow=nV ) i <- rep(1L,n) j <- 1L while (i[1] > 0) { for (k in 1:n) { V[j,k] <- breaks[[k]][i[k]] } j <- j + 1L i <- NextMultiIndex(i,ngrid) } nS <- prod(nbins) vps <- as.integer(2^n) S <- array( 0.0, dim=c(vps,n,nS) ) SVI <- matrix( 0L, nrow=vps, ncol=nS ) i <- rep(1L,n) j <- 1L while (i[1] > 0) { for (k in 1:vps) { m <- ConvertBase( k-1L, 2L, n ) for (l in 1:n) { S[k,l,j] <- breaks[[l]][i[l]+m[l]] } SVI[k,j] <- MatchRow( S[k,,j], V ) } i <- NextMultiIndex(i,nbins) j <- j + 1L } mesh <- list(type="SolidRectangle",mvmesh.type=7L,n=n,m=n,vps=as.integer(2^n),S=S,V=V,SVI=SVI, a=a,b=b,breaks=breaks) class(mesh) <- "mvmesh" return(mesh) } mvmeshRectBreaks <- function(a,b,breaks,silent ) { stopifnot( is.numeric(a), is.numeric(b), is.vector(a), is.vector(b), length(a)==length(b), length(a) >= 1, all(a < b) ) n <- length(a) if ( is.numeric(breaks) & is.vector(breaks) ) { breaks <- as.integer(breaks) if( length(breaks)==1 ) { breaks <- rep(breaks,n) } stopifnot( all(breaks > 0), length(breaks)==n ) new.breaks <- vector(mode="list",length=n) for (j in 1:n) { new.breaks[[j]] <- seq( a[j], b[j], length=breaks[j]+1) } breaks <- new.breaks } if( !is.list(breaks) ) { stop("breaks must be an integer, a vector of integers, or a list") } for (j in 1:n) { stopifnot( is.numeric(breaks[[j]]), is.vector(breaks[[j]]), length(breaks[[j]]) > 1, all(diff(breaks[[j]])>0) ) } if( !silent ) { aa <- rep(NA,n) bb <- rep(NA,n) for (j in 1:n) { tmp <- range( breaks[[j]] ) aa[j] <- tmp[1] bb[j] <- tmp[2] } if ( any(a < aa) | any(b > bb) ){ warning("specified breaks do not cover the hyperectangle [a,b]" ) } } return( breaks ) } HollowRectangle <- function( a, b, breaks=5, silent=FALSE ) { n <- length(a) allBreaks <- mvmeshRectBreaks( a, b, breaks, silent ) bnd <- sapply(allBreaks,range) for (i in 1:n) { side <- SolidRectangle( a[-i], b[-i], allBreaks[-i] ) nVside <- nrow(side$V) nSVIside <- ncol(side$SVI) if (i==1) { V <- rbind( cbind(rep(bnd[1,1],nVside),side$V), cbind( rep(bnd[2,1],nVside),side$V) ) SVI <- cbind( side$SVI, side$SVI+nVside) nV0 <- nrow(V) } else { nV <- nrow(V) left <- side$V[,1:(i-1),drop=FALSE] if( i < n) { right <- side$V[,i:ncol(side$V),drop=FALSE] } else { right <- matrix(0.0,nrow=nVside,ncol=0) } newV <- rbind( cbind(left, rep(bnd[1,i],nVside), right), cbind(left, rep(bnd[2,i],nVside), right) ) V <- rbind(V,newV) SVI <- cbind(SVI,side$SVI+nV,side$SVI+nV+nVside) } } nVnew <- nV0 for (j in (nV0+1):nrow(V)) { k <- MatchRow( V[j,],V,1,nVnew ) if (length(k) == 1) { change <- which( SVI == j ) SVI[change] <- k } else { nVnew <- nVnew + 1 V[nVnew,] <- V[j, ] change <- which( SVI == j ) SVI[change] <- nVnew } } mesh <- mvmeshFromSVI( V[1:nVnew, ] , SVI, n-1 ) mesh$type <- "HollowRectangle" mesh$mvmesh.type=13L mesh$breaks <- allBreaks return(mesh) } HollowTube <- function( n, k.x=1, k.circumference=2, method="dyadic", p=2 ){ n <- as.integer(n) k.x <- as.integer(k.x) k.circumfernce <- as.integer(k.circumference) stopifnot( n >= 2, k.x >= 1, k.circumference >= 1 ) x.grid <- seq(0,1,length=k.x+1) vps <- 2*(n-1) if (n==2){ nS <- 2*k.x SVI <- matrix( 0L, nrow=vps, ncol=nS ) V <- cbind( rep(x.grid,2), c(rep(1,k.x+1),rep(-1,k.x+1) ) ) for (i in 1:k.x) { SVI[ ,i] <- c(i,i+1) SVI[ ,i+k.x] <- c(i+k.x+1,i+k.x+2) } } else { sphere <- UnitSphere(n=n-1,k=k.circumference,method=method,p=p) nS.sphere <- dim(sphere$S)[3] nV.sphere <- nrow(sphere$V) V <- matrix( 0.0, nrow=(k.x+1)*nV.sphere, ncol=n ) k <- 0 for (i in 1:(k.x+1)) { for (j in 1:nV.sphere) { k <- k + 1 V[k, ] <- c( x.grid[i], sphere$V[j,] ) } } nS <- k.x * nS.sphere SVI <- matrix( 0L, nrow=vps, ncol=nS ) k <- 0 for (i in 1:k.x) { for (j in 1:nS.sphere) { k <- k + 1 SVI[ ,k] <- c( (i-1)*nV.sphere + sphere$SVI[,j], rev(i*nV.sphere + sphere$SVI[,j]) ) } } } S <- array( 0.0, dim=c(vps,n,nS ) ) for (i in 1:nS) { for (j in 1:vps) { S[j, ,i] <- V[SVI[j,i],] } } mesh <- list(type="HollowTube",mvmesh.type=11L,n=n,vps=vps,S=S,V=V,SVI=SVI, k.x=k.x,k.circumference=k.circumference) class(mesh) <- "mvmesh" return(mesh)} SolidTube <- function( n, k.x=1, k.circumference=2, method="dyadic", p=2 ){ n <- as.integer(n) k.x <- as.integer(k.x) k.circumfernce <- as.integer(k.circumference) stopifnot( n >= 2, k.x >= 1, k.circumference >= 1 ) x.grid <- seq(0,1,length=k.x+1) vps <- 2*n if (n==2){ nS <- k.x SVI <- matrix( 0L, nrow=vps, ncol=nS ) V <- cbind( rep(x.grid,2), c(rep(1,k.x+1),rep(-1,k.x+1) ) ) for (i in 1:nS) { SVI[ ,i] <- c(i,i+1,i+k.x+2,i+k.x+1) } } else { ball <- UnitBall(n=n-1,k=k.circumference,method=method,p=p) nS.ball <- dim(ball$S)[3] nV.ball <- nrow(ball$V) V <- matrix( 0.0, nrow=(k.x+1)*nV.ball, ncol=n ) k <- 0 for (i in 1:(k.x+1)) { for (j in 1:nV.ball) { k <- k + 1 V[k, ] <- c( x.grid[i], ball$V[j,] ) } } nS <- k.x * nS.ball SVI <- matrix( 0L, nrow=vps, ncol=nS ) k <- 0 for (i in 1:k.x) { for (j in 1:nS.ball) { k <- k + 1 SVI[ ,k] <- c( (i-1)*nV.ball + ball$SVI[,j], rev(i*nV.ball + ball$SVI[,j]) ) } } } S <- array( 0.0, dim=c(vps,n,nS ) ) for (i in 1:nS) { for (j in 1:vps) { S[j, ,i] <- V[SVI[j,i],] } } mesh <- list(type="SolidTube",mvmesh.type=12L,n=n,vps=n,S=S,V=V,SVI=SVI, k.x=k.x,k.circumference=k.circumference) class(mesh) <- "mvmesh" return(mesh)} NextMultiIndex <- function( i, n ) { cur <- 1L k <- length(i) repeat { i[cur] <- i[cur]+1L if (i[cur] <= n[cur]) { break } if (cur == k) { i[1] <- 0 break } i[cur] <- 1L cur <- cur + 1L } return(i) } EdgeSubdivision <- function( n, k ){ n <- as.integer(n) k <- as.integer(k) stopifnot( length(n)==1, length(k)==1 ) nS <- k^n T <- array( 0L, dim=c(k,n+1,nS) ) CS <- matrix( 0L, nrow=k, ncol=n+1) for (l in 1L:nS) { x <- ConvertBase( l-1L, k, n ) cor <- 0L for (i in 1L:k){ CS[i,1] <- cor for (j in 1:n) { if ( x[n+1-j] == (i-1L) ) { cor <- cor + 1L } CS[i,j+1] <- cor; } } T[,,l] <- CS } return(T) } ConvertBase <- function( m, b, n ){ y <- rep(0L,n) for(i in 1:n){ d <- floor(m/b) y[i] <- m-d*b m <- d } return(y) } SimplexCoord <- function( S, color ){ n <-ncol(S) vps <- nrow(S) P <- matrix(0.0,nrow=vps,ncol=n) for (j in 1:vps) { P[j,] <- PointCoord(S,color[,j]) } return(P) } PointCoord <- function( S, color ){ n <- ncol(S) k <- length(color) P <- rep( 0.0, n ) for (i in 1:k) { P <- P + S[color[i]+1, ] } return(P/k) } SVIFromColor <- function( S, T ) { n <- ncol(S) k <- dim(T)[1] vps <- dim(T)[2] nS <- dim(T)[3] a <- matrix( 0L, nrow=k, ncol=nS*vps ) m <- 0 for (i in 1:nS) { for (j in 1:vps) { m <- m + 1 a[,m] <- T[,j,i] } } b <- unique(a,MARGIN=2) nV <- ncol(b) V <- matrix(0.0,nrow=nV,ncol=n) for (i in 1:nV) { V[i,] <- PointCoord(S,b[,i]) } SVI <- matrix( 0L, nrow=vps, ncol=nS ) for (i in 1:vps) { for (j in 1:nS) { for (m in 1:nV) { if( identical(b[,m],T[,i,j] )) { SVI[i,j] <- m } } } } return( list( V=V, SVI=SVI ) ) } NumVertices <- function( n, k, single=TRUE ) { v <- matrix(as.integer(0),k,n) v[1,] <- 1:n v[,1] <- as.integer(1) for (j in 2:n) { for (i in 2:k) { v[i,j] <- v[i-1,j] + v[i,j-1] } } if (single) return(v[k,n]) else return(v) } MatchRow <- function( v, table, first=1, last=nrow(table) ) { j <- integer(0) for (i in first:last) { if (identical(v,table[i,]) ) { j <- c(j,i) } } return( j ) } EdgeSubdivisionMulti <- function( V, SVI, k, normalize=FALSE, p=2 ) { k <- as.integer( k ) stopifnot( is.matrix(V), is.matrix(SVI), k > 1, is.logical(normalize), p > 0.0 ) n <- ncol(V); nV <- nrow(V); vps <- nrow(SVI); nS <- ncol(SVI) T <- EdgeSubdivision( n=vps-1, k=k ) new <- SVIFromColor( V[ SVI[,1], ], T ) M <- nrow(new$V); L <- ncol(new$SVI) Vnew <- matrix(0.0,ncol=n,nrow=nS*M) SVInew <- matrix( 0L, nrow=vps, ncol=nS*L) Vend <- 0L SVIend <- 0L for (i in 1:nS) { new <- SVIFromColor( V[SVI[,i], ], T ) Vnew[ (Vend+1):(Vend+M), ] <- new$V SVInew[ ,(SVIend+1):(SVIend+L)] <- new$SVI + Vend Vend <- Vend+M SVIend <- SVIend + L } count <- 1 for (i in 2:Vend) { l <- which(SVInew==i) j <- MatchRow( Vnew[i,], Vnew, 1, count ) if (length(j)==0) { count <- count + 1 Vnew[count,] <- Vnew[i,] SVInew[l] <- count } else { SVInew[l] <- j[1] } } if (normalize) { r <- LpNorm(Vnew[1:count,],p) for (i in 1:count) { Vnew[i,] <- Vnew[i,]/r[i] } } mesh <- list( V=Vnew[1:count,], SVI=SVInew) class(mesh) <- "mvmesh" return(mesh)} Icosahedron <- function( ) { p <- (sqrt(5)-1)/2 V <- matrix( c(0,p,1, 0,p,-1, 0,-p,1, 0,-p,-1, p,1,0, p,-1,0, -p,1,0, -p,-1,0, 1,0,p, -1,0,p, 1,0,-p, -1,0,-p), nrow=12, ncol=3, byrow=TRUE) c1 <- 1.0/sqrt( sum( V[1,]^2 ) ) V <- c1*V SVI <- matrix( as.integer(c( 1,3,9, 1,9,5, 1,5,7, 1,7,10, 1,10,3, 4,12,2, 4,2,11, 4,11,6, 4,6,8, 4,8,12, 9,3,6, 5,9,11, 7,5,2, 10,7,12, 3,10,8, 2,12,7, 11,2,5, 6,11,9, 8,6,3, 12,8,10 ) ), nrow= 3 , ncol= 20 ) S <- array( 0.0, dim=c(3,3,20)) for (k in 1:20) { S[ ,,k] <- V[ SVI[,k], ] } mesh <- list( type="Icosahedron", mvmesh.type=8L, n=3L,m=2,vps=3,k=NA, originalS=S, S=S, V=V, SVI=SVI ) class(mesh) <- "mvmesh" return( mesh ) } LpNorm <- function( x, p ){ if (is.vector(x)) { x <- matrix(x,nrow=1) } stopifnot( is.matrix(x), nrow(x) > 0, ncol(x) > 0, p > 0 ) if (is.finite(p)) { r <- apply( abs(x)^p, MARGIN=1, FUN=sum )^(1/p) } else { r <- apply( abs(x), MARGIN=1, FUN=max ) } return(r) } AffineTransform <- function( mesh, A, shift ) { stopifnot( is.list(mesh), class(mesh)=="mvmesh", is.matrix(A), is.numeric(A), is.numeric(shift), is.vector(shift), nrow(A)==ncol(A), nrow(A)==length(shift) ) new <- mesh new$type <- paste( mesh$type, "+affine", sep="" ) nV <- nrow( new$V ) nS <- ncol( new$SVI ) vps <- new$vps affine.func <- function( v, A, b ) { A %*% v + b } new$V <- t( apply( mesh$V, MARGIN=1, affine.func, A=A, b=shift ) ) for (k in 1:nS) { for (j in 1:vps) { new$S[j,,k] <- new$V[ new$SVI[j,k], ] } } return( new ) } Rotate2D <- function( theta ) { stopifnot( is.numeric(theta), length(theta)==1 ) return( matrix( c( cos(theta),sin(theta),-sin(theta),cos(theta) ), nrow=2,ncol=2) )} Rotate3D <- function( theta ) { stopifnot( is.numeric(theta), length(theta)==3 ) Rx <- matrix( c(1,0,0, 0,cos(theta[1]),sin(theta[1]), 0,-sin(theta[1]),cos(theta[1]) ), nrow=3, ncol=3) Ry <- matrix( c(cos(theta[2]),0,-sin(theta[2]), 0,1,0, sin(theta[2]),0,cos(theta[2]) ), nrow=3, ncol=3) Rz <- matrix( c(cos(theta[3]),sin(theta[3]),0, -sin(theta[3]),cos(theta[3]),0, 0,0,1 ), nrow=3, ncol=3) return( Rx %*% Ry %*% Rz )} V2Hrep <- function( S ) { if (is.matrix(S) ) { S <- array( S, dim=c(nrow(S),ncol(S),1) ) } nS <- dim(S)[3] dim.Hrep <- c(0L,0L) for (k in 1:nS) { Vk <- makeV( S[,,k] ) tmp <- rcdd::scdd( Vk, representation="V" )$output if (k==1) { dim.Hrep <- dim(tmp) H <- array( 0.0, dim=c(dim.Hrep,nS) ) } if ( any(dim(tmp) != dim.Hrep)) stop( "simplices have different size H-representations" ) H[,,k] <- tmp } return(H) } H2Vrep <- function( H ) { if (is.matrix(H) ) { H <- array( H, dim=c(nrow(H),ncol(H),1) ) } dimH <- dim(H) stopifnot( is.array(H), length(dimH)==3 ) nS <- dimH[3] dim.Vrep <- c(0L,0L) for (k in 1:nS) { tmp <- rcdd::scdd( H[,,k], representation="H" )$output[ ,-c(1,2),drop=FALSE] if (k==1) { dim.Vrep <- dim(tmp) S <- array( 0.0, dim=c(dim(tmp),nS)) } if ( any(dim(tmp) != dim.Vrep)) stop( "simplices have different size V-representations" ) S[,,k] <- tmp } return(S) } SatisfyHrep <- function( x, Hsingle ) { stopifnot( is.matrix(Hsingle) ) l <- Hsingle[ ,1] b <- Hsingle[ ,2] A <- - Hsingle[ , -(1:2)] if (is.vector(x)) { x <- matrix( x, nrow=1 ) } stopifnot( is.matrix(x), ncol(x)+2==ncol(Hsingle) ) n <- ncol(x) nx <- nrow(x) satisfy <- integer(0) for (k in 1:nx) { axmb <- A %*% x[k,] - b if (all(axmb <= 0.0) & all( l*axmb == 0 ) ) { satisfy <- c(satisfy,k) } } return(satisfy)} Polar2Rectangular <- function( r, theta ) { m <- length(r) if (!is.matrix(theta)) { theta <- as.matrix(theta,nrow=1) } stopifnot( m == nrow(theta)) n <- ncol(theta) + 1L x <- matrix(0.0,nrow=m,ncol=n) for (j in 1:m) { col.cos <- cos(theta[j,]) col.sin <- sin(theta[j,]) s <- c( col.cos[1], rep(col.sin[1],n-1) ) if (n > 2) { for (k in 2:(n-1)) { s[k] <- s[k]*col.cos[k] s[(k+1):n] <- s[(k+1):n]*col.sin[k] } } x[j,] <- r[j]*s } return(x) } Rectangular2Polar <- function( x ) { if(!is.matrix(x)) { x <- as.matrix(x,nrow=1) } n <- ncol(x) m <- nrow(x) r <- rep(0.0,m) theta <- matrix(0.0,ncol=n-1,nrow=m) for (j in 1:m) { rsq <- x[j,]^2 cum.rsq <- cumsum(rev(rsq)) r[j] <- sqrt( cum.rsq[n] ) if (r[j] > 0.0) { if (n>2) { for (k in 1:(n-2)) { theta[j,k] <- atan2( sqrt(cum.rsq[n-k]), x[j,k] ) } } theta[j,n-1] <- 2*atan2( x[j,n], x[j,n-1]+sqrt(cum.rsq[2] ) ) } } return(list(r=r,theta=theta))} IntersectMultipleSimplicesV <- function( S1, S2 ) { H1 <- V2Hrep( S1 ) H2 <- V2Hrep( S2 ) return( IntersectMultipleSimplicesH( H1, H2 ) ) } IntersectMultipleSimplicesH <- function( H1, H2, skip.redundant=FALSE ) { stopifnot( ncol(H1)==ncol(H2) ) n <- ncol(H1)-2 count <- 0 S <- NULL index1 <- integer(0) index2 <- index1 nS1 <- dim(H1)[3] nS2 <- dim(H2)[3] for (i2 in 1:nS2) { for (i1 in 1:nS1) { a <- Intersect2SimplicesH( H1[,,i1], H2[,,i2], tessellate=TRUE ) if ( !is.null(a$S) && (dim(a$S)[1]>0) ) { m <- dim(a$S)[3] index1 <- c(index1,rep(i1,m)) index2 <- c(index2,rep(i2,m)) if (is.null(S) ) { S <- a$S } else { S <- abind( S, a$S, force.array=TRUE ) } } } } dimnames(S) <- NULL return( list( S=S, index1=index1, index2=index2 ) )} Intersect2SimplicesH <- function( H1, H2, tessellate=FALSE, skip.redundant=FALSE ) { if( is.vector( H1 ) ) { H1 <- matrix( H1, nrow=1 ) } if( is.vector( H2 ) ) { H2 <- matrix( H2, nrow=1 ) } n <- ncol(H1)-2 if (skip.redundant ) { H <- rbind( H1, H2 ) } else { H <- rcdd::redundant( rbind( H1, H2 ), representation="H")$output } V <- NULL S <- NULL if( nrow(H) > n) { V <- H2Vrep( H )[,,1] if (tessellate) { if (nrow(V) > n) { new.tess <- geometry::delaunayn( V, options="Qz" ) S <- array( 0.0, dim=c(n+1,n,nrow(new.tess)) ) for (k in 1:nrow(new.tess)) { b <- new.tess[k,] cur.tess <- V[b,] S[,,k] <- cur.tess } } } } return( list(H=H, V=V, S=S) ) } Lift2UnitSimplex <- function( S ){ n <- nrow(S) if (is.matrix(S)) { S <- array(S,dim=c(nrow(S),ncol(S),1) )} stopifnot( is.array(S), length(dim(S))==3 ) nS <- dim(S)[3] S2 <- array( 0.0, dim=c(n,n,nS) ) for (k in 1:nS) { tmp <- 1-rowSums( S[,,k,drop=FALSE] ) S2[,,k] <- cbind(S[,,k],tmp) } return(S2) } mvmeshFromSVI <- function( V, SVI, m ) { vps <- nrow(SVI) n <- ncol(V) nS <- ncol(SVI) S <- array( 0.0, dim=c(vps,n,nS) ) for (i in 1:nS) { for (j in 1:vps) { S[j,,i] <- V[SVI[j,i],] } } a <- list(type="mvmeshFromSVI",mvmesh.type=-1,n=n,m=m,vps=vps,S=S,V=V,SVI=SVI) class(a) <- "mvmesh" return(a) } mvmeshFromSimplices <- function( S ) { if (is.matrix(S)) { S <- array(S,dim=c(dim(S),1) ) } stopifnot( is.array(S), length(dim(S))==3 ) dimS <- dim(S) vps <- dimS[1] n <- dimS[2] nS <- dimS[3] V <- uniqueRowsFromDoubleArray( S ) SVI <- matrix( 0L, nrow=vps, ncol=nS) for (i in 1:nrow(V)) { for (j in 1:nS) { k <- MatchRow( V[i,], S[,,j]) if (length(k) > 0) { SVI[k,j] <- i } } } k <- which(SVI==0) if( length(k) > 0 ) warning(paste(length(k),"unmatched rows in function mvmeshFromSimplices")) a <- list(type="mvmeshFromSimplices",mvmesh.type=-1,n=n,m=vps-1,vps=vps,S=S,V=V,SVI=SVI) class(a) <- "mvmesh" return(a)} uniqueRowsFromDoubleArray <- function( A ) { if( is.matrix(A) ) { A <- array( A, dim=c(dim(A),1) ) } stopifnot( is.array(A), length(dim(A))==3, all(dim(A)>0) ) nA <- dim(A)[3] B <- matrix( 0, ncol=ncol(A), nrow=nrow(A)*nA ) B[1,] <- A[1,,1] count <- 1 for (i in 1:nA) { for (j in 1:nrow(A)) { match <- MatchRow( A[j,,i], B, first=1, last=count ) if (length(match)==0) { count <- count + 1 B[count,] <- A[j,,i] } } } return(B[1:count, ]) } mvmeshFromVertices <- function( V ) { SVI <- t( delaunayn( V ) ) n <- ncol(V) nV <- nrow(V) vps <- nrow(SVI) S <- array( 0.0, dim=c(vps,n,ncol(SVI))) for (i in 1:ncol(SVI)) { for (j in 1:n) { S[j,,i] <- V[SVI[j,i],] } } a <- list(type="mvmeshFromVertices",mvmesh.type=-1,n=n,m=n,vps=vps,S=S,V=V,SVI=SVI) class(a) <- "mvmesh" return(a)} mvmeshCombine <- function( mesh1, mesh2 ) { stopifnot( mesh1$n == mesh2$n, mesh1$m==mesh2$m, mesh1$vps==mesh2$vps ) new <- mesh1 new$V <- rbind(mesh1$V,mesh2$V) new$SVI <- cbind(mesh1$SVI,mesh2$SVI) new$S <- abind( mesh1$S, mesh2$S ) return(new) }
library(datasets) X = cbind(attenu$mag, attenu$dist) colnames(X) = c("mag", "dist") X_s = cbind(attenu$mag, 1 / attenu$dist) colnames(X_s) = c("mag", "dist_inv") y = attenu$accel fit = lmvar(y, X, X_s) fitted(fit, sigma = FALSE) fitted(fit, mu = FALSE) fitted(fit, sigma = FALSE, interval = "confidence") fitted(fit, mu = FALSE, interval = "confidence", level = 0.8) fitted(fit) fitted(fit, interval = "confidence") fitted(fit, interval = "prediction", level = 0.9) y = log(attenu$accel) fit_log = lmvar(y, X, X_s) fitted(fit_log) fitted(fit_log, log = TRUE) fitted(fit_log, log = TRUE, interval = "confidence", level = 0.9)
simplify.expression <- function(P.num, P.den) { if (is.null(P.den)) { if (P.num$fraction) { P.new <- simplify.expression(P.num$num, P.num$den) if (P.new$product && length(P.new$children) == 1) { ss <- P.new$sumset P.new <- P.new$children[[1]] P.new$sumset <- union(P.new$sumset, ss) } return(P.new) } P <- P.num if (P$product) { parse.children <- sapply(P$children, FUN = function(x) (x$product || length(x$sumset) > 0 || x$fraction || x$sum)) if (sum(parse.children) > 0) return(P) while (length(P$sumset) > 0) { if (P$children[[1]]$var %in% P$sumset) { P$sumset <- setdiff(P$sumset, P$children[[1]]$var) P$children <- P$children[-1] } else break } if (length(P$children) == 1) { ch <- P$children[[1]] return(probability(var = ch$var, cond = ch$cond, sumset = P$sumset, domain = ch$domain, do = ch$do)) } if (length(P$children) == 0) { return(probability()) } else return(P) } else { return(probability(var = setdiff(P$var, P$sumset), cond = P$cond, sumset = c(), domain = P$domain, do = P$do)) } } else { P.num <- simplify.expression(P.num, NULL) P.den <- simplify.expression(P.den, NULL) if (length(P.den$sumset) > 0) { P.new <- probability(fraction = TRUE) P.new$num <- P.num P.new$den <- P.den return(P.new) } else { if (P.num$product) { parse.children.num <- sapply(P.num$children, FUN = function(x) (x$product || length(x$sumset) > 0 || x$fraction || x$sum)) if (sum(parse.children.num) > 0) { P.new <- probability(fraction = TRUE) P.new$num <- P.num P.new$den <- P.den return(P.new) } if (P.den$product) { parse.children.den <- sapply(P.den$children, FUN = function(x) (x$product || length(x$sumset) > 0 || x$fraction || x$sum)) if (sum(parse.children.den) > 0) { P.new <- probability(fraction = TRUE) P.new$num <- P.num P.new$den <- P.den return(P.new) } else { last.num <- length(P.num$children) last.den <- length(P.den$children) while (length(P.den$children) > 0) { P.num$children <- P.num$children[-last.num] P.den$children <- P.den$children[-last.den] last.num <- last.num - 1 last.den <- last.den - 1 } if (length(P.den$children) == 1) P.den <- P.den$children[[1]] if (length(P.den$children) == 0) { return(P.num) } else { P.new <- probability(fraction = TRUE) P.new$num <- P.num P.new$den <- P.den return(P.new) } } } else { P.num$children <- P.num$children[-length(P.num$children)] if (length(P.num$children) == 1) { ch <- P.num$children[[1]] ch$sumset <- P.num$sumset return(ch) } return(P.num) } } } } }
expected <- eval(parse(text="5L")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(name = structure(c(\"McNeil\", \"Ripley\", \"Ripley\", \"Tierney\", \"Tukey\", \"Venables\"), class = \"AsIs\"), title = structure(c(3L, 6L, 7L, 4L, 2L, 5L), .Label = c(\"An Introduction to R\", \"Exploratory Data Analysis\", \"Interactive Data Analysis\", \"LISP-STAT\", \"Modern Applied Statistics ...\", \"Spatial Statistics\", \"Stochastic Simulation\"), class = \"factor\"), other.author = structure(c(NA, NA, NA, NA, NA, 1L), .Label = c(\"Ripley\", \"Venables & Smith\"), class = \"factor\"), nationality = structure(c(1L, 2L, 2L, 3L, 3L, 1L), .Label = c(\"Australia\", \"UK\", \"US\"), class = \"factor\"), deceased = structure(c(1L, 1L, 1L, 1L, 2L, 1L), .Label = c(\"no\", \"yes\"), class = \"factor\")), .Names = c(\"name\", \"title\", \"other.author\", \"nationality\", \"deceased\"), row.names = c(6L, 4L, 5L, 3L, 1L, 2L), class = \"data.frame\"))")); do.call(`length`, argv); }, o=expected);
mqmscan <- function(cross,cofactors=NULL,pheno.col=1,model=c("additive","dominance"),forceML=FALSE, cofactor.significance=0.02,em.iter=1000,window.size=25.0,step.size=5.0,logtransform = FALSE, estimate.map = FALSE,plot=FALSE,verbose=FALSE, outputmarkers=TRUE, multicore=TRUE, batchsize=10, n.clusters=1, test.normality=FALSE,off.end=0) { start <- proc.time() model <- match.arg(model) cross <- omit_x_chr(cross) if(forceML){ forceML <- 1 }else{ forceML <- 0 } dominance <- 0 if(model=="dominance"){ dominance <- 1 } if(estimate.map){ estimate.map <- 1 }else{ estimate.map <- 0 } n.run <- 0 if(is.null(cross)){ stop("No cross file. Please supply a valid cross object.") } crosstype <- crosstype(cross) if(crosstype == "f2" || crosstype == "bc" || crosstype == "riself"){ if(crosstype == "f2"){ ctype = 1 } if(crosstype == "bc" || crosstype=="dh" || crosstype=="haploid"){ ctype = 2 } if(crosstype == "riself") { ctype = 3 g <- as.numeric(pull.geno(cross)) g <- sort(unique(g[!is.na(g)])) if(max(g)==2) { for(i in seq(along=cross$geno)) cross$geno[[i]]$data[!is.na(cross$geno[[i]]$data) & cross$geno[[i]]$data==2] <- 3 } } n.ind <- nind(cross) n.chr <- nchr(cross) if(verbose) { cat("INFO: Received a valid cross file type:",crosstype,".\n") cat("INFO: Number of individuals: ",n.ind,"\n") cat("INFO: Number of chromosomes: ",n.chr,"\n") } savecross <- cross geno <- NULL chr <- NULL dist <- NULL newcmbase <- NULL out.qtl <- NULL for(i in 1:n.chr) { geno <- cbind(geno,cross$geno[[i]]$data) chr <- c(chr,rep(i,dim(cross$geno[[i]]$data)[2])) newcmbase = c(newcmbase,min(cross$geno[[i]]$map)) cross$geno[[i]]$map <- cross$geno[[i]]$map-(min(cross$geno[[i]]$map)) dist <- c(dist,cross$geno[[i]]$map) } if(cofactor.significance <=0 || cofactor.significance >= 1){ stop("cofactor.significance must be between 0 and 1.\n") } if(any(is.na(geno))){ stop("Missing genotype information, please estimate unknown data, before running mqmscan.\n") } if(missing(cofactors)) cofactors <- rep(0,sum(nmar(cross))) numcofold <- sum(cofactors) cofactors <- checkdistances(cross,cofactors,1) numcofnew <- sum(cofactors) if(numcofold!=numcofnew){ cat("INFO: Removed ",numcofold-numcofnew," cofactors that were close to eachother\n") } pheno.col = stringPhenoToInt(cross,pheno.col) if (length(pheno.col) > 1){ cross$pheno <- cross$pheno[,pheno.col] result <- mqmscanall( cross,cofactors=cofactors,forceML=forceML,model=model, cofactor.significance=cofactor.significance,step.size=step.size,window.size=window.size, logtransform=logtransform, estimate.map = estimate.map,plot=plot, verbose=verbose,n.clusters=n.clusters,batchsize=batchsize) return(result) } if(pheno.col != 1){ if(verbose) { cat("INFO: Selected phenotype ",pheno.col,".\n") cat("INFO: Number of phenotypes in object ",nphe(cross),".\n") } if(nphe(cross) < pheno.col || pheno.col < 1){ stop("No such phenotype in cross object.\n") } } if(test.normality && !mqmtestnormal(cross, pheno.col, 0.01, FALSE)){ warning("Trait might not be normal (Shapiro normality test)\n") } pheno <- cross$pheno[,pheno.col] phenovar = var(pheno,na.rm = TRUE) if(phenovar > 1000){ if(!logtransform){ if(verbose) cat("INFO: Before LOG transformation Mean:",mean(pheno,na.rm = TRUE),"variation:",var(pheno,na.rm = TRUE),".\n") } } if(logtransform){ cross <- transformPheno(cross,pheno.col,transf=log) pheno <- cross$pheno[,pheno.col] } n.mark <- ncol(geno) if(verbose) cat("INFO: Number of markers:",n.mark,"\n") dropped <- NULL droppedIND <- NULL for(i in 1:length(pheno)) { if(is.na(pheno[i]) || is.infinite(pheno[i])){ if(verbose) cat("INFO: Dropped individual ",i," with missing phenotype.\n") dropped <- c(dropped,i) if(!is.null(cross$mqm)){ droppedIND <- c(droppedIND,cross$mqm$augIND[i]) } n.ind = n.ind-1 } } if(!is.null(dropped)){ geno <- geno[-dropped,] pheno <- pheno[-dropped] } if(!is.null(cross$mqm)){ augmentedNind <- cross$mqm$Nind augmentedInd <- cross$mqm$augIND if(verbose){ cat("n.ind:",n.ind,"\n") cat("augmentedNind:",augmentedNind,"\n") cat("length(augmentedInd):",length(augmentedInd),"\n") } if(!is.null(dropped)){ augmentedInd <- cross$mqm$augIND[-dropped] augmentedInd[1] <- 0 for(x in 1:(length(augmentedInd)-1)){ if(augmentedInd[x+1] - 1 > augmentedInd[x] ){ for(y in (x+1):length(augmentedInd)){ augmentedInd[y] <- augmentedInd[y] - ((augmentedInd[x+1] - augmentedInd[x])-1) } } } } augmentedNind <- length(unique(augmentedInd)) if(verbose){ cat("New augmentedNind:",augmentedNind,"\n") cat("New length(augmentedInd):",length(augmentedInd),"\n") } }else{ augmentedNind <- n.ind augmentedInd <- 0:n.ind } backward <- 0; if(missing(cofactors)){ if(verbose) cat("INFO: No cofactors, setting cofactors to 0\n") cofactors = rep(0,n.mark) }else{ if(length(cofactors) != n.mark){ if(verbose) cat("ERROR: }else{ if(verbose) cat("INFO:",sum(cofactors!=0),"Cofactors received to be analyzed\n") if((sum(cofactors) > n.ind-10 && dominance==0)){ stop("Cofactors don't look okay for use without dominance\n") } if((sum(cofactors)*2 > n.ind-10 && dominance==1)){ stop("Cofactors don't look okay for use with dominance\n") } if(sum(cofactors) > 0){ if(verbose) cat("INFO: Doing backward elimination of selected cofactors.\n") backward <- 1; n.run <- 0; }else{ backward <- 0; cofactors = rep(0,n.mark) } } } step.min = -off.end; step.max = max(dist)+step.size+off.end; step.max <- as.integer(ceiling((step.max+step.size)/step.size)*step.size) if((step.min+step.size) > step.max){ stop("step.max needs to be >= step.min + step.size") } if(step.size < 1){ stop("step.size needs to be >= 1") } qtlAchromo <- length(seq(step.min,step.max,step.size)) if(verbose) cat("INFO: Number of locations per chromosome: ",qtlAchromo, "\n") end.1 <- proc.time() result <- .C("R_mqmscan", as.integer(n.ind), as.integer(n.mark), as.integer(1), as.integer(geno), as.integer(chr), DIST=as.double(dist), as.double(pheno), COF=as.integer(cofactors), as.integer(backward), as.integer(forceML), as.double(cofactor.significance), as.integer(em.iter), as.double(window.size), as.double(step.size), as.double(step.min), as.double(step.max), as.integer(n.run), as.integer(augmentedNind), as.integer(augmentedInd), QTL=as.double(rep(0,2*n.chr*qtlAchromo)), as.integer(estimate.map), as.integer(ctype), as.integer(dominance), as.integer(verbose), PACKAGE="qtl") end.2 <- proc.time() qtl <- NULL info <- NULL names <- NULL for(i in 1:(n.chr*qtlAchromo)) { qtl <- rbind(qtl,c(ceiling(i/qtlAchromo),rep(seq(step.min,step.max,step.size),n.chr)[i],result$QTL[i])) info <- rbind(info,result$QTL[(n.chr*qtlAchromo)+i]) names <- c(names,paste("c",ceiling(i/qtlAchromo),".loc",rep(seq(step.min,step.max,step.size),n.chr)[i],sep="")) } if(estimate.map){ new.map <- pull.map(cross) chrmarkers <- nmar(cross) sum <- 1 for(i in 1:length(chrmarkers)) { for(j in 1:chrmarkers[[i]]) { new.map[[i]][j] <- result$DIST[sum] sum <- sum+1 } } } if(plot){ if(estimate.map && backward){ op <- par(mfrow = c(3,1)) }else{ if(estimate.map || backward){ op <- par(mfrow = c(2,1)) }else{ op <- par(mfrow = c(1,1)) } } if(estimate.map){ if(verbose) cat("INFO: Viewing the user supplied map versus genetic map used during analysis.\n") plotMap(pull.map(cross), new.map,main="Supplied map versus re-estimated map") } } if(backward){ if(!estimate.map){ new.map <- pull.map(cross) } chrmarkers <- nmar(cross) mapnames <- NULL for(x in 1:nchr(cross)){ mapnames <- c(mapnames,names(pull.map(cross)[[x]])) } sum <- 1 model.present <- 0 qc <- NULL qp <- NULL qn <- NULL for(i in 1:length(chrmarkers)) { for(j in 1:chrmarkers[[i]]) { if(result$COF[sum] != 48){ if(verbose) cat("MODEL: Marker",sum,"named:", strsplit(names(unlist(new.map)),".",fixed=TRUE)[[sum]][2],"from model found, CHR=",i,",POSITION=",as.double(unlist(new.map)[sum])," cM\n") qc <- c(qc, as.character(names(cross$geno)[i])) qp <- c(qp, as.double(unlist(new.map)[sum])) qn <- c(qn, mapnames[sum]) model.present <- 1 } sum <- sum+1 } } if(!is.null(qc) && model.present){ why <- sim.geno(savecross,n.draws=1) QTLmodel <- makeqtl(why, qc, qp, qn, what="draws") attr(QTLmodel,"mqm") <- 1 if(plot) plot(QTLmodel) } } rownames(qtl) <- names qtl <- cbind(qtl,1/(min(info))*(info-min(info))) qtl <- cbind(qtl,1/(min(info))*(info-min(info))*qtl[,3]) colnames(qtl) = c("chr","pos (cM)",paste("LOD",colnames(cross$pheno)[pheno.col]),"info","LOD*info") qtl <- as.data.frame(qtl, stringsAsFactors=TRUE) if(backward && !is.null(qc) && model.present){ attr(qtl,"mqmmodel") <- QTLmodel cimcovar <- as.data.frame(cbind(as.numeric(attr(qtl,"mqmmodel")[[4]]),as.data.frame(attr(qtl,"mqmmodel")[[5]])), stringsAsFactors=TRUE) rownames(cimcovar) <- attr(qtl,"mqmmodel")[[2]] colnames(cimcovar) <- c("chr","pos") attr(qtl, "marker.covar.pos") <- cimcovar } class(qtl) <- c("scanone",class(qtl)) if(outputmarkers){ for( x in 1:nchr(cross)){ to.remove <- NULL chr.length <- max(cross$geno[[x]]$map) markers.on.chr <- which(qtl[,1]==x) to.remove <- markers.on.chr[which(qtl[markers.on.chr,2] > chr.length+off.end+(2*step.size))] to.remove <- c(to.remove,markers.on.chr[which(qtl[markers.on.chr,2] < -off.end)]) if(length(to.remove) > 0) qtl <- qtl[-to.remove,] } qtl <- addmarkerstointervalmap(cross,qtl) qtl <- as.data.frame(qtl, stringsAsFactors=TRUE) if(backward && !is.null(qc) && model.present){ attr(qtl,"mqmmodel") <- QTLmodel cimcovar <- as.data.frame(cbind(as.numeric(attr(qtl,"mqmmodel")[[4]]),as.data.frame(attr(qtl,"mqmmodel")[[5]])), stringsAsFactors=TRUE) rownames(cimcovar) <- attr(qtl,"mqmmodel")[[2]] colnames(cimcovar) <- c("chr","pos") attr(qtl, "marker.covar.pos") <- cimcovar } class(qtl) <- c("scanone",class(qtl)) } qtlnew <- qtl rownames(qtlnew) <- paste0("qtlnew_X", 1:nrow(qtl)) oldnames <- rownames(qtl) for(x in 1:n.chr){ markers.on.chr <- which(qtl[,1]==x) if(newcmbase[x] !=0 && nrow(qtl[markers.on.chr,]) > 0){ qtl[markers.on.chr,2] <- qtl[markers.on.chr,2]+newcmbase[x] for(n in 1:nrow(qtl[markers.on.chr,])){ name <- rownames(qtl[markers.on.chr,])[n] id <- which(name==oldnames) if(!is.na(name) && grepl(".loc",name,fixed=TRUE)){ rownames(qtlnew)[id] <- paste(strsplit(name,".loc",fixed=TRUE)[[1]][1],".loc",qtlnew[id,2],sep="") }else{ rownames(qtlnew)[id] <- name } } }else{ rownames(qtlnew)[markers.on.chr] <- rownames(qtl)[markers.on.chr] } } qtl <- qtlnew for( x in 1:nchr(cross)){ if(chrtype(cross$geno[[x]])!="X"){ to.remove <- NULL chr.length <- max(cross$geno[[x]]$map) markers.on.chr <- which(qtl[,1]==x) to.remove <- markers.on.chr[which(qtl[markers.on.chr,2] > chr.length+off.end)] to.remove <- c(to.remove,markers.on.chr[which(qtl[markers.on.chr,2] < -off.end)]) qtl <- qtl[-to.remove,] } } qtl[,1] <- factor(names(cross$geno)[qtl[,1]], levels=names(cross$geno)) if(plot){ info.c <- qtl e <- 0 for(i in 1:ncol(qtl)){ if(is.na(info.c[i,5])){ e<- 1 } if(is.infinite(info.c[i,5])){ e<- 1 } if(is.null(info.c[i,5])){ e<- 1 } } if(!e){ mqmplot.singletrait(qtl,main=paste(colnames(cross$pheno)[pheno.col],"at significance=",cofactor.significance)) }else{ plot(qtl,main=paste(colnames(cross$pheno)[pheno.col],"at significance=",cofactor.significance),lwd=1) grid(max(qtl$chr),5) labels <- paste("QTL",colnames(cross$pheno)[pheno.col]) legend("topright", labels,col=c("black"),lty=c(1)) } op <- par(mfrow = c(1,1)) } end.3 <- proc.time() if(verbose) cat("INFO: Calculation time (R->C,C,C-R): (",round((end.1-start)[3], digits=3), ",",round((end.2-end.1)[3], digits=3),",",round((end.3-end.2)[3], digits=3),") (in seconds)\n") qtl }else{ stop("Currently only F2, BC, and selfed RIL crosses can be analyzed by MQM.") } }
"VMACpp" <- function(da,q=1,include.mean=T,fixed=NULL,beta=NULL,sebeta=NULL,prelim=F,details=F,thres=2.0){ if(!is.matrix(da))da=as.matrix(da) nT=dim(da)[1] k=dim(da)[2] if(q < 1)q=1 kq=k*q THini <- function(y,x,q,include.mean){ if(!is.matrix(y))y=as.matrix(y) if(!is.matrix(x))x=as.matrix(x) nT=dim(y)[1] k=dim(y)[2] ist=1+q ne=nT-q if(include.mean){ xmtx=matrix(1,ne,1) } else { xmtx=NULL } ymtx=y[ist:nT,] for (j in 1:q){ xmtx=cbind(xmtx,x[(ist-j):(nT-j),]) } xtx=crossprod(xmtx,xmtx) xty=crossprod(xmtx,ymtx) xtxinv=solve(xtx) beta=xtxinv%*%xty resi= ymtx - xmtx%*%beta sse=crossprod(resi,resi)/ne dd=diag(xtxinv) sebeta=NULL for (j in 1:k){ se=sqrt(dd*sse[j,j]) sebeta=cbind(sebeta,se) } THini <- list(estimates=beta,se=sebeta) } if(length(fixed) < 1){ m1=VARorder(da,q+12,output=FALSE) porder=m1$aicor if(porder < 1)porder=1 m2=VAR(da,porder,output=FALSE) y=da[(porder+1):nT,] x=m2$residuals m3=THini(y,x,q,include.mean) beta=m3$estimates sebeta=m3$se nr=dim(beta)[1] if(prelim){ fixed = matrix(0,nr,k) for (j in 1:k){ tt=beta[,j]/sebeta[,j] idx=c(1:nr)[abs(tt) >= thres] fixed[idx,j]=1 } } if(length(fixed) < 1){fixed=matrix(1,nr,k)} } else{ nr=dim(beta)[1] } par=NULL separ=NULL fix1=fixed VMAcnt=0 ist=0 if(include.mean){ jdx=c(1:k)[fix1[1,]==1] VMAcnt=length(jdx) if(VMAcnt > 0){ par=beta[1,jdx] separ=sebeta[1,jdx] } TH=-beta[2:(kq+1),] seTH=sebeta[2:(kq+1),] ist=1 } else { TH=-beta seTH=sebeta } for (j in 1:k){ idx=c(1:(nr-ist))[fix1[(ist+1):nr,j]==1] if(length(idx) > 0){ par=c(par,TH[idx,j]) separ=c(separ,seTH[idx,j]) } } ParMA <- par LLKVMACpp <- function(par,zt=zt,q=q,fixed=fix1,include.mean=include.mean){ k=ncol(zt) nT=nrow(zt) kq=k*q fix <- fixed ListObs = .Call("GetVMAObs", zt, fix1, par, q, include.mean) zt = do.call(rbind, ListObs) ListTH = .Call("GetVMATH", zt, fix1, par, q, include.mean) TH = do.call(rbind, ListTH) mm=eigen(TH) V1=mm$values P1=mm$vectors v1=Mod(V1) ich=0 for (i in 1:kq){ if(v1[i] > 1)V1[i]=1/V1[i] ich=1 } if(ich > 0){ P1i=solve(P1) GG=diag(V1) TH=Re(P1%*%GG%*%P1i) Theta=t(TH[1:k,]) icnt <- VMAcnt ist=0 if(icnt > 0)ist=1 for (j in 1:k){ idx=c(1:kq)[fix[(ist+1):(ist+kq),j]==1] jcnt=length(idx) if(jcnt > 0){ par[(icnt+1):(icnt+jcnt)]=TH[j,idx] icnt=icnt+jcnt } } ParMA <- par } at=mFilter(zt,t(Theta)) sig=t(at)%*%at/nT ll=dmvnorm(at,rep(0,k),sig) LLKVMACpp =-sum(log(ll)) LLKVMACpp } cat("Number of parameters: ",length(par),"\n") cat("initial estimates: ",round(par,4),"\n") lowerBounds=par; upperBounds=par npar=length(par) mult=2.0 if((npar > 10)||(q > 2))mult=1.2 for (j in 1:npar){ lowerBounds[j] = par[j]-mult*separ[j] upperBounds[j] = par[j]+mult*separ[j] } cat("Par. Lower-bounds: ",round(lowerBounds,4),"\n") cat("Par. Upper-bounds: ",round(upperBounds,4),"\n") if(details){ fit = nlminb(start = ParMA, objective = LLKVMACpp,zt=da,fixed=fixed,include.mean=include.mean,q=q, lower = lowerBounds, upper = upperBounds, control = list(trace=3)) } else { fit = nlminb(start = ParMA, objective = LLKVMACpp, zt=da, fixed=fixed, include.mean=include.mean, q=q, lower = lowerBounds, upper = upperBounds) } epsilon = 0.0001 * fit$par npar=length(par) Hessian = matrix(0, ncol = npar, nrow = npar) for (i in 1:npar) { for (j in 1:npar) { x1 = x2 = x3 = x4 = fit$par x1[i] = x1[i] + epsilon[i]; x1[j] = x1[j] + epsilon[j] x2[i] = x2[i] + epsilon[i]; x2[j] = x2[j] - epsilon[j] x3[i] = x3[i] - epsilon[i]; x3[j] = x3[j] + epsilon[j] x4[i] = x4[i] - epsilon[i]; x4[j] = x4[j] - epsilon[j] Hessian[i, j] = (LLKVMACpp(x1,zt=da,q=q,fixed=fixed,include.mean=include.mean) -LLKVMACpp(x2,zt=da,q=q,fixed=fixed,include.mean=include.mean) -LLKVMACpp(x3,zt=da,q=q,fixed=fixed,include.mean=include.mean) +LLKVMACpp(x4,zt=da,q=q,fixed=fixed,include.mean=include.mean))/ (4*epsilon[i]*epsilon[j]) } } est=fit$par cat("Final Estimates: ",est,"\n") se.coef = sqrt(diag(solve(Hessian))) tval = fit$par/se.coef matcoef = cbind(fit$par, se.coef, tval, 2*(1-pnorm(abs(tval)))) dimnames(matcoef) = list(names(tval), c(" Estimate", " Std. Error", " t value", "Pr(>|t|)")) cat("\nCoefficient(s):\n") printCoefmat(matcoef, digits = 4, signif.stars = TRUE) cat("---","\n") cat("Estimates in matrix form:","\n") icnt=0 ist=0 cnt=NULL if(include.mean){ ist=1 cnt=rep(0,k) secnt=rep(1,k) jdx=c(1:k)[fix1[1,]==1] icnt=length(jdx) if(icnt > 0){ cnt[jdx]=est[1:icnt] secnt[jdx]=se.coef[1:icnt] cat("Constant term: ","\n") cat("Estimates: ",cnt,"\n") } } cat("MA coefficient matrix","\n") TH=matrix(0,kq,k) seTH=matrix(1,kq,k) for (j in 1:k){ idx=c(1:kq)[fix1[(ist+1):nr,j]==1] jcnt=length(idx) if(jcnt > 0){ TH[idx,j]=est[(icnt+1):(icnt+jcnt)] seTH[idx,j]=se.coef[(icnt+1):(icnt+jcnt)] icnt=icnt+jcnt } } icnt=0 for (i in 1:q){ cat("MA(",i,")-matrix","\n") theta=t(TH[(icnt+1):(icnt+k),]) print(theta,digits=3) icnt=icnt+k } zt=da if(include.mean){ for (i in 1:k){ zt[,i]=zt[,i]-cnt[i] } } at=mFilter(zt,t(TH)) sig=t(at)%*%at/nT cat(" ","\n") cat("Residuals cov-matrix:","\n") print(sig) dd=det(sig) d1=log(dd) aic=d1+2*npar/nT bic=d1+log(nT)*npar/nT cat("----","\n") cat("aic= ",aic,"\n") cat("bic= ",bic,"\n") Theta=t(TH) if(include.mean){ TH=rbind(cnt,TH) seTH=rbind(secnt,seTH) } VMACpp <- list(data=da,MAorder=q,cnst=include.mean,coef=TH,secoef=seTH,residuals=at,Sigma=sig,Theta=Theta,mu=cnt,aic=aic,bic=bic) }
zvode <- function(y, times, func, parms, rtol=1e-6, atol=1e-6, jacfunc=NULL, jactype = "fullint", mf = NULL, verbose=FALSE, tcrit = NULL, hmin=0, hmax=NULL, hini=0, ynames=TRUE, maxord=NULL, bandup=NULL, banddown=NULL, maxsteps=5000, dllname=NULL, initfunc=dllname, initpar=parms, rpar=NULL, ipar=NULL, nout=0, outnames=NULL, forcings=NULL, initforc = NULL, fcontrol=NULL, ...) { n <- length(y) if (! is.null(times) && !is.numeric(times)) stop("`times' must be NULL or numeric") if (!is.function(func) && !is.character(func)) stop("`func' must be a function or character vector") if (is.character(func) && (is.null(dllname) || !is.character(dllname))) stop("specify the name of the dll or shared library where func can be found (without extension)") if (!is.numeric(rtol)) stop("`rtol' must be numeric") if (!is.numeric(atol)) stop("`atol' must be numeric") if (!is.null(tcrit) & !is.numeric(tcrit)) stop("`tcrit' must be numeric") if (!is.null(jacfunc) && !(is.function(jacfunc) || is.character(jacfunc))) stop(paste(jacfunc," must be a function or character vector")) if (length(atol) > 1 && length(atol) != n) stop("`atol' must either be a scalar, or as long as `y'") if (length(rtol) > 1 && length(rtol) != n) stop("`rtol' must either be a scalar, or as long as `y'") if (!is.numeric(hmin)) stop("`hmin' must be numeric") if (hmin < 0) stop("`hmin' must be a non-negative value") if (is.null(hmax)) hmax <- if (is.null(times)) 0 else max(abs(diff(times))) if (!is.numeric(hmax)) stop("`hmax' must be numeric") if (hmax < 0) stop("`hmax' must be a non-negative value") if (hmax == Inf) hmax <- 0 if (!is.null(hini)) if(hini < 0) stop("`hini' must be a non-negative value") if (!is.null(maxord)) if (maxord < 1) stop("`maxord' must be >1") if (is.null(mf)) { if (jactype == "fullint" ) imp <- 22 else if (jactype == "fullusr" ) imp <- 21 else if (jactype == "bandusr" ) imp <- 24 else if (jactype == "bandint" ) imp <- 25 else stop("'jactype' must be one of 'fullint', 'fullusr', 'bandusr' or 'bandint' if 'mf' not specified") } else imp <- mf if (! imp %in% c(10:17, 20:27, -11,-12,-14,-15,-21, -22, -24: -27)) stop ("method flag 'mf' not allowed") miter <- abs(imp)%%10 if (miter %in% c(1,4) & is.null(jacfunc)) stop ("'jacfunc' NOT specified; either specify 'jacfunc' or change 'jactype' or 'mf'") meth <- abs(imp)%/%10 jsv <- sign(imp) if (is.null (maxord)) maxord <- ifelse(meth==1,12,5) if (meth==1 && maxord > 12) stop ("'maxord' too large: should be <= 12") if (meth==2 && maxord > 5 ) stop ("'maxord' too large: should be <= 5") if (miter %in% c(4,5) && is.null(bandup)) stop("'bandup' must be specified if banded Jacobian") if (miter %in% c(4,5) && is.null(banddown)) stop("'banddown' must be specified if banded Jacobian") if (is.null(banddown)) banddown <-1 if (is.null(bandup )) bandup <-1 Func <- NULL JacFunc <- NULL if (miter == 4 && banddown>0) erow<-matrix(data=0, ncol=n, nrow=banddown) else erow<-NULL Ynames <- attr(y,"names") flist<-list(fmat=0,tmat=0,imat=0,ModelForc=NULL) ModelInit <- NULL if (is.character(func) | inherits(func, "CFunc")) { DLL <- checkDLL(func,jacfunc,dllname, initfunc,verbose,nout, outnames) ModelInit <- DLL$ModelInit Func <- DLL$Func JacFunc <- DLL$JacFunc Nglobal <- DLL$Nglobal Nmtot <- DLL$Nmtot if (! is.null(forcings)) flist <- checkforcings(forcings,times,dllname,initforc,verbose,fcontrol) rho <- NULL if (is.null(ipar)) ipar<-0 if (is.null(rpar)) rpar<-0 if (!is.null(jacfunc)) { if (miter == 4&& banddown>0) stop("The combination of user-supplied banded Jacobian in a dll is NOT allowed") } } else { if(is.null(initfunc)) initpar <- NULL rho <- environment(func) if(ynames) { Func <- function(time,state) { attr(state,"names") <- Ynames func (time,state,parms,...)[1] } Func2 <- function(time,state){ attr(state,"names") <- Ynames func (time,state,parms,...) } JacFunc <- function(time,state){ attr(state,"names") <- Ynames rbind(jacfunc(time,state,parms,...),erow) } } else { Func <- function(time,state) func (time,state,parms,...)[1] Func2 <- function(time,state) func (time,state,parms,...) JacFunc <- function(time,state) rbind(jacfunc(time,state,parms,...),erow) } FF <- checkFuncComplex(Func2,times,y,rho) Nglobal<-FF$Nglobal Nmtot <- FF$Nmtot if (miter %in% c(1,4)) { tmp <- eval(JacFunc(times[1], y), rho) if (!is.matrix(tmp)) stop("Jacobian function must return a matrix\n") dd <- dim(tmp) if((miter ==4 && any(dd != c(bandup+banddown+banddown+1,n))) || (miter ==1 && any(dd != c(n,n)))) stop("Jacobian dimension not ok") } } lzw <- n*(maxord+1)+2*n if(miter %in% c(1,2) && imp>0) lzw <- lzw + 2*n*n+2 if(miter %in% c(1,2) && imp<0) lzw <- lzw + n*n if(miter ==3) lzw <- lzw + n if(miter %in% c(4,5) && imp>0) lzw <- lzw + (3*banddown+2*bandup+2)*n if(miter %in% c(4,5) && imp<0) lzw <- lzw + (2*banddown+bandup+1)*n lrw <- 20 +n liw <- ifelse(miter %in% c(0,3),30,30+n) iwork <- vector("integer",30) rwork <- vector("double",20) rwork[] <- 0. iwork[] <- 0 iwork[1] <- banddown iwork[2] <- bandup iwork[5] <- maxord iwork[6] <- maxsteps if(! is.null(tcrit)) rwork[1] <- tcrit rwork[5] <- hini rwork[6] <- hmax rwork[7] <- hmin if (! is.null(times)) itask <- ifelse (is.null (tcrit), 1,4) else itask <- ifelse (is.null (tcrit), 2,5) if(is.null(times)) times<-c(0,1e8) if (verbose) { printtask(itask,func,jacfunc) printM("\n--------------------") printM("Integration method") printM("--------------------") df <- c("method flag, =", "jsv =", "meth =", "miter =") vals <- c(imp, jsv, meth, miter) txt <- "; (note: mf = jsv * (10 * meth + miter))" if (jsv==1) txt<-c(txt, "; a copy of the Jacobian is saved for reuse in the corrector iteration algorithm" ) else if (jsv==-1)txt<-c(txt, "; a copy of the Jacobian is not saved") if (meth==1)txt<-c(txt, "; the basic linear multistep method: the implicit Adams method") else if (meth==2)txt<-c(txt,"; the basic linear multistep method: based on backward differentiation formulas") if (miter==0)txt<-c(txt, "; functional iteration (no Jacobian matrix is involved") else if (miter==1)txt<-c(txt, "; chord iteration with a user-supplied full (NEQ by NEQ) Jacobian") else if (miter==2)txt<-c(txt, "; chord iteration with an internally generated full Jacobian, (NEQ extra calls to F per df/dy value)") else if (miter==3)txt<-c(txt, "; chord iteration with an internally generated diagonal Jacobian (1 extra call to F per df/dy evaluation)") else if (miter==4)txt<-c(txt, "; chord iteration with a user-supplied banded Jacobian") else if (miter==5)txt<-c(txt, "; chord iteration with an internally generated banded Jacobian (using ML+MU+1 extra calls to F per df/dy evaluation)") printmessage(df, vals, txt) } storage.mode(y) <- "complex" storage.mode(times) <- "double" on.exit(.C("unlock_solver")) out <- .Call("call_zvode", y, times, Func, initpar, rtol, atol, rho, tcrit, JacFunc, ModelInit, as.integer(itask), as.double(rwork),as.integer(iwork), as.integer(imp),as.integer(Nglobal), as.integer(lzw),as.integer(lrw),as.integer(liw), as.complex (rpar), as.integer(ipar),flist,PACKAGE = "deSolve") nR <- ncol(out) out [1,] <- as.complex(times[1:nR]) out <- saveOut(out, y, n, Nglobal, Nmtot, func, Func2, iin=c(1,12:23), iout=1:13) attr(out, "type") <- "cvode" if (verbose) diagnostics(out) out } checkFuncComplex<- function (Func2, times, y, rho) { if (! is.complex(y)) stop("'y' should be complex, not real") tmp <- eval(Func2(times[1], y), rho) if (!is.list(tmp)) stop("Model function must return a list\n") if (length(tmp[[1]]) != length(y)) stop(paste("The number of derivatives returned by func() (", length(tmp[[1]]), ") must equal the length of the initial conditions vector (", length(y),")",sep="")) if (! is.complex(tmp[[1]])) stop("derivatives (first element returned by 'func') should be complex, not real") Nglobal <- if (length(tmp) > 1) length(unlist(tmp[-1])) else 0 Nmtot <- attr(unlist(tmp[-1]),"names") return(list(Nglobal = Nglobal, Nmtot=Nmtot)) }
context("Github API") test_that("Non Nested", { mydata <- fromJSON("https://api.github.com/users/hadley/orgs"); expect_that(mydata, is_a("data.frame")); }); test_that("Nested 1 Level", { mydata <- fromJSON("https://api.github.com/users/hadley/repos"); expect_that(mydata, is_a("data.frame")); expect_that(mydata$owner, is_a("data.frame")); expect_that(nrow(mydata), equals(nrow(mydata$owner))); }); test_that("Nested 1 Level", { mydata <- fromJSON("https://api.github.com/repos/hadley/ggplot2/issues"); expect_that(mydata, is_a("data.frame")); expect_that(mydata$user, is_a("data.frame")); expect_that(mydata$pull_request, is_a("data.frame")); expect_that(nrow(mydata), equals(nrow(mydata$pull_request))); }); test_that("Nested 1 Level within list", { mydata <- fromJSON("https://api.github.com/search/repositories?q=tetris+language:assembly&sort=stars&order=desc"); expect_that(mydata, is_a("list")); expect_that(mydata$items, is_a("data.frame")); expect_that(mydata$items$owner, is_a("data.frame")); expect_that(nrow(mydata$items), equals(nrow(mydata$items$owner))); }); test_that("Nested 2 Level", { mydata <- fromJSON("https://api.github.com/repos/hadley/ggplot2/commits"); expect_that(mydata, is_a("data.frame")); expect_that(mydata$commit, is_a("data.frame")); expect_that(mydata$commit$author, is_a("data.frame")); expect_that(mydata$commit$author$name, is_a("character")); expect_that(nrow(mydata), equals(nrow(mydata$commit))); expect_that(nrow(mydata), equals(nrow(mydata$commit$author))); }); test_that("Nested inconsistent (payload), one-to-many", { mydata <- fromJSON("https://api.github.com/users/hadley/events"); expect_that(mydata, is_a("data.frame")); expect_that(mydata$actor, is_a("data.frame")); expect_that(mydata$repo, is_a("data.frame")); expect_that(mydata$type, is_a("character")); expect_that(mydata$payload, is_a("data.frame")); if(any(mydata$type == "PushEvent")){ expect_true(all(vapply(mydata$payload$commits, function(x){is.null(x) || is.data.frame(x)}, logical(1)))); } }); test_that("Nested inconsistent (payload), one-to-many", { mydata <- fromJSON("https://api.github.com/repos/hadley/ggplot2/events"); if(any("ForkEvent" %in% mydata$type)){ expect_that(mydata$payload$forkee$owner, is_a("data.frame")) } if(any(mydata$type %in% c("IssuesEvent", "IssueCommentEvent"))){ expect_that(mydata$payload$issue, is_a("data.frame")); expect_that(mydata$payload$issue$user, is_a("data.frame")); } });
detectbound <- function(distname, vstart, obs, fix.arg=NULL, echo=FALSE) { ddistname <- paste("d", distname, sep="") argdist <- formalArgs(ddistname) argdist <- argdist[!argdist %in% c("x", "log")] stopifnot(all(names(vstart) %in% argdist)) if("scale" %in% argdist && "rate" %in% argdist) { if(length(grep("rate", as.character(formals(ddistname)$scale))) > 0) { argdist <- argdist[argdist != "rate"] if("rate" %in% names(vstart)) { vstart["rate"] <- 1/vstart["rate"] names(vstart)[names(vstart) == "rate"] <- "scale" } } } argdist <- argdist[!argdist %in% names(fix.arg)] if(length(argdist) == 0) return(NULL) if(echo) { print(argdist) print(vstart) } lowb <- rep(-Inf, length(argdist)) uppb <- -lowb names(lowb) <- names(uppb) <- argdist eps <- sqrt(.Machine$double.eps) owarn <- getOption("warn") oerr <- getOption("show.error.messages") options(warn=-1, show.error.messages=FALSE) for(a in argdist) { if(echo) cat(a, "\n") dx <- do.call(ddistname, c(list(obs), as.list(vstart), as.list(fix.arg))) if(any(is.nan(dx))) stop("wrong init param") vstarta <- vstart aval <- -1:1 for(i in 1:length(aval)) { vstarta[a] <- aval[i]-eps dx1 <- try(do.call(ddistname, c(list(obs), as.list(vstarta), as.list(fix.arg))), silent=TRUE) vstarta[a] <- aval[i]+eps dx2 <- try(do.call(ddistname, c(list(obs), as.list(vstarta), as.list(fix.arg))), silent=TRUE) if(echo) { cat(i, "\ttested value", vstarta, "\n") print(dx1) print(dx2) } if(class(dx1) == "try-error" && class(dx2) != "try-error") { lowb[a] <- aval[i] } if(any(is.nan(dx1)) && any(!is.nan(dx2))) { lowb[a] <- aval[i] } if(class(dx1) != "try-error" && class(dx2) == "try-error") { uppb[a] <- aval[i] } if(any(!is.nan(dx1)) && any(is.nan(dx2))) { uppb[a] <- aval[i] } } } options(warn=owarn, show.error.messages=oerr) rbind(lowb, uppb) }
context("test bi_scale_fill function") data("stl_race_income", package = "biscale") data <- bi_class(stl_race_income, x = pctWhite, y = medInc, dim = 2) library(ggplot2) library(sf) test_that("missing parameters trigger appropriate errors", { expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(dim = 2), "A palette must be specified for the 'pal' argument. Please choose one of: 'Brown', 'DkBlue', 'DkCyan', 'DkViolet', or 'GrPink'.") }) test_that("incorrectly specified parameters trigger appropriate errors", { expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "ham", dim = 2), "The given palette is not one of the allowed options for bivariate mapping. Please choose one of: 'Brown', 'DkBlue', 'DkCyan', 'DkViolet', or 'GrPink'.") expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "Brown", dim = 5), "The 'dim' argument only accepts the numeric values '2' or '3'.") expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "Brown", dim = "ham"), "The 'dim' argument only accepts the numeric values '2' or '3'.") }) test_that("correctly specified functions execute without error", { expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "Brown", dim = 2), NA) expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "DkBlue", dim = 2), NA) expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "DkCyan", dim = 2), NA) expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "DkViolet", dim = 2), NA) expect_error(ggplot() + geom_sf(data = data, aes(fill = bi_class), color = "white", size = 0.1, show.legend = FALSE) + bi_scale_fill(pal = "GrPink", dim = 2), NA) }) custom_pal <- bi_pal_manual(val_1_1 = " test_that("correctly specified functions execute without error", { expect_error(ggplot() + geom_sf(data = data, aes(color = bi_class), show.legend = FALSE) + bi_scale_fill(pal = custom_pal, dim = 2), NA) })
classnameOK <- function(text) { gsub("[^._A-Za-z0-9]+", "_", text) } JunitReporter <- R6::R6Class("JunitReporter", inherit = Reporter, public = list( results = NULL, timer = NULL, doc = NULL, errors = NULL, failures = NULL, skipped = NULL, tests = NULL, root = NULL, suite = NULL, suite_time = NULL, file_name = NULL, elapsed_time = function() { time <- (private$proctime() - self$timer)[["elapsed"]] self$timer <- private$proctime() time }, reset_suite = function() { self$errors <- 0 self$failures <- 0 self$skipped <- 0 self$tests <- 0 self$suite_time <- 0 }, start_reporter = function() { check_installed("xml2", "JunitReporter") self$timer <- private$proctime() self$doc <- xml2::xml_new_document() self$root <- xml2::xml_add_child(self$doc, "testsuites") self$reset_suite() }, start_file = function(file) { self$file_name <- file }, start_test = function(context, test) { if (is.null(context)) { context_start_file(self$file_name) } }, start_context = function(context) { self$suite <- xml2::xml_add_child( self$root, "testsuite", name = context, timestamp = private$timestamp(), hostname = private$hostname() ) }, end_context = function(context) { xml2::xml_attr(self$suite, "tests") <- as.character(self$tests) xml2::xml_attr(self$suite, "skipped") <- as.character(self$skipped) xml2::xml_attr(self$suite, "failures") <- as.character(self$failures) xml2::xml_attr(self$suite, "errors") <- as.character(self$errors) xml2::xml_attr(self$suite, "time") <- as.character(round(self$suite_time, 3)) self$reset_suite() }, add_result = function(context, test, result) { self$tests <- self$tests + 1 time <- self$elapsed_time() self$suite_time <- self$suite_time + time name <- test %||% "(unnamed)" testcase <- xml2::xml_add_child( self$suite, "testcase", time = toString(time), classname = classnameOK(context), name = classnameOK(name) ) first_line <- function(x) { loc <- expectation_location(x) paste0(strsplit(x$message, split = "\n")[[1]][1], " (", loc, ")") } if (expectation_error(result)) { error <- xml2::xml_add_child(testcase, "error", type = "error", message = first_line(result)) xml2::xml_text(error) <- crayon::strip_style(format(result)) self$errors <- self$errors + 1 } else if (expectation_failure(result)) { failure <- xml2::xml_add_child(testcase, "failure", type = "failure", message = first_line(result)) xml2::xml_text(failure) <- crayon::strip_style(format(result)) self$failures <- self$failures + 1 } else if (expectation_skip(result)) { xml2::xml_add_child(testcase, "skipped", message = first_line(result)) self$skipped <- self$skipped + 1 } }, end_reporter = function() { if (is.character(self$out)) { xml2::write_xml(self$doc, self$out, format = TRUE) } else if (inherits(self$out, "connection")) { file <- tempfile() xml2::write_xml(self$doc, file, format = TRUE) cat(brio::read_file(file), file = self$out) } else { stop("unsupported output type: ", toString(self$out)) } } ), private = list( proctime = function() { proc.time() }, timestamp = function() { strftime(Sys.time(), "%Y-%m-%dT%H:%M:%SZ", tz = "UTC") }, hostname = function() { Sys.info()[["nodename"]] } ) ) JunitReporterMock <- R6::R6Class("JunitReporterMock", inherit = JunitReporter, public = list(), private = list( proctime = function() { c(user = 0, system = 0, elapsed = 0) }, timestamp = function() { "1999:12:31 23:59:59" }, hostname = function() { "nodename" } ) )
require(ocs4R, quietly = TRUE) require(testthat) context("api-user-provisioning") test_that("User Provisioning API - getUsers",{ users <- OCS$getUsers() expect_is(users, "character") expect_equal(length(users), 1L) }) test_that("User Provisioning API - getUser",{ user <- OCS$getUser("admin") expect_is(user, "list") user.df <- OCS$getUser("admin", TRUE) expect_is(user.df, "data.frame") }) test_that("User Provisioning API - addUser",{ added <- OCS$addUser("john.doe", password = "ocs4johnsecret") expect_true(added) users <- OCS$getUsers() expect_equal(length(users), 2L) user <- OCS$getUser("john.doe") expect_is(user, "list") expect_true(user$enabled) expect_equal(user$displayname, "john.doe") expect_null(user$email) }) test_that("User Provisioning API - disableUser / enableUser",{ disabled <- OCS$disableUser("john.doe") expect_true(disabled) user <- OCS$getUser("john.doe") expect_false(user$enabled) enabled <- OCS$enableUser("john.doe") expect_true(enabled) user <- OCS$getUser("john.doe") expect_true(user$enabled) }) test_that("User Provisioning API - editUser",{ edited <- OCS$editUser("john.doe", key = "display", value = "John Doe") expect_true(edited) john <- OCS$getUser("john.doe") expect_equal(john$displayname, "John Doe") edited2 <- OCS$editUserDisplayName("john.doe", displayName = "John Doe Jr.") expect_true(edited2) john <- OCS$getUser("john.doe") expect_equal(john$displayname, "John Doe Jr.") }) test_that("User Provisioning API - getUserGroups",{ admingroups <- OCS$getUserGroups("admin") expect_equal(admingroups, "admin") }) test_that("User Provisioning API - getGroups",{ groups <- OCS$getGroups() expect_equal(groups, "admin") }) test_that("User Provisioning API - addGroup",{ added <- OCS$addGroup("scientists") expect_true(added) groups <- OCS$getGroups() expect_equal(groups, c("admin", "scientists")) }) test_that("User Provisioning API - getGroup",{ admin_group <- OCS$getGroup("admin") expect_equal(admin_group$id, "admin") expect_equal(admin_group$users, "admin") sc_group <- OCS$getGroup("scientists") expect_equal(sc_group$id, "scientists") expect_null(sc_group$users) }) test_that("User Provisioning API - addToGroup",{ added <- OCS$addToGroup("john.doe", "scientists") expect_true(added) expect_true("john.doe" %in% OCS$getGroup("scientists")$users) }) test_that("User Provisioning API - removeFromGroup",{ removed <- OCS$removeFromGroup("john.doe", "scientists") expect_true(removed) expect_false("john.doe" %in% OCS$getGroup("scientists")$users) }) test_that("User Provisioning API - deleteUser",{ deleted <- OCS$deleteUser("john.doe") expect_true(deleted) users <- OCS$getUsers() expect_false("john.doe" %in% users) }) test_that("UserProvisioning API - deleteGroup",{ deleted <- OCS$deleteGroup("scientists") expect_true(deleted) groups <- OCS$getGroups() expect_false("scientists" %in% groups) })
context("ape") test_that("From ape::phylo to RNeXML::nexml object", { skip_on_cran() data(bird.orders) expect_is(as(bird.orders, "nexml"), class="nexml") }) test_that("We can go from various orderings of ape::phylo to RNeXML::nexml", { skip_on_cran() data(bird.orders) nexml <- as(bird.orders, "nexml") phy <- as(nexml, "phylo") p <- plot(phy) expect_that(plot(phy), is_a("list")) expect_that(phy, is_a("phylo")) }) test_that("From nexml to multiPhylo", { skip_on_cran() f <- system.file("examples", "trees.xml", package="RNeXML") doc <- xmlParse(f) root <- xmlRoot(doc) nexml <- as(root, "nexml") expect_warning(phy <- as(nexml, "phylo"), "Multiple trees found, Returning multiPhylo object") expect_is(phy, "multiPhylo") }) test_that("We can serialize the various versions of the ape format", { skip_on_cran() data(bird.orders) nexml <- as(bird.orders, "nexml") nexml_write(nexml, file = "test.xml") expect_true_or_null(nexml_validate("test.xml")) unlink("test.xml") }) test_that("We can read and write NeXML to phylo and back without edge.lengths", { skip_on_cran() s <- "owls(((Strix_aluco,Asio_otus),Athene_noctua),Tyto_alba);" cat(s, file = "ex.tre", sep = "\n") owls <- read.tree("ex.tre") nexml_write(owls, file = "ex.xml") owls2 <- as(nexml_read("ex.xml"), "phylo") expect_equal(owls, owls2) unlink("ex.tre") unlink("ex.xml") }) test_that("Rooted trees remain rooted on conversions", { skip_on_cran() expect_true(is.rooted(bird.orders)) expect_true(is.rooted(as(as(bird.orders, "nexml"), "phylo"))) write.nexml(bird.orders, file = "tmp.xml") expect_true(is.rooted(as(read.nexml("tmp.xml"), "phylo"))) unlink("tmp.xml") }) test_that("Unrooted trees remain unrooted on conversions", { skip_on_cran() phy <- unroot(bird.orders) expect_false(is.rooted(phy)) expect_false(is.rooted(as(as(phy, "nexml"), "phylo"))) write.nexml(phy, file = "tmp.xml") expect_false(is.rooted(as(read.nexml("tmp.xml"), "phylo"))) unlink("tmp.xml") }) test_that("We can convert trees with only some edge lengths into ape::phylo", { skip_on_cran() f <- system.file("examples", "some_missing_branchlengths.xml", package="RNeXML") expect_warning(a <- as(read.nexml(f), "phylo"), "Multiple trees found, Returning multiPhylo object") }) test_that("NeXML with rootedge can be converted to ape::phylo", { skip_on_cran() f <- system.file("examples", "coal.xml", package = "RNeXML") nex <- read.nexml(f) tr <- nex@trees[[1]]@tree[[1]] phy <- as(nex, "phylo") testthat::expect_equal(Nnode(phy) + Ntip(phy), length(tr@node) + 1) testthat::expect_equal(Nedge(phy), length(tr@edge) + 1) newick <- write.tree(phy) testthat::expect_true(startsWith(newick, "((")) testthat::expect_true(grepl('):[0-9.]+);$', newick)) })
context( "sfc_multipoints " ) test_that("various objects converted to sfc_MULTIPOINT objects",{ m <- matrix() expect_error( sfheaders:::rcpp_sfc_multipoint( m, NULL, NULL, "" ), "sfheaders - can't work out the dimension") m <- matrix(c(0,0), ncol = 2) res <- sfheaders:::rcpp_sfc_multipoint( m, NULL, NULL, "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( all( is.na( unclass( attr( res, "z_range" ) ) ) ) ) m <- matrix(c(0,0,1,1), ncol = 2, byrow = T) res <- sfheaders:::rcpp_sfc_multipoint( m, NULL, NULL, "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(c(0,0,0,0,1,1), ncol = 3, byrow = T) res <- sfheaders:::rcpp_sfc_multipoint( m, NULL, NULL, "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( all( attr( res, "z_range") == c(0,1) ) ) m <- matrix(c(0,0,1,1), ncol = 2, byrow = T) res <- sfheaders:::rcpp_sfc_multipoint( m, c(0L,1L), NULL, "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(c(0,0,1,1), ncol = 2, byrow = T) expect_error( sfheaders:::rcpp_sfc_multipoint( m, NULL, 0L, "" ), "sfheaders - can't work out the dimension" ) m <- matrix(c(0,0,1,1), ncol = 2, byrow = T) res <- sfheaders:::rcpp_sfc_multipoint( m, c(0L,1L), 0L, "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(c(0,0,1,1), ncol = 2, byrow = T) expect_error( sfheaders:::rcpp_sfc_multipoint( m, NULL, c(0L), "" ), "sfheaders - can't work out the dimension") m <- matrix(c(0,0,0,0,1,1,1,1,1), ncol = 3, byrow = T) res <- sfheaders:::rcpp_sfc_multipoint( m, c(1L,2L), c(0L), "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) df <- data.frame(x = 1, y = 1) res <- sfheaders:::rcpp_sfc_multipoint(df, NULL, NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) df <- data.frame(id = 1, x = 1, y = 1) res <- sfheaders:::rcpp_sfc_multipoint(df, c("x","y"), c("id"), "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) df <- data.frame(id = 1:2, x = 1:2, y = 1:2) res <- sfheaders:::rcpp_sfc_multipoint(df, c("x","y"), c("id"), "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) df <- data.frame(id = 1, x = 1:2, y = 1:2) res <- sfheaders:::rcpp_sfc_multipoint(df, c("x","y"), c("id"), "" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) }) test_that("after refactoring issue14 I haven't lost anything",{ is_multipoint <- function(x) { y <- sapply( x, function(y) is.matrix(unclass(y))) z <- sapply( x, function(y) attr( y, "class")[2] == "MULTIPOINT") return( all(y) & all(z)) } v <- 1:3 res <- sfheaders:::rcpp_sfc_multipoint(v, NULL, NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) v <- c(1.2,2,3) res <- sfheaders:::rcpp_sfc_multipoint(v, NULL, NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1:4, ncol = 2) res <- sfheaders:::rcpp_sfc_multipoint(m, NULL, NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1:4, ncol = 2) res <- sfheaders:::rcpp_sfc_multipoint(m, c(0L,1L), NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1:4, ncol = 2) df <- as.data.frame( m ) res <- sfheaders:::rcpp_sfc_multipoint(df, NULL, NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1:4, ncol = 2) df <- as.data.frame( m ) res <- sfheaders:::rcpp_sfc_multipoint(df, c(0L,1L), NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1:4, ncol = 2) df <- as.data.frame( m ) res <- sfheaders:::rcpp_sfc_multipoint(df, c("V1","V2"), NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1L:4L, ncol = 2) df <- as.data.frame( m ) m <- as.matrix( m ) res <- sfheaders:::rcpp_sfc_multipoint(m, c("V1","V2"), NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(c(1.2,2,3,4), ncol = 2) df <- as.data.frame( m ) m <- as.matrix( m ) res <- sfheaders:::rcpp_sfc_multipoint(m, c("V1","V2"), NULL, "") expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) m <- matrix(1:8, ncol = 2) m <- cbind(m, c(1,1,2,2)) res <- sfheaders:::rcpp_sfc_multipoint(m, NULL, 2L, "") expect_true( is_multipoint( res ) ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(1L:8L, ncol = 2) m <- cbind(m, c(1L,1L,2L,2L)) res <- sfheaders:::rcpp_sfc_multipoint(m, c(0L,1L), 2L, "") expect_true( is_multipoint( res ) ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(1:8, ncol = 2) m <- cbind(m, c(1,1,2,2)) res <- sfheaders:::rcpp_sfc_multipoint(m, c(0L,1L), 2L, "") expect_true( is_multipoint( res ) ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(1:8, ncol = 2) m <- cbind(m, c(1,1,2,2)) df <- as.data.frame( m ) res <- sfheaders:::rcpp_sfc_multipoint(df, NULL, 2L, "") expect_true( is_multipoint( res ) ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(1:8, ncol = 2) m <- cbind(m, c(1,1,2,2)) df <- as.data.frame( m ) res <- sfheaders:::rcpp_sfc_multipoint(df, c(0L,1L), 2L, "") expect_true( is_multipoint( res ) ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(1:8, ncol = 2) m <- cbind(m, c(1,1,2,2)) df <- as.data.frame( m ) res <- sfheaders:::rcpp_sfc_multipoint(df, c("V1","V2"), c("V3"), "") expect_true( is_multipoint( res ) ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) m <- matrix(1:4, ncol = 2) expect_error( sfheaders:::rcpp_sfc_multipoint(m, NULL, 0L, ""), "sfheaders - can't work out the dimension") }) test_that("data.frame with non-numeric id columns work",{ is_multipoint <- function(x) { y <- sapply( x, function(y) is.matrix(unclass(y))) z <- sapply( x, function(y) attr( y, "class")[2] == "MULTIPOINT") return( all(y) & all(z)) } df <- data.frame( p_id = letters[c(1,1,1,1,2,2,2,2)] , l_id = c(1,1,1,1,1,1,1,1) , x = c(1,2,3,1,4,5,6,4) , y = c(1,2,3,1,4,5,6,4) , stringsAsFactors = F ) res <- sfheaders::sfc_multipoint( obj = df , x = "x" , y = "y" , multipoint_id = "p_id" ) expect_equal( attr( res, "class" ), c("sfc_MULTIPOINT", "sfc") ) expect_true( is_multipoint( res ) ) }) test_that("vectorised version works",{ is_multipoint <- function(x) { y <- sapply( x, function(y) is.matrix(unclass(y))) z <- sapply( x, function(y) attr( y, "class")[2] == "MULTIPOINT") return( all(y) & all(z)) } m1 <- matrix(1:12, ncol = 3) m2 <- matrix(1:12, ncol = 3) lst <- list( m1, m2 ) res <- sfheaders:::rcpp_sfc_multipoints( lst, "" ) expect_true( all( sapply( res, is_multipoint ) ) ) })
timestamp <- Sys.time() library(caret) library(plyr) library(recipes) library(dplyr) model <- "bayesglm" set.seed(2) training <- twoClassSim(50, linearVars = 2) testing <- twoClassSim(500, linearVars = 2) trainX <- training[, -ncol(training)] trainY <- training$Class rec_cls <- recipe(Class ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all", classProbs = TRUE, summaryFunction = twoClassSummary) cctrl2 <- trainControl(method = "LOOCV", classProbs = TRUE, summaryFunction = twoClassSummary) cctrl3 <- trainControl(method = "none", classProbs = TRUE, summaryFunction = twoClassSummary) set.seed(849) test_class_cv_model <- train(trainX, trainY, method = "bayesglm", trControl = cctrl1, metric = "ROC", preProc = c("center", "scale")) set.seed(849) test_class_cv_form <- train(Class ~ ., data = training, method = "bayesglm", trControl = cctrl1, metric = "ROC", preProc = c("center", "scale")) test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)]) test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob") test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)]) test_class_prob_form <- predict(test_class_cv_form, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_loo_model <- train(trainX, trainY, method = "bayesglm", trControl = cctrl2, metric = "ROC", preProc = c("center", "scale")) set.seed(849) test_class_none_model <- train(trainX, trainY, method = "bayesglm", trControl = cctrl3, tuneLength = 1, metric = "ROC", preProc = c("center", "scale")) test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)]) test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob") set.seed(849) test_class_rec <- train(x = rec_cls, data = training, method = "bayesglm", trControl = cctrl1, metric = "ROC") if( !isTRUE( all.equal(test_class_cv_model$results, test_class_rec$results)) ) stop("CV weights not giving the same results") test_class_imp_rec <- varImp(test_class_rec) test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)]) test_class_prob_rec <- predict(test_class_rec, testing[, -ncol(testing)], type = "prob") test_levels <- levels(test_class_cv_model) if(!all(levels(trainY) %in% test_levels)) cat("wrong levels") library(caret) library(plyr) library(recipes) library(dplyr) set.seed(1) training <- SLC14_1(30) testing <- SLC14_1(100) trainX <- training[, -ncol(training)] trainY <- training$y rec_reg <- recipe(y ~ ., data = training) %>% step_center(all_predictors()) %>% step_scale(all_predictors()) testX <- trainX[, -ncol(training)] testY <- trainX$y rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all") rctrl2 <- trainControl(method = "LOOCV") rctrl3 <- trainControl(method = "none") set.seed(849) test_reg_cv_model <- train(trainX, trainY, method = "bayesglm", trControl = rctrl1, preProc = c("center", "scale")) test_reg_pred <- predict(test_reg_cv_model, testX) set.seed(849) test_reg_cv_form <- train(y ~ ., data = training, method = "bayesglm", trControl = rctrl1, preProc = c("center", "scale")) test_reg_pred_form <- predict(test_reg_cv_form, testX) set.seed(849) test_reg_loo_model <- train(trainX, trainY, method = "bayesglm", trControl = rctrl2, preProc = c("center", "scale")) set.seed(849) test_reg_none_model <- train(trainX, trainY, method = "bayesglm", trControl = rctrl3, tuneLength = 1, preProc = c("center", "scale")) test_reg_none_pred <- predict(test_reg_none_model, testX) set.seed(849) test_reg_rec <- train(x = rec_reg, data = training, method = "bayesglm", trControl = rctrl1) if( !isTRUE( all.equal(test_reg_cv_model$results, test_reg_rec$results)) ) stop("CV weights not giving the same results") test_reg_imp_rec <- varImp(test_reg_rec) test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)]) tests <- grep("test_", ls(), fixed = TRUE, value = TRUE) sInfo <- sessionInfo() timestamp_end <- Sys.time() save(list = c(tests, "sInfo", "timestamp", "timestamp_end"), file = file.path(getwd(), paste(model, ".RData", sep = ""))) if(!interactive()) q("no")
print.phenologyout <- function(x, ...) { object <- x cat(paste("Number of timeseries: ", nrow(object$synthesis), "\n", sep="")) for (i in 1:nrow(object$synthesis)) { nmser <- object$synthesis[i, "series"] tx <- paste0("Timeseries: ", nmser) cat(paste0(rep("-", nchar(tx)), collapse=""), "\n") cat(tx, "\n") cat(paste0(rep("-", nchar(tx)), collapse=""), "\n") cat("Total estimate not taking into account the observations: ") cat(paste0("Mean=", object$synthesis[nmser, "without_obs_Mean"], "\n")) cat("Total estimate taking into account the observations: ") cat(paste0("Mean=", object$synthesis[nmser, "with_obs_Mean"], "\n")) if (!is.na(object$synthesis[nmser, "without_obs_Median_ML"])) { cat("Total estimate not taking into account the observations ML-based:\n") cat(paste0("Low=", object$synthesis[nmser, "without_obs_Low_ML"], " Median=", object$synthesis[nmser, "without_obs_Median_ML"], " High=", object$synthesis[nmser, "without_obs_High_ML"], "\n")) cat("Total estimate taking into account the observations ML-based:\n") cat(paste0("Low=", object$synthesis[nmser, "with_obs_Low_ML"], " Median=", object$synthesis[nmser, "with_obs_Median_ML"], " High=", object$synthesis[nmser, "with_obs_High_ML"], "\n")) } if (!is.na(object$synthesis[nmser, "without_obs_Median_MCMC"])) { cat("Total estimate not taking into account the observations MCMC-based:\n") cat(paste0("Low=", object$synthesis[nmser, "without_obs_Low_MCMC"], " Median=", object$synthesis[nmser, "without_obs_Median_MCMC"], " High=", object$synthesis[nmser, "without_obs_High_MCMC"], "\n")) cat("Total estimate taking into account the observations MCMC-based:\n") cat(paste0("Low=", object$synthesis[nmser, "with_obs_Low_MCMC"], " Median=", object$synthesis[nmser, "with_obs_Median_MCMC"], " High=", object$synthesis[nmser, "with_obs_High_MCMC"], "\n")) } } }
lsh <- function(bucket_size=NA, hash_width=NA, input_model=NA, k=NA, num_probes=NA, projections=NA, query=NA, reference=NA, second_hash_size=NA, seed=NA, tables=NA, true_neighbors=NA, verbose=FALSE) { IO_RestoreSettings("K-Approximate-Nearest-Neighbor Search with LSH") if (!identical(bucket_size, NA)) { IO_SetParamInt("bucket_size", bucket_size) } if (!identical(hash_width, NA)) { IO_SetParamDouble("hash_width", hash_width) } if (!identical(input_model, NA)) { IO_SetParamLSHSearchPtr("input_model", input_model) } if (!identical(k, NA)) { IO_SetParamInt("k", k) } if (!identical(num_probes, NA)) { IO_SetParamInt("num_probes", num_probes) } if (!identical(projections, NA)) { IO_SetParamInt("projections", projections) } if (!identical(query, NA)) { IO_SetParamMat("query", to_matrix(query)) } if (!identical(reference, NA)) { IO_SetParamMat("reference", to_matrix(reference)) } if (!identical(second_hash_size, NA)) { IO_SetParamInt("second_hash_size", second_hash_size) } if (!identical(seed, NA)) { IO_SetParamInt("seed", seed) } if (!identical(tables, NA)) { IO_SetParamInt("tables", tables) } if (!identical(true_neighbors, NA)) { IO_SetParamUMat("true_neighbors", to_matrix(true_neighbors)) } if (verbose) { IO_EnableVerbose() } else { IO_DisableVerbose() } IO_SetPassed("distances") IO_SetPassed("neighbors") IO_SetPassed("output_model") lsh_mlpackMain() output_model <- IO_GetParamLSHSearchPtr("output_model") attr(output_model, "type") <- "LSHSearch" out <- list( "distances" = IO_GetParamMat("distances"), "neighbors" = IO_GetParamUMat("neighbors"), "output_model" = output_model ) IO_ClearSettings() return(out) }
html_cat <- function(msg, id = paste0("ID", stats::runif(1))) { htmltools::div(class = "caption", id = id, style = "padding-top: 8px; padding-bottom: 8px; color: text-align: left;", msg) %>% as.character() %>% cat() } break_page <- function() { htmltools::HTML( paste0(htmltools::div(class = 'page-break-after', "")) ) } break_page_asis <- function() { htmltools::HTML( cat( paste0( htmltools::div(class = 'page-break-after', "") ) ) ) } break_line_asis <- function(n = 1) { for (i in seq(n)) { htmltools::br() %>% as.character() %>% cat() } } print_tab <- function(tab, n_rows = 25, add_row = 3, caption = "", full_width = TRUE, font_size = 14, align = NULL, col.names = NA, digits = 2, big_mark = TRUE) { N <- nrow(tab) n_pages <- 1 if (N > n_rows) { n_pages <- n_pages + ceiling((N - n_rows) / (n_rows + add_row)) } for (i in seq(n_pages)) { if (i == 1) { idx <- intersect(seq(N), seq(n_rows)) } else { idx <- (max(idx) + 1):(max(idx) + n_rows + add_row) %>% pmin(N) %>% unique() } if (is.null(align)) { if (big_mark) { ktab <- knitr::kable(tab[idx, ], digits = digits, format = "html", caption = ifelse(i > 1, paste(caption, "(continued)"), caption), col.names = col.names, format.args = list(big.mark = ",")) } else { ktab <- knitr::kable(tab[idx, ], digits = digits, format = "html", caption = ifelse(i > 1, paste(caption, "(continued)"), caption), col.names = col.names) } } else { if (big_mark) { ktab <- knitr::kable(tab[idx, ], digits = digits, format = "html", align = align, caption = ifelse(i > 1, paste(caption, "(continued)"), caption), col.names = col.names, format.args = list(big.mark = ",")) } else { ktab <- knitr::kable(tab[idx, ], digits = digits, format = "html", align = align, caption = ifelse(i > 1, paste(caption, "(continued)"), caption), col.names = col.names) } } ktab %>% kableExtra::kable_styling(full_width = full_width, font_size = font_size, position = "left") %>% gsub("font-size: initial !important;", "font-size: 12px !important;", .) %>% cat() if (n_pages == 1 | i < n_pages) { break_page_asis() } } } col2hex <- function(col) { if (length(grep("^ return(col) } mat_rgb <- col %>% tolower() %>% grDevices::col2rgb() %>% t() / 255 grDevices::rgb(mat_rgb) } fixed_text <- function(x, max_width = 30) { ifelse(nchar(x) > max_width, paste(strtrim(x, max_width - 4), "..."), x) }
context("basic RDD functions") sc <- sparkR.init() nums <- 1:10 rdd <- parallelize(sc, nums, 2L) intPairs <- list(list(1L, -1), list(2L, 100), list(2L, 1), list(1L, 200)) intRdd <- parallelize(sc, intPairs, 2L) test_that("get number of partitions in RDD", { expect_equal(numPartitions(rdd), 2) expect_equal(numPartitions(intRdd), 2) }) test_that("first on RDD", { expect_true(first(rdd) == 1) newrdd <- lapply(rdd, function(x) x + 1) expect_true(first(newrdd) == 2) }) test_that("count and length on RDD", { expect_equal(count(rdd), 10) expect_equal(length(rdd), 10) }) test_that("count by values and keys", { mods <- lapply(rdd, function(x) { x %% 3 }) actual <- countByValue(mods) expected <- list(list(0, 3L), list(1, 4L), list(2, 3L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) actual <- countByKey(intRdd) expected <- list(list(2L, 2L), list(1L, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) }) test_that("lapply on RDD", { multiples <- lapply(rdd, function(x) { 2 * x }) actual <- collect(multiples) expect_equal(actual, as.list(nums * 2)) }) test_that("lapplyPartition on RDD", { sums <- lapplyPartition(rdd, function(part) { sum(unlist(part)) }) actual <- collect(sums) expect_equal(actual, list(15, 40)) }) test_that("mapPartitions on RDD", { sums <- mapPartitions(rdd, function(part) { sum(unlist(part)) }) actual <- collect(sums) expect_equal(actual, list(15, 40)) }) test_that("flatMap() on RDDs", { flat <- flatMap(intRdd, function(x) { list(x, x) }) actual <- collect(flat) expect_equal(actual, rep(intPairs, each=2)) }) test_that("filterRDD on RDD", { filtered.rdd <- filterRDD(rdd, function(x) { x %% 2 == 0 }) actual <- collect(filtered.rdd) expect_equal(actual, list(2, 4, 6, 8, 10)) filtered.rdd <- Filter(function(x) { x[[2]] < 0 }, intRdd) actual <- collect(filtered.rdd) expect_equal(actual, list(list(1L, -1))) filtered.rdd <- filterRDD(rdd, function(x) { x > 10 }) actual <- collect(filtered.rdd) expect_equal(actual, list()) }) test_that("lookup on RDD", { vals <- lookup(intRdd, 1L) expect_equal(vals, list(-1, 200)) vals <- lookup(intRdd, 3L) expect_equal(vals, list()) }) test_that("several transformations on RDD (a benchmark on PipelinedRDD)", { rdd2 <- rdd for (i in 1:12) rdd2 <- lapplyPartitionsWithIndex( rdd2, function(split, part) { part <- as.list(unlist(part) * split + i) }) rdd2 <- lapply(rdd2, function(x) x + x) actual <- collect(rdd2) expected <- list(24, 24, 24, 24, 24, 168, 170, 172, 174, 176) expect_equal(actual, expected) }) test_that("PipelinedRDD support actions: cache(), persist(), unpersist(), checkpoint()", { rdd2 <- rdd rdd2 <- lapplyPartitionsWithIndex( rdd2, function(split, part) { part <- as.list(unlist(part) * split) }) cache(rdd2) expect_true(rdd2@env$isCached) rdd2 <- lapply(rdd2, function(x) x) expect_false(rdd2@env$isCached) unpersist(rdd2) expect_false(rdd2@env$isCached) persist(rdd2, "MEMORY_AND_DISK") expect_true(rdd2@env$isCached) rdd2 <- lapply(rdd2, function(x) x) expect_false(rdd2@env$isCached) unpersist(rdd2) expect_false(rdd2@env$isCached) setCheckpointDir(sc, "checkpoints") checkpoint(rdd2) expect_true(rdd2@env$isCheckpointed) rdd2 <- lapply(rdd2, function(x) x) expect_false(rdd2@env$isCached) expect_false(rdd2@env$isCheckpointed) collect(rdd2) unlink("checkpoints") }) test_that("reduce on RDD", { sum <- reduce(rdd, "+") expect_equal(sum, 55) sumInline <- reduce(rdd, function(x, y) { x + y }) expect_equal(sumInline, 55) }) test_that("lapply with dependency", { fa <- 5 multiples <- lapply(rdd, function(x) { fa * x }) actual <- collect(multiples) expect_equal(actual, as.list(nums * 5)) }) test_that("lapplyPartitionsWithIndex on RDDs", { func <- function(splitIndex, part) { list(splitIndex, Reduce("+", part)) } actual <- collect(lapplyPartitionsWithIndex(rdd, func), flatten = FALSE) expect_equal(actual, list(list(0, 15), list(1, 40))) pairsRDD <- parallelize(sc, list(list(1, 2), list(3, 4), list(4, 8)), 1L) partitionByParity <- function(key) { if (key %% 2 == 1) 0 else 1 } mkTup <- function(splitIndex, part) { list(splitIndex, part) } actual <- collect(lapplyPartitionsWithIndex( partitionBy(pairsRDD, 2L, partitionByParity), mkTup), FALSE) expect_equal(actual, list(list(0, list(list(1, 2), list(3, 4))), list(1, list(list(4, 8))))) }) test_that("sampleRDD() on RDDs", { expect_equal(unlist(collect(sampleRDD(rdd, FALSE, 1.0, 2014L))), nums) }) test_that("takeSample() on RDDs", { data <- parallelize(sc, 1:100, 2L) for (seed in 4:5) { s <- takeSample(data, FALSE, 20L, seed) expect_equal(length(s), 20L) expect_equal(length(unique(s)), 20L) for (elem in s) { expect_true(elem >= 1 && elem <= 100) } } for (seed in 4:5) { s <- takeSample(data, FALSE, 200L, seed) expect_equal(length(s), 100L) expect_equal(length(unique(s)), 100L) for (elem in s) { expect_true(elem >= 1 && elem <= 100) } } for (seed in 4:5) { s <- takeSample(data, TRUE, 20L, seed) expect_equal(length(s), 20L) for (elem in s) { expect_true(elem >= 1 && elem <= 100) } } for (seed in 4:5) { s <- takeSample(data, TRUE, 100L, seed) expect_equal(length(s), 100L) expect_true(length(unique(s)) < 100L) } for (seed in 4:5) { s <- takeSample(data, TRUE, 200L, seed) expect_equal(length(s), 200L) expect_true(length(unique(s)) < 100L) } }) test_that("mapValues() on pairwise RDDs", { multiples <- mapValues(intRdd, function(x) { x * 2 }) actual <- collect(multiples) expected <- lapply(intPairs, function(x) { list(x[[1]], x[[2]] * 2) }) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) }) test_that("flatMapValues() on pairwise RDDs", { l <- parallelize(sc, list(list(1, c(1,2)), list(2, c(3,4)))) actual <- collect(flatMapValues(l, function(x) { x })) expect_equal(actual, list(list(1,1), list(1,2), list(2,3), list(2,4))) actual <- collect(flatMapValues(intRdd, function(x) { x:(x + 1) })) expect_equal(actual, list(list(1L, -1), list(1L, 0), list(2L, 100), list(2L, 101), list(2L, 1), list(2L, 2), list(1L, 200), list(1L, 201))) }) test_that("reduceByKeyLocally() on PairwiseRDDs", { pairs <- parallelize(sc, list(list(1, 2), list(1.1, 3), list(1, 4)), 2L) actual <- reduceByKeyLocally(pairs, "+") expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list(1, 6), list(1.1, 3)))) pairs <- parallelize(sc, list(list("abc", 1.2), list(1.1, 0), list("abc", 1.3), list("bb", 5)), 4L) actual <- reduceByKeyLocally(pairs, "+") expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list("abc", 2.5), list(1.1, 0), list("bb", 5)))) }) test_that("distinct() on RDDs", { nums.rep2 <- rep(1:10, 2) rdd.rep2 <- parallelize(sc, nums.rep2, 2L) uniques <- distinct(rdd.rep2) actual <- sort(unlist(collect(uniques))) expect_equal(actual, nums) }) test_that("maximum() on RDDs", { max <- maximum(rdd) expect_equal(max, 10) }) test_that("minimum() on RDDs", { min <- minimum(rdd) expect_equal(min, 1) }) test_that("sumRDD() on RDDs", { sum <- sumRDD(rdd) expect_equal(sum, 55) }) test_that("keyBy on RDDs", { func <- function(x) { x*x } keys <- keyBy(rdd, func) actual <- collect(keys) expect_equal(actual, lapply(nums, function(x) { list(func(x), x) })) }) test_that("repartition/coalesce on RDDs", { rdd <- parallelize(sc, 1:20, 4L) r1 <- repartition(rdd, 2) expect_equal(numPartitions(r1), 2L) count <- length(collectPartition(r1, 0L)) expect_true(count >= 8 && count <= 12) r2 <- repartition(rdd, 6) expect_equal(numPartitions(r2), 6L) count <- length(collectPartition(r2, 0L)) expect_true(count >=0 && count <= 4) r3 <- coalesce(rdd, 1) expect_equal(numPartitions(r3), 1L) count <- length(collectPartition(r3, 0L)) expect_equal(count, 20) }) test_that("sortBy() on RDDs", { sortedRdd <- sortBy(rdd, function(x) { x * x }, ascending = FALSE) actual <- collect(sortedRdd) expect_equal(actual, as.list(sort(nums, decreasing = TRUE))) rdd2 <- parallelize(sc, sort(nums, decreasing = TRUE), 2L) sortedRdd2 <- sortBy(rdd2, function(x) { x * x }) actual <- collect(sortedRdd2) expect_equal(actual, as.list(nums)) }) test_that("takeOrdered() on RDDs", { l <- list(10, 1, 2, 9, 3, 4, 5, 6, 7) rdd <- parallelize(sc, l) actual <- takeOrdered(rdd, 6L) expect_equal(actual, as.list(sort(unlist(l)))[1:6]) l <- list("e", "d", "c", "d", "a") rdd <- parallelize(sc, l) actual <- takeOrdered(rdd, 3L) expect_equal(actual, as.list(sort(unlist(l)))[1:3]) }) test_that("top() on RDDs", { l <- list(10, 1, 2, 9, 3, 4, 5, 6, 7) rdd <- parallelize(sc, l) actual <- top(rdd, 6L) expect_equal(actual, as.list(sort(unlist(l), decreasing = TRUE))[1:6]) l <- list("e", "d", "c", "d", "a") rdd <- parallelize(sc, l) actual <- top(rdd, 3L) expect_equal(actual, as.list(sort(unlist(l), decreasing = TRUE))[1:3]) }) test_that("fold() on RDDs", { actual <- fold(rdd, 0, "+") expect_equal(actual, Reduce("+", nums, 0)) rdd <- parallelize(sc, list()) actual <- fold(rdd, 0, "+") expect_equal(actual, 0) }) test_that("aggregateRDD() on RDDs", { rdd <- parallelize(sc, list(1, 2, 3, 4)) zeroValue <- list(0, 0) seqOp <- function(x, y) { list(x[[1]] + y, x[[2]] + 1) } combOp <- function(x, y) { list(x[[1]] + y[[1]], x[[2]] + y[[2]]) } actual <- aggregateRDD(rdd, zeroValue, seqOp, combOp) expect_equal(actual, list(10, 4)) rdd <- parallelize(sc, list()) actual <- aggregateRDD(rdd, zeroValue, seqOp, combOp) expect_equal(actual, list(0, 0)) }) test_that("zipWithUniqueId() on RDDs", { rdd <- parallelize(sc, list("a", "b", "c", "d", "e"), 3L) actual <- collect(zipWithUniqueId(rdd)) expected <- list(list("a", 0), list("b", 3), list("c", 1), list("d", 4), list("e", 2)) expect_equal(actual, expected) rdd <- parallelize(sc, list("a", "b", "c", "d", "e"), 1L) actual <- collect(zipWithUniqueId(rdd)) expected <- list(list("a", 0), list("b", 1), list("c", 2), list("d", 3), list("e", 4)) expect_equal(actual, expected) }) test_that("zipWithIndex() on RDDs", { rdd <- parallelize(sc, list("a", "b", "c", "d", "e"), 3L) actual <- collect(zipWithIndex(rdd)) expected <- list(list("a", 0), list("b", 1), list("c", 2), list("d", 3), list("e", 4)) expect_equal(actual, expected) rdd <- parallelize(sc, list("a", "b", "c", "d", "e"), 1L) actual <- collect(zipWithIndex(rdd)) expected <- list(list("a", 0), list("b", 1), list("c", 2), list("d", 3), list("e", 4)) expect_equal(actual, expected) }) test_that("glom() on RDD", { rdd <- parallelize(sc, as.list(1:4), 2L) actual <- collect(glom(rdd)) expect_equal(actual, list(list(1, 2), list(3, 4))) }) test_that("keys() on RDDs", { keys <- keys(intRdd) actual <- collect(keys) expect_equal(actual, lapply(intPairs, function(x) { x[[1]] })) }) test_that("values() on RDDs", { values <- values(intRdd) actual <- collect(values) expect_equal(actual, lapply(intPairs, function(x) { x[[2]] })) }) test_that("pipeRDD() on RDDs", { actual <- collect(pipeRDD(rdd, "more")) expected <- as.list(as.character(1:10)) expect_equal(actual, expected) trailed.rdd <- parallelize(sc, c("1", "", "2\n", "3\n\r\n")) actual <- collect(pipeRDD(trailed.rdd, "sort")) expected <- list("", "1", "2", "3") expect_equal(actual, expected) rev.nums <- 9:0 rev.rdd <- parallelize(sc, rev.nums, 2L) actual <- collect(pipeRDD(rev.rdd, "sort")) expected <- as.list(as.character(c(5:9, 0:4))) expect_equal(actual, expected) }) test_that("zipRDD() on RDDs", { rdd1 <- parallelize(sc, 0:4) rdd2 <- parallelize(sc, 1000:1004) actual <- collect(zipRDD(rdd1, rdd2)) expect_equal(actual, list(list(0, 1000), list(1, 1001), list(2, 1002), list(3, 1003), list(4, 1004))) mockFile = c("Spark is pretty.", "Spark is awesome.") fileName <- tempfile(pattern="spark-test", fileext=".tmp") writeLines(mockFile, fileName) rdd <- textFile(sc, fileName) actual <- collect(zipRDD(rdd, rdd)) expected <- lapply(mockFile, function(x) { list(x ,x) }) expect_equal(actual, expected) rdd1 <- parallelize(sc, 0:1) actual <- collect(zipRDD(rdd1, rdd)) expected <- lapply(0:1, function(x) { list(x, mockFile[x + 1]) }) expect_equal(actual, expected) rdd1 <- map(rdd, function(x) { x }) actual <- collect(zipRDD(rdd, rdd1)) expected <- lapply(mockFile, function(x) { list(x, x) }) expect_equal(actual, expected) unlink(fileName) }) test_that("cartesian() on RDDs", { rdd <- parallelize(sc, 1:3) actual <- collect(cartesian(rdd, rdd)) expect_equal(sortKeyValueList(actual), list( list(1, 1), list(1, 2), list(1, 3), list(2, 1), list(2, 2), list(2, 3), list(3, 1), list(3, 2), list(3, 3))) emptyRdd <- parallelize(sc, list()) actual <- collect(cartesian(rdd, emptyRdd)) expect_equal(actual, list()) mockFile = c("Spark is pretty.", "Spark is awesome.") fileName <- tempfile(pattern="spark-test", fileext=".tmp") writeLines(mockFile, fileName) rdd <- textFile(sc, fileName) actual <- collect(cartesian(rdd, rdd)) expected <- list( list("Spark is awesome.", "Spark is pretty."), list("Spark is awesome.", "Spark is awesome."), list("Spark is pretty.", "Spark is pretty."), list("Spark is pretty.", "Spark is awesome.")) expect_equal(sortKeyValueList(actual), expected) rdd1 <- parallelize(sc, 0:1) actual <- collect(cartesian(rdd1, rdd)) expect_equal(sortKeyValueList(actual), list( list(0, "Spark is pretty."), list(0, "Spark is awesome."), list(1, "Spark is pretty."), list(1, "Spark is awesome."))) rdd1 <- map(rdd, function(x) { x }) actual <- collect(cartesian(rdd, rdd1)) expect_equal(sortKeyValueList(actual), expected) unlink(fileName) }) test_that("subtract() on RDDs", { l <- list(1, 1, 2, 2, 3, 4) rdd1 <- parallelize(sc, l) actual <- collect(subtract(rdd1, rdd1)) expect_equal(actual, list()) rdd2 <- parallelize(sc, list()) actual <- collect(subtract(rdd1, rdd2)) expect_equal(as.list(sort(as.vector(actual, mode="integer"))), l) rdd2 <- parallelize(sc, list(2, 4)) actual <- collect(subtract(rdd1, rdd2)) expect_equal(as.list(sort(as.vector(actual, mode="integer"))), list(1, 1, 3)) l <- list("a", "a", "b", "b", "c", "d") rdd1 <- parallelize(sc, l) rdd2 <- parallelize(sc, list("b", "d")) actual <- collect(subtract(rdd1, rdd2)) expect_equal(as.list(sort(as.vector(actual, mode="character"))), list("a", "a", "c")) }) test_that("subtractByKey() on pairwise RDDs", { l <- list(list("a", 1), list("b", 4), list("b", 5), list("a", 2)) rdd1 <- parallelize(sc, l) actual <- collect(subtractByKey(rdd1, rdd1)) expect_equal(actual, list()) rdd2 <- parallelize(sc, list()) actual <- collect(subtractByKey(rdd1, rdd2)) expect_equal(sortKeyValueList(actual), sortKeyValueList(l)) rdd2 <- parallelize(sc, list(list("a", 3), list("c", 1))) actual <- collect(subtractByKey(rdd1, rdd2)) expect_equal(actual, list(list("b", 4), list("b", 5))) l <- list(list(1, 1), list(2, 4), list(2, 5), list(1, 2)) rdd1 <- parallelize(sc, l) rdd2 <- parallelize(sc, list(list(1, 3), list(3, 1))) actual <- collect(subtractByKey(rdd1, rdd2)) expect_equal(actual, list(list(2, 4), list(2, 5))) }) test_that("intersection() on RDDs", { actual <- collect(intersection(rdd, rdd)) expect_equal(sort(as.integer(actual)), nums) emptyRdd <- parallelize(sc, list()) actual <- collect(intersection(rdd, emptyRdd)) expect_equal(actual, list()) rdd1 <- parallelize(sc, list(1, 10, 2, 3, 4, 5)) rdd2 <- parallelize(sc, list(1, 6, 2, 3, 7, 8)) actual <- collect(intersection(rdd1, rdd2)) expect_equal(sort(as.integer(actual)), 1:3) }) test_that("join() on pairwise RDDs", { rdd1 <- parallelize(sc, list(list(1,1), list(2,4))) rdd2 <- parallelize(sc, list(list(1,2), list(1,3))) actual <- collect(join(rdd1, rdd2, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list(1, list(1, 2)), list(1, list(1, 3))))) rdd1 <- parallelize(sc, list(list("a",1), list("b",4))) rdd2 <- parallelize(sc, list(list("a",2), list("a",3))) actual <- collect(join(rdd1, rdd2, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list("a", list(1, 2)), list("a", list(1, 3))))) rdd1 <- parallelize(sc, list(list(1,1), list(2,2))) rdd2 <- parallelize(sc, list(list(3,3), list(4,4))) actual <- collect(join(rdd1, rdd2, 2L)) expect_equal(actual, list()) rdd1 <- parallelize(sc, list(list("a",1), list("b",2))) rdd2 <- parallelize(sc, list(list("c",3), list("d",4))) actual <- collect(join(rdd1, rdd2, 2L)) expect_equal(actual, list()) }) test_that("leftOuterJoin() on pairwise RDDs", { rdd1 <- parallelize(sc, list(list(1,1), list(2,4))) rdd2 <- parallelize(sc, list(list(1,2), list(1,3))) actual <- collect(leftOuterJoin(rdd1, rdd2, 2L)) expected <- list(list(1, list(1, 2)), list(1, list(1, 3)), list(2, list(4, NULL))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list("a",1), list("b",4))) rdd2 <- parallelize(sc, list(list("a",2), list("a",3))) actual <- collect(leftOuterJoin(rdd1, rdd2, 2L)) expected <- list(list("b", list(4, NULL)), list("a", list(1, 2)), list("a", list(1, 3))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list(1,1), list(2,2))) rdd2 <- parallelize(sc, list(list(3,3), list(4,4))) actual <- collect(leftOuterJoin(rdd1, rdd2, 2L)) expected <- list(list(1, list(1, NULL)), list(2, list(2, NULL))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list("a",1), list("b",2))) rdd2 <- parallelize(sc, list(list("c",3), list("d",4))) actual <- collect(leftOuterJoin(rdd1, rdd2, 2L)) expected <- list(list("b", list(2, NULL)), list("a", list(1, NULL))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) }) test_that("rightOuterJoin() on pairwise RDDs", { rdd1 <- parallelize(sc, list(list(1,2), list(1,3))) rdd2 <- parallelize(sc, list(list(1,1), list(2,4))) actual <- collect(rightOuterJoin(rdd1, rdd2, 2L)) expected <- list(list(1, list(2, 1)), list(1, list(3, 1)), list(2, list(NULL, 4))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list("a",2), list("a",3))) rdd2 <- parallelize(sc, list(list("a",1), list("b",4))) actual <- collect(rightOuterJoin(rdd1, rdd2, 2L)) expected <- list(list("b", list(NULL, 4)), list("a", list(2, 1)), list("a", list(3, 1))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list(1,1), list(2,2))) rdd2 <- parallelize(sc, list(list(3,3), list(4,4))) actual <- collect(rightOuterJoin(rdd1, rdd2, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list(3, list(NULL, 3)), list(4, list(NULL, 4))))) rdd1 <- parallelize(sc, list(list("a",1), list("b",2))) rdd2 <- parallelize(sc, list(list("c",3), list("d",4))) actual <- collect(rightOuterJoin(rdd1, rdd2, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list("d", list(NULL, 4)), list("c", list(NULL, 3))))) }) test_that("fullOuterJoin() on pairwise RDDs", { rdd1 <- parallelize(sc, list(list(1,2), list(1,3), list(3,3))) rdd2 <- parallelize(sc, list(list(1,1), list(2,4))) actual <- collect(fullOuterJoin(rdd1, rdd2, 2L)) expected <- list(list(1, list(2, 1)), list(1, list(3, 1)), list(2, list(NULL, 4)), list(3, list(3, NULL))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list("a",2), list("a",3), list("c", 1))) rdd2 <- parallelize(sc, list(list("a",1), list("b",4))) actual <- collect(fullOuterJoin(rdd1, rdd2, 2L)) expected <- list(list("b", list(NULL, 4)), list("a", list(2, 1)), list("a", list(3, 1)), list("c", list(1, NULL))) expect_equal(sortKeyValueList(actual), sortKeyValueList(expected)) rdd1 <- parallelize(sc, list(list(1,1), list(2,2))) rdd2 <- parallelize(sc, list(list(3,3), list(4,4))) actual <- collect(fullOuterJoin(rdd1, rdd2, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list(1, list(1, NULL)), list(2, list(2, NULL)), list(3, list(NULL, 3)), list(4, list(NULL, 4))))) rdd1 <- parallelize(sc, list(list("a",1), list("b",2))) rdd2 <- parallelize(sc, list(list("c",3), list("d",4))) actual <- collect(fullOuterJoin(rdd1, rdd2, 2L)) expect_equal(sortKeyValueList(actual), sortKeyValueList(list(list("a", list(1, NULL)), list("b", list(2, NULL)), list("d", list(NULL, 4)), list("c", list(NULL, 3))))) }) test_that("sortByKey() on pairwise RDDs", { numPairsRdd <- map(rdd, function(x) { list (x, x) }) sortedRdd <- sortByKey(numPairsRdd, ascending = FALSE) actual <- collect(sortedRdd) numPairs <- lapply(nums, function(x) { list (x, x) }) expect_equal(actual, sortKeyValueList(numPairs, decreasing = TRUE)) rdd2 <- parallelize(sc, sort(nums, decreasing = TRUE), 2L) numPairsRdd2 <- map(rdd2, function(x) { list (x, x) }) sortedRdd2 <- sortByKey(numPairsRdd2) actual <- collect(sortedRdd2) expect_equal(actual, numPairs) l <- list(list("a", 1), list("b", 2), list("1", 3), list("d", 4), list("2", 5)) rdd3 <- parallelize(sc, l, 2L) sortedRdd3 <- sortByKey(rdd3) actual <- collect(sortedRdd3) expect_equal(actual, list(list("1", 3), list("2", 5), list("a", 1), list("b", 2), list("d", 4))) rdd4 <- parallelize(sc, l, 1L) sortedRdd4 <- sortByKey(rdd4) actual <- collect(sortedRdd4) expect_equal(actual, list(list("1", 3), list("2", 5), list("a", 1), list("b", 2), list("d", 4))) rdd5 <- parallelize(sc, l, 2L) sortedRdd5 <- sortByKey(rdd5, numPartitions = 1L) actual <- collect(sortedRdd5) expect_equal(actual, list(list("1", 3), list("2", 5), list("a", 1), list("b", 2), list("d", 4))) l2 <- list(list("a", 1)) rdd6 <- parallelize(sc, l2, 2L) sortedRdd6 <- sortByKey(rdd6) actual <- collect(sortedRdd6) expect_equal(actual, l2) l3 <- list() rdd7 <- parallelize(sc, l3, 2L) sortedRdd7 <- sortByKey(rdd7) actual <- collect(sortedRdd7) expect_equal(actual, l3) }) test_that("collectAsMap() on a pairwise RDD", { rdd <- parallelize(sc, list(list(1, 2), list(3, 4))) vals <- collectAsMap(rdd) expect_equal(vals, list(`1` = 2, `3` = 4)) rdd <- parallelize(sc, list(list("a", 1), list("b", 2))) vals <- collectAsMap(rdd) expect_equal(vals, list(a = 1, b = 2)) rdd <- parallelize(sc, list(list(1.1, 2.2), list(1.2, 2.4))) vals <- collectAsMap(rdd) expect_equal(vals, list(`1.1` = 2.2, `1.2` = 2.4)) rdd <- parallelize(sc, list(list(1, "a"), list(2, "b"))) vals <- collectAsMap(rdd) expect_equal(vals, list(`1` = "a", `2` = "b")) }) test_that("sampleByKey() on pairwise RDDs", { rdd <- parallelize(sc, 1:2000) pairsRDD <- lapply(rdd, function(x) { if (x %% 2 == 0) list("a", x) else list("b", x) }) fractions <- list(a = 0.2, b = 0.1) sample <- sampleByKey(pairsRDD, FALSE, fractions, 1618L) expect_equal(100 < length(lookup(sample, "a")) && 300 > length(lookup(sample, "a")), TRUE) expect_equal(50 < length(lookup(sample, "b")) && 150 > length(lookup(sample, "b")), TRUE) expect_equal(lookup(sample, "a")[which.min(lookup(sample, "a"))] >= 0, TRUE) expect_equal(lookup(sample, "a")[which.max(lookup(sample, "a"))] <= 2000, TRUE) expect_equal(lookup(sample, "b")[which.min(lookup(sample, "b"))] >= 0, TRUE) expect_equal(lookup(sample, "b")[which.max(lookup(sample, "b"))] <= 2000, TRUE) rdd <- parallelize(sc, 1:2000) pairsRDD <- lapply(rdd, function(x) { if (x %% 2 == 0) list(2, x) else list(3, x) }) fractions <- list(`2` = 0.2, `3` = 0.1) sample <- sampleByKey(pairsRDD, TRUE, fractions, 1618L) expect_equal(100 < length(lookup(sample, 2)) && 300 > length(lookup(sample, 2)), TRUE) expect_equal(50 < length(lookup(sample, 3)) && 150 > length(lookup(sample, 3)), TRUE) expect_equal(lookup(sample, 2)[which.min(lookup(sample, 2))] >= 0, TRUE) expect_equal(lookup(sample, 2)[which.max(lookup(sample, 2))] <= 2000, TRUE) expect_equal(lookup(sample, 3)[which.min(lookup(sample, 3))] >= 0, TRUE) expect_equal(lookup(sample, 3)[which.max(lookup(sample, 3))] <= 2000, TRUE) })
getProducts = function(value, position = NULL){ values.list = value[[1]] is.factor = value[[2]] n = length(values.list) result = 1 results = c() for(i in 1:n){ variable = values.list[[i]] if(is.factor[i]){ variable.length = length(variable[,1]) }else{ variable.length = length(variable) } if(!is.null(position) && i == position && !is.factor[i]){ result = result * (variable.length-1) }else if(!is.null(position) && i == position & is.factor[i]){ gauss = (variable.length)*(variable.length-1)/2 result = result * gauss } else{ result = result * variable.length } results = c(results,result) } return(results) }
formulaUnimva <- function( formula, var.subset, split.x=FALSE, intercept=0, allow.noresp=FALSE ){ if(intercept==0){ formula <- update(formula, ~ . + 0) } else { formula <- update(formula, ~ . + 1) } if(split.x){ foo.new <- extend.x.formula(formula, return.interaction=FALSE, extend.term=TRUE) } else foo.new <- formula terms.foo <- terms(foo.new) term.labels <- attr(terms.foo,"term.labels") formulasUni.mvad <- list() resp <- attr(terms.foo,"response") if(resp==1) { respname <- foo.new[[2]] datay <- eval(respname) respname <- deparse(respname, width.cutoff =500) } else { if(!allow.noresp) stop("no formulaUnimva's can be build: formula has no response") formulasUni.mvad[[1]] <- foo.new return(formulasUni.mvad) } labelsyp <- labels(datay)[[2]] p <- NCOL(datay) if(p==0) stop("no formulaUnimva's can be build: formula has no response") if(missing(var.subset)) { var.subset <- 1:p } else { if(is.logical(var.subset) & any(!is.na(var.subset))) var.subset <- which(var.subset[!is.na(var.subset)]) if((max (var.subset)>p) | (p<1)) stop("'var.subset' is not valid") } if(p > 1) { j=1 for (i in var.subset){ tmp <- paste("(",respname,")[,",i,"]", sep="") fooi <- as.formula(paste(tmp,'~',c(terms.foo[[3]]))) if(intercept==0) { formulasUni.mvad[[j]] <- update(fooi, ~ . + 0) } else { formulasUni.mvad[[j]] <- update(fooi, ~ . + 1) } j=1+j } } else formulasUni.mvad[[1]] <- foo.new names(formulasUni.mvad)<- labelsyp[var.subset] class(formulasUni.mvad) <- c("formulaUnimva", "list") return( formulasUni.mvad) } is.formulaUnimva <- function(x) { inherits(x, "formulaUnimva") } setMethod("show", "formulaUnimva", function(object) { obj<-object@g show(obj) })
gf_point(distance ~ stretch, data = elasticband) %>% gf_lm() %>% gf_ribbon(lwr + upr ~ stretch, fill = "skyblue", data = cbind(elasticband, predict(eband.model, interval = "prediction"))) %>% gf_ribbon(lwr + upr ~ stretch, data = cbind(elasticband, predict(eband.model, interval = "confidence"))) gf_point(distance ~ stretch, data = elasticband) %>% gf_lm(interval = "prediction", fill = "skyblue") %>% gf_lm(interval = "confidence")
`SIRbd` <- function (t, y, p) { S <- y[1] I <- y[2] R <- y[3] with(as.list(p), { dS.dt <- b * (S + I + R) - B * I * S - m * S dI.dt <- B * I * S - g * I - m * I dR.dt <- g * I - m * R return(list(c(dS.dt, dI.dt, dR.dt))) }) }
library(EnvStats) stats <- summaryStats(Iron.ppm ~ Well, data = EPA.09.Ex.13.1.iron.df, combine.groups = FALSE, digits = 2, stats.in.rows = TRUE) stats windows() boxplot(Iron.ppm ~ Well, data = EPA.09.Ex.13.1.iron.df, ylim = c(0, 250), ylab = "Iron (ppm)", main = "Figure 13-1. Side-by-Side Iron Boxplots") points(1:ncol(stats), stats["Mean", ], pch = 5) windows() stripChart(Iron.ppm ~ Well, data = EPA.09.Ex.13.1.iron.df, show.ci = F, location.scale.text.cex = 0.7, ylim = c(0, 250), ylab = "Iron (ppm)") mtext("Alternative Figure 13-1. Side-by-Side Iron Strip Plots", cex = 1.25, font = 2, line = 2.5) windows() stripChart(Iron.ppm ~ Well, data = EPA.09.Ex.13.1.iron.df, location.scale.text.cex = 0.7, ylim = c(0, 300), ylab = "Iron (ppm)") mtext(paste("Alternative Figure 13-1. Side-by-Side Iron Strip Plots", "with 95% Confidence Intervals", sep = "\n"), cex = 1.25, font = 2, line = 1.75) stats <- summaryStats(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df, combine.groups = F, digits = 2, stats.in.rows = TRUE) stats windows() boxplot(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df, ylim = c(3, 6), ylab = "Log Iron log(ppm)", main = "Figure 13-2. Side-by-Side Log(Iron) Boxplots") points(1:ncol(stats), stats["Mean",], pch = 5) windows() stripChart(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df, show.ci = F, location.scale.text.cex = 0.7, ylim = c(3, 6), ylab = "Log Iron log(ppm)") mtext("Alternative Figure 13-2. Side-by-Side Log(Iron) Strip Plots", cex = 1.15, font = 2, line = 2.5) windows() stripChart(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df, location.scale.text.cex = 0.7, ylim = c(3, 6), ylab = "Log(Iron) log(ppm)") mtext(paste("Alternative Figure 13-2. Side-by-Side Log(Iron) Strip Plots", "with 95% Confidence Intervals", sep = "\n"), line = 1.75, cex = 1.15, font = 2) rm(stats) stats <- summaryStats(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df, digits = 3, combine.groups = TRUE, stats.in.rows = TRUE) stats fit <- aov(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df) anova(fit) rm(fit, stats) stats <- summaryStats(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df, combine.groups = F, digits = 3, stats.in.rows = TRUE) UPLs <- sapply( with(EPA.09.Ex.13.1.iron.df, split(Iron.ppm, Well)), function(x, pi.type, conf.level) { predIntLnorm(x, pi.type = "upper", conf.level = 0.99)$interval$limits["UPL"] }) rbind(stats[c("Mean", "SD", "N"), ], "99% PL" = round(UPLs, 1)) fit <- aov(log(Iron.ppm) ~ Well, data = EPA.09.Ex.13.1.iron.df) anova.fit <- anova(fit) anova.fit RMSE <- anova.fit["Residuals", "Mean Sq"] Df <- anova.fit["Residuals", "Df"] t.crit <- qt(0.99, df = Df) UPLs <- sapply( with(EPA.09.Ex.13.1.iron.df, split(log(Iron.ppm), Well)), function(x, t.crit, RMSE) { exp(mean(x) + t.crit * sqrt(RMSE * (1 + 1/length(x)))) }, t.crit = t.crit, RMSE = RMSE) rbind(stats[c("Mean", "SD", "N"), ], "99% PL" = round(UPLs, 1)) rm(stats, UPLs, fit, anova.fit, RMSE, Df, t.crit)
chart_PerfSummary <- function(ret = ret, geometric = TRUE, main = "Cumulative Returns and Drawdowns", linesize = 1.25) { ret <- xts::xts(ret[, -1], order.by = ret[, 1]) if (geometric == TRUE) { cumret <- cumprod(ret + 1) } else { cumret <- cumsum(ret) } Drawdowns <- PerformanceAnalytics::Drawdowns(ret, geometric) cumret <- dplyr::as_tibble(cumret) %>% dplyr::mutate(date = zoo::index(cumret)) %>% tidyr::gather(series, value, -date) cumret$variable <- "CumRet" drawd <- dplyr::as_tibble(Drawdowns) %>% dplyr::mutate(date = zoo::index(Drawdowns)) %>% tidyr::gather(series, value, -date) drawd$variable <- "Dranwdowns" df <- rbind(drawd, cumret) df %>% ggplot2::ggplot(ggplot2::aes(x = date, y = value, color = series)) + ggplot2::facet_grid(variable ~ ., scales = "free", space = "free") + ggplot2::geom_line() + ggplot2::ggtitle(main) + ggplot2::xlab("") + ggplot2::ylab("") }
runChain = function(chainNumber, variables, data, specs, options, chain, message){ temp = lapply(X = variables, FUN = function(x) {x$loadPointers(); return(NULL)}) temp = lapply(X = variables, FUN = function(x) {x$initializeParameters(); return(NULL)}) data = initUnits(data = data, variables = variables, specs = specs) totalIter = (chainNumber-1)*specs$iterationsPerChain lastIterNum = 0 iter = 1 for (iter in 1:(options$nBurnin+options$nSampled*options$nThin)){ totalIter = totalIter+1 if (iter %% options$nThin == 0 & iter > options$nBurnin){ lastIterNum = lastIterNum+1 iterNum = lastIterNum } else { iterNum = NA } eval(message) data = sampleUnits(data = data, variables = variables, specs = specs) temp = lapply(X = variables, FUN = function(x, data) {x$sampleParameters(data = data); return(NULL)}, data = data) if (!is.na(iterNum)) { chain[iterNum,] = unlist(lapply(X = specs$parameters$paramLocation, FUN = function(x){return(eval(parse(text=x)))})) } } cat("\r") return(chain) }
id.garch <- function(x, max.iter = 5, crit = 0.001, restriction_matrix = NULL, start_iter = 50){ u <- Tob <- p <- k <- residY <- coef_x <- yOut <- type <- y <- A_hat <- NULL get_var_objects(x) if(inherits(x,"varest")){ if(!is.null(x$restrictions)){ stop("id.garch currently supports identification of unrestricted VARs only. Consider using id.dc, id.cvm or id.chol instead.") } } restriction_matrix = get_restriction_matrix(restriction_matrix, k) restrictions <- length(restriction_matrix[!is.na(restriction_matrix)]) sigg <- crossprod(u)/(Tob - 1 - k * p) eigVectors <- eigen(sigg)$vectors eigValues <- diag(eigen(sigg)$values) eigVectors <- eigVectors[,rev(1:ncol(eigVectors))] eigValues <- diag(rev(eigen(sigg)$values)) CC <- eigVectors %*% sqrt(eigValues) %*% t(eigVectors) B0 <- solve(solve(sqrt(eigValues)) %*% t(eigVectors)) ste <- solve(sqrt(eigValues)) %*% t(eigVectors) %*% t(u) parameter_consider <- GarchStart(k, ste, Tob, start_iter) parameter_ini_univ <- parameter_consider[[which.min(sapply(parameter_consider, '[[', 'Likelihoods'))]]$ParameterE Sigma_e_univ <- parameter_consider[[which.min(sapply(parameter_consider, '[[', 'Likelihoods'))]]$ConVariance if(restrictions > 0){ resultUnrestricted <- identifyGARCH(B0 = B0, k = k, Tob = Tob, restriction_matrix = NULL, Sigma_e_univ = Sigma_e_univ, coef_x = coef_x, x = x, parameter_ini_univ = parameter_ini_univ, max.iter = max.iter, crit = crit, u = u, p = p, yOut = yOut, type = type) result <- identifyGARCH(B0 = B0, k = k, Tob = Tob, restriction_matrix = restriction_matrix, Sigma_e_univ = Sigma_e_univ, coef_x = coef_x, x = x, parameter_ini_univ = parameter_ini_univ, max.iter = max.iter, crit = crit, u = u, p = p, yOut = yOut, type = type) lRatioTestStatistic = 2 * (resultUnrestricted$Lik - result$Lik) pValue = round(1 - pchisq(lRatioTestStatistic, result$restrictions), 4) lRatioTest <- data.frame(testStatistic = lRatioTestStatistic, p.value = pValue) rownames(lRatioTest) <- "" colnames(lRatioTest) <- c("Test statistic", "p-value") result$lRatioTest <- lRatioTest }else{ restriction_matrix <- NULL result <- identifyGARCH(B0 = B0, k = k, Tob = Tob, restriction_matrix = restriction_matrix, Sigma_e_univ = Sigma_e_univ, coef_x = coef_x, x = x, parameter_ini_univ = parameter_ini_univ, max.iter = max.iter, crit = crit, u = u, p = p, yOut = yOut, type = type) } if (type == 'const' | type == 'trend') { result$AIC <- (-2) * result$Lik + 2*(k + p * k^2 + 2*k + k^2) } else if (type == 'none') { result$AIC <- (-2) * result$Lik + 2*(p * k^2 + 2*k + k^2) } else if (type == 'both') { result$AIC <- (-2) * result$Lik + 2*(2*k + p * k^2 + 2*k + k^2) } result$VAR <- x result$CC <- CC result$I_test <- garch_ident_test(result) class(result) <- "svars" return(result) }
Inv_sinh_CI_OR_2x2 <- function(n, alpha=0.05, printresults=TRUE) { estimate <- n[1, 1] * n[2, 2] / (n[1, 2] * n[2, 1]) z <- qnorm(1-alpha / 2, 0, 1) tmp <- asinh(0.5 * z*sqrt(1 / n[1, 1] + 1 / n[1, 2] + 1 / n[2, 1] + 1 / n[2, 2])) L <- exp(log(estimate) - 2 * tmp) U <- exp(log(estimate) + 2 * tmp) if (n[1, 1] == 0) {U = (z ^ 2) * n[2, 2] / (n[1, 2] * n[2, 1])} if (n[2, 2] == 0) {U = n[1, 1] * (z ^ 2) / (n[1, 2] * n[2, 1])} if (n[1, 1] == 0 && n[2, 2] == 0) { U = ((z ^ 2) * (z ^ 2)) / (n[1, 2] * n[2, 1]) } if (n[1, 2] == 0) {L = n[1, 1] * n[2, 2] / ((z ^ 2) * n[2, 1])} if (n[2, 1] == 0) {L = n[1, 1] * n[2, 2] / (n[1, 2] * (z ^ 2))} if (n[1, 2] == 0 && n[2, 1] == 0) { L = n[1, 1] * n[2, 2] / ((z ^ 2) * (z ^ 2)) } if (printresults) { print( sprintf( 'The inverse sinh CI: estimate = %6.4f (%g%% CI %6.4f to %6.4f)', estimate, 100 * (1 - alpha), L, U ), quote=FALSE ) } res <- data.frame(lower=L, upper=U, estimate=estimate) invisible(res) }
plot_DetPlot <- function( object, signal.integral.min, signal.integral.max, background.integral.min, background.integral.max, method = "shift", signal_integral.seq = NULL, analyse_function = "analyse_SAR.CWOSL", analyse_function.control = list(), n.channels = NULL, show_ShineDownCurve = TRUE, respect_RC.Status = FALSE, verbose = TRUE, ... ) { object.structure <- structure_RLum(object) if(is.null(n.channels)){ n.channels <- ceiling( (background.integral.min - 1 - signal.integral.max) / (signal.integral.max - signal.integral.min) ) } analyse_function.settings <- list( sequence.structure = c("TL", "IR50", "pIRIR225"), dose.points = NULL, mtext.outer = "", fit.method = "EXP", fit.force_through_origin = FALSE, plot = FALSE, plot.single = FALSE ) analyse_function.settings <- modifyList(analyse_function.settings, analyse_function.control) if (is.null(signal_integral.seq)) { if(signal.integral.min == signal.integral.max){ signal_integral.seq <- signal.integral.min:(background.integral.min - 1) }else{ signal_integral.seq <- seq(signal.integral.min, background.integral.min - 1, by = signal.integral.max - signal.integral.min) } } if(analyse_function == "analyse_SAR.CWOSL"){ results <- merge_RLum(lapply(1:n.channels, function(x){ analyse_SAR.CWOSL( object = object, signal.integral.min = if(method == "shift"){signal_integral.seq[x]}else{signal_integral.seq[1]}, signal.integral.max = signal_integral.seq[x+1], background.integral.min = background.integral.min, background.integral.max = background.integral.max, dose.points = analyse_function.settings$dose.points, mtext.outer = analyse_function.settings$mtext.outer, fit.force_through_origin = analyse_function.settings$fit.force_through_origin, fit.method = analyse_function.settings$fit.method, plot = analyse_function.settings$plot, plot.single = analyse_function.settings$plot.single, verbose = verbose ) })) } else if(analyse_function == "analyse_pIRIRSequence"){ results <- merge_RLum(lapply(1:n.channels, function(x){ analyse_pIRIRSequence( object = object, signal.integral.min = if(method == "shift"){signal_integral.seq[x]}else{signal_integral.seq[1]}, signal.integral.max = signal_integral.seq[x+1], background.integral.min = background.integral.min, background.integral.max = background.integral.max, dose.points = analyse_function.settings$dose.points, mtext.outer = analyse_function.settings$mtext.outer, plot = analyse_function.settings$plot, plot.single = analyse_function.settings$plot.single, sequence.structure = analyse_function.settings$sequence.structure, verbose = verbose ) })) } else{ stop("[plot_DetPlot()] 'analyse_function' unknown!", call. = FALSE) } if(analyse_function == "analyse_pIRIRSequence"){ pIRIR_signals <- unique(get_RLum(results)$Signal) }else{ pIRIR_signals <- NA } df_final <- lapply(1:length(pIRIR_signals), function(i){ df <- get_RLum(results) if(!is.na(pIRIR_signals[1])){ df <- df[df$Signal == pIRIR_signals[i],] } OSL_curve <- as(get_RLum(object, recordType = "SL")[[i]], "matrix") OSL_curve <- OSL_curve[1:signal_integral.seq[n.channels + 1],] m <- ((min(df$De - df$De.Error, na.rm = TRUE)) - (max(df$De, na.rm = TRUE) + max(df$De.Error, na.rm = TRUE))) / (min(OSL_curve[, 2], na.rm = TRUE) - max(OSL_curve[, 2], na.rm = TRUE)) n <- (max(df$De, na.rm = TRUE) + max(df$De.Error, na.rm = TRUE)) - m * max(OSL_curve[, 2]) OSL_curve[, 2] <- m * OSL_curve[, 2] + n rm(n, m) plot.settings <- list( ylim = c(min(df$De - df$De.Error, na.rm = TRUE), (max(df$De, na.rm = TRUE) + max(df$De.Error, na.rm = TRUE))), xlim = c(min(OSL_curve[, 1]), max(OSL_curve[, 1])), ylab = expression(paste(D[e] / s, " and ", L[n]/(a.u.))), xlab = "Stimulation time [s]", main = "De(t) plot", pch = 1, mtext = ifelse(is.na(pIRIR_signals[1]), "", paste0("Signal: ",pIRIR_signals[i])), cex = 1, legend = TRUE, legend.text = c(expression(L[n]-signal), expression(D[e])), legend.pos = "bottomleft" ) plot.settings <- modifyList(plot.settings, list(...)) par(cex = plot.settings$cex) plot( NA, NA, xlim = plot.settings$xlim, ylim = plot.settings$ylim, xlab = plot.settings$xlab, ylab = plot.settings$ylab, main = plot.settings$main ) if (show_ShineDownCurve) { lines(OSL_curve, type = "b", pch = 20) } df_x <- OSL_curve[seq(signal.integral.max, signal_integral.seq[n.channels+1], length.out = nrow(df)),1] df_final <- cbind(df, df_x) if (respect_RC.Status) { df_final <- df_final[df_final$RC.Status != "FAILED", ] } points(df_final[, c("df_x", "De")], pch = plot.settings$pch) segments( x0 = df_final$df_x, y0 = df_final$De + df_final$De.Error, x1 = df_final$df_x, y1 = df_final$De - df_final$De.Error ) mtext(side = 3, plot.settings$mtext) if(plot.settings$legend){ legend( plot.settings$legend.pos, legend = plot.settings$legend.text, pch = c(plot.settings$pch, 20), bty = "n" ) } return(df_final) }) return(set_RLum( class = "RLum.Results", data = list( De.values = as.data.frame(data.table::rbindlist(df_final)), signal_integral.seq = signal_integral.seq ), info = list(call = sys.call()) )) }
mr_scatter_plot <- function(mr_results, dat) { requireNamespace("ggplot2", quietly=TRUE) requireNamespace("plyr", quietly=TRUE) mrres <- plyr::dlply(dat, c("id.exposure", "id.outcome"), function(d) { d <- plyr::mutate(d) if(nrow(d) < 2 | sum(d$mr_keep) == 0) { return(blank_plot("Insufficient number of SNPs")) } d <- subset(d, mr_keep) index <- d$beta.exposure < 0 d$beta.exposure[index] <- d$beta.exposure[index] * -1 d$beta.outcome[index] <- d$beta.outcome[index] * -1 mrres <- subset(mr_results, id.exposure == d$id.exposure[1] & id.outcome == d$id.outcome[1]) mrres$a <- 0 if("MR Egger" %in% mrres$method) { temp <- mr_egger_regression(d$beta.exposure, d$beta.outcome, d$se.exposure, d$se.outcome, default_parameters()) mrres$a[mrres$method == "MR Egger"] <- temp$b_i } if("MR Egger (bootstrap)" %in% mrres$method) { temp <- mr_egger_regression_bootstrap(d$beta.exposure, d$beta.outcome, d$se.exposure, d$se.outcome, default_parameters()) mrres$a[mrres$method == "MR Egger (bootstrap)"] <- temp$b_i } ggplot2::ggplot(data=d, ggplot2::aes(x=beta.exposure, y=beta.outcome)) + ggplot2::geom_errorbar(ggplot2::aes(ymin=beta.outcome-se.outcome, ymax=beta.outcome+se.outcome), colour="grey", width=0) + ggplot2::geom_errorbarh(ggplot2::aes(xmin=beta.exposure-se.exposure, xmax=beta.exposure+se.exposure), colour="grey", height=0) + ggplot2::geom_point() + ggplot2::geom_abline(data=mrres, ggplot2::aes(intercept=a, slope=b, colour=method), show.legend=TRUE) + ggplot2::scale_colour_manual(values=c(" ggplot2::labs(colour="MR Test", x=paste("SNP effect on", d$exposure[1]), y=paste("SNP effect on", d$outcome[1])) + ggplot2::theme(legend.position="top", legend.direction="vertical") + ggplot2::guides(colour=ggplot2::guide_legend(ncol=2)) }) mrres } blank_plot <- function(message) { requireNamespace("ggplot2", quietly=TRUE) ggplot2::ggplot(data.frame(a=0,b=0,n=message)) + ggplot2::geom_text(ggplot2::aes(x=a,y=b,label=n)) + ggplot2::labs(x=NULL,y=NULL) + ggplot2::theme(axis.text=ggplot2::element_blank(), axis.ticks=ggplot2::element_blank()) }
had_miyamoto<-function(n){ p<-n/4 m<- (p-1)/2 A<-miyamotoC(n) if(is.null(A)){ return(NULL) } C1<- -A[2:(m+1),2:(m+1)] C2<- A[2:(m+1),(m+2):p] C2t<- C2 C4<- A[(m+2):p,(m+2):p] K<-Hadamard_Matrix(p-1) if(is.matrix(K)==F){ return(NULL) } K1<- K[1:((p-1)/2),1:((p-1)/2)] K2<- K[1:((p-1)/2),(((p-1)/2)+1):(p-1)] K3<- -K[(((p-1)/2)+1):(p-1), 1:((p-1)/2)] K4<- K[(((p-1)/2)+1):(p-1), (((p-1)/2)+1):(p-1)] zero <-matrix(rep(0,m*m),nrow=m,ncol=m) u1<- cbind(C1,C2,zero,zero) u2<-cbind(-C2t,C4,zero,zero) u3<-cbind(zero,zero,C1,C2) u4<- cbind(zero,zero,-C2t,C4) U<-rbind(u1,u2,u3,u4) I<-diag(m) v1<- cbind(I,zero,K1,K2) v2<- cbind(zero,I,K3,-K4) v3<- cbind(-t(K1),-t(K3), I,zero) v4<- cbind(-t(K2),t(K4),zero,I) V<-rbind(v1,v2,v3,v4) s1<- matrix(rep(1),nrow = 2,ncol = 2) s2<- matrix(c(1,-1,-1,1),nrow = 2,ncol = 2) T11<- (C1 %x% s1) + (I %x% s2) T12<- (C2 %x% s1) + (zero %x% s2) T13<- (zero %x% s1) + ( K1 %x% s2) T14<- (zero %x% s1) + ( K2 %x% s2) T21<- (t(C2) %x% s1) + ( zero %x% s2) T22<- (C4 %x% s1) + ( I %x% s2) T23<- (zero %x% s1) + ( K3 %x% s2) T24<- (zero %x% s1) + ( K4 %x% s2) T31<- (zero %x% s1) + ( t(K1) %x% s2) T32<-(zero %x% s1) + ( t(K3) %x% s2) T33<-(C1 %x% s1) + ( I %x% s2) T34<- (C2 %x% s1) + ( zero %x% s2) T41<- (zero %x% s1) + ( t(K2) %x% s2) T42<- (zero %x% s1) + ( t(K4) %x% s2) T43<- (t(C2) %x% s1) + ( zero %x% s2) T44<-(C4 %x% s1) + ( I %x% s2) et<-matrix(rep(1),ncol = 2*m,nrow = 1) e<-matrix(rep(1),ncol = 1,nrow = 2*m) a1<-cbind(1,et) a12<- cbind(e,T12) X12<-rbind(a1,a12) a13<- cbind(e,T13) X13<-rbind(a1,a13) a14<- cbind(e,T14) X14<-rbind(a1,a14) a21<- cbind(e,T21) X21<-rbind(a1,a21) a23<- cbind(e,T23) X23<-rbind(a1,a23) a24<- cbind(e,T24) X24<-rbind(a1,a24) a31<- cbind(e,T31) X31<-rbind(a1,a31) a32<- cbind(e,T32) X32<-rbind(a1,a32) a34<- cbind(e,T34) X34<-rbind(a1,a34) a41<- cbind(e,T41) X41<-rbind(a1,a41) a42<- cbind(e,T42) X42<-rbind(a1,a42) a43<- cbind(e,T43) X43<-rbind(a1,a43) b1<- cbind(1,-et) b11<- cbind(-e,T11) X11<-rbind(b1,b11) b22<- cbind(-e,T22) X22<-rbind(b1,b22) b33<- cbind(-e,T33) X33<-rbind(b1,b33) b44<- cbind(-e,T44) X44<-rbind(b1,b44) h1<- cbind(X11,X12,X13,X14) h2<- cbind(-X21,X22,X23,-X24) h3<- cbind(-X31,-X32,X33,X34) h4<- cbind(-X41,X42,-X43,X44) H<-rbind(h1,h2,h3,h4) return(H) }
cwt_wst <- function(signal, dt = 1, scales = NULL, powerscales = TRUE, wname = c("MORLET", "DOG", "PAUL", "HAAR", "HAAR2"), wparam = NULL, waverad = NULL, border_effects = c("BE", "PER", "SYM"), makefigure = TRUE, time_values = NULL, energy_density = FALSE, figureperiod = TRUE, xlab = "Time", ylab = NULL, main = NULL, zlim = NULL ) { wname <- toupper(wname) wname <- match.arg(wname) if (is.null(waverad)) { if ((wname == "MORLET") || (wname == "DOG")) { waverad <- sqrt(2) } else if (wname == "PAUL") { waverad <- 1 / sqrt(2) } else { waverad <- 0.5 } } border_effects <- toupper(border_effects) border_effects <- match.arg(border_effects) nt <- length(signal) fourierfactor <- fourier_factor(wname = wname, wparam = wparam) if (is.null(scales)) { scmin <- 2 / fourierfactor scmax <- floor(nt / (2 * waverad)) if (powerscales) { scales <- pow2scales(c(scmin, scmax, ceiling(256 / log2(scmax / scmin)))) } else { scales <- seq(scmin, scmax, by = (scmax - scmin) / 256) } scalesdt <- scales * dt } else { if (powerscales && length(scales) == 3) { scales <- pow2scales(scales) } else { if (is.unsorted(scales)) { warning("Scales were not sorted.") scales <- sort(scales) } aux <- diff(log2(scales)) if (powerscales && ((max(aux) - min(aux)) / max(aux) > 0.05)) { warning("Scales seem like they are not power 2 scales. Powerscales set to FALSE.") powerscales <- FALSE } } scalesdt <- scales scales <- scales / dt } ns <- length(scales) if (border_effects == "BE") { nt_ini <- 1 nt_end <- nt } else if (border_effects == "PER") { ndatcat <- ceiling(ceiling(waverad * scales[ns]) / nt) ntcat <- (ndatcat * 2 + 1) * nt datcat <- numeric(ntcat) for (itcat in 1:ntcat) { datcat[itcat] = signal[itcat - floor((itcat - 1) / nt) * nt] } signal <- datcat nt_ini <- ndatcat * nt + 1 nt_end <- nt_ini + nt - 1 } else if (border_effects == "SYM") { ndatcat <- ceiling(ceiling(waverad * scales[ns]) / nt) dat_sym <- signal aux <- rev(signal) for (icat in 1:ndatcat) { dat_sym <- c(aux, dat_sym, aux) aux <- rev(aux) } signal <- dat_sym nt_ini <- ndatcat * nt + 1 nt_end <- nt_ini + nt - 1 } nt <- length(signal) coefs <- matrix(0, nrow = nt, ncol = ns) if (wname == "HAAR") { precision <- max(12, floor(log2(max(scales))) + 4) step <- 2 ^ (-precision) xval <- seq(from = 0, to = 1 + step, by = step) xmax <- max(xval) psi_integ <- xval * (xval < 1 / 2) + (1 - xval) * (xval >= 1 / 2) for (k in 1:ns) { a <- scales[k] j <- 1 + floor((0:a * xmax) / (a * step)) if (length(j) == 1) { j <- c(1, 1) } f <- rev(psi_integ[j]) coefs[, k] <- -sqrt(a) * core(diff(stats::convolve(signal, f, type = "open")), nt) } } else if (wname == "HAAR2") { for (j in 1:ns) { kmatrix <- matrix(0, nrow = nt, ncol = nt) klen <- floor((scales[j] - 1) / 2) kfrac <- (((scales[j] - 1) / 2) - klen) for (i in 1:nt) { kmin <- max(1, i - klen) kmax <- min(nt, i + klen) if (kmin <= (i - 1)) { kmatrix[kmin:(i - 1), i] <- 1 } if (kmin >= 2) { kmatrix[kmin - 1, i] <- kfrac } if (kmax >= (i + 1)) { kmatrix[(i + 1):kmax, i] <- -1 } if (kmax <= (nt - 1)) { kmatrix[kmax + 1, i] <- -kfrac } } coefs[, j] <- signal %*% kmatrix / sqrt(scales[j]) } } else { f <- stats::fft(signal) k <- 1:trunc(nt / 2) k <- k * 2 * pi / nt k <- c(0, k, -k[trunc((nt - 1) / 2):1]) n <- length(k) if (wname == "MORLET") { if (is.null(wparam)) { wparam <- 6 } expnt <- -(diag(x = scales, ncol = ns) %*% matrix(rep(k, ns), nrow = ns, byrow = T) - wparam) ^ 2 / 2 expnt <- sweep(expnt, MARGIN = 2, (k > 0), `*`) Norm <- sqrt(scales * k[2]) *pi ^ (-.25) * sqrt(n) daughter <- diag(x = Norm, ncol = ns) %*% exp(expnt) daughter <- sweep(daughter, MARGIN = 2, (k > 0), `*`) coefs <- coefs + 1i*coefs } else if (wname == "PAUL") { if (is.null(wparam)) { wparam <- 4 } coefs <- coefs + 1i*coefs expnt <- -diag(x = scales, ncol = ns) %*% matrix(rep(k, ns), nrow = ns, byrow = T) expnt <- sweep(expnt, MARGIN = 2, (k > 0), `*`) Norm <- sqrt(scales * k[2]) * (2 ^ wparam / sqrt(wparam * prod(2:(2 * wparam - 1)))) * sqrt(n) daughter <- diag(x = Norm, ncol = ns) %*% expnt ^ wparam * exp(expnt) daughter <- sweep(daughter, MARGIN = 2, (k > 0), `*`) coefs <- coefs + 1i*coefs } else if (wname == "DOG") { if (is.null(wparam)) { wparam <- 2 } preexpnt <- (diag(x = scales, ncol = ns) %*% matrix(rep(k, ns), nrow = ns, byrow = T)) expnt <- -preexpnt ^ 2 / 2 Norm <- sqrt(scales * k[2] / gamma(wparam + 0.5)) * sqrt(n) daughter <- diag(x = -Norm * (1i ^ wparam), ncol = ns) %*% preexpnt ^ wparam * exp(expnt) } coefs <- stats::mvfft(t(sweep(daughter, MARGIN = 2, f, `*`)), inverse = TRUE) / length(f) } coefs <- coefs[nt_ini:nt_end, 1:ns] * sqrt(dt) nt <- nt_end - nt_ini + 1 coi_maxscale <- numeric(nt) for (i in 1:nt) { coi_maxscale[i] <- dt * min(i - 1, nt - i) / waverad } if (makefigure) { if (is.null(time_values)) { X <- seq(0, (nt - 1) * dt, dt) } else { if (length(time_values) != nt) { warning("Invalid length of time_values vector. Changing to default.") X <- seq(0, (nt - 1) * dt, dt) } else { X <- time_values } } ylab_aux <- ylab if (figureperiod) { Y <- fourierfactor * scalesdt coi <- fourierfactor * coi_maxscale if (is.null(ylab)) ylab <- "Period" } else { Y <- scalesdt coi <- coi_maxscale if (is.null(ylab)) ylab <- "Scale" } if (energy_density) { Z <- t(t(abs(coefs) ^ 2) / scalesdt) if (is.null(main)) main <- "Wavelet Power Spectrum / Scales" } else { Z <- abs(coefs) ^ 2 if (is.null(main)) main <- "Wavelet Power Spectrum" } if (ns > 1) { wavPlot( Z = Z, X = X, Y = Y, Ylog = powerscales, coi = coi, Xname = xlab, Yname = ylab, Zname = main, zlim = zlim ) } else { if (is.null(ylab_aux)) { if (energy_density) { ylab <- "Wavelet Power Spectrum / Scales" } else { ylab <- "Wavelet Power Spectrum" } } plot(X, Z, type = "l", xlab = xlab, ylab = ylab, main = main, xaxt = "n") axis(side = 1, at = X[1 + floor((0:8) * (nt - 1) / 8)]) abline(v = range(X[(coi > Y)]), lty = 2) } } return(list( coefs = coefs, scales = scalesdt, fourierfactor = fourierfactor, coi_maxscale = coi_maxscale )) } core <- function(x, n) { if (n > length(x)) { stop("Error. The length of the vector x should be greater than n.") } if (n == length(x)) { extracted <- x } else { if (length(x) %% 2 == 0){ center1 <- length(x) / 2 center2 <- length(x) / 2 + 1 if (n %% 2 == 1) { n1 <- center1 - floor(n / 2) n2 <- center2 + floor(n / 2) - 1 } else { n1 <- center1 - (n / 2 - 1) n2 <- center2 + (n / 2 - 1) } } else { center <- floor(length(x) / 2) + 1 if (n %% 2 == 1) { n1 <- center - floor(n / 2) n2 <- center + floor(n / 2) } else { n1 <- center - n / 2 n2 <- center + (n / 2 - 1) } } extracted <- x[n1:n2] } return(extracted) }
leafsfirst.complex<-function(dendat,f,complex,rho=0) { d<-dim(dendat)[2] lkm<-dim(complex)[1] lambdas<-matrix(0,lkm,1) mids<-matrix(0,lkm,d) for (i in 1:lkm){ vs<-complex[i,] vals<-f[vs] lambdas[i]<-min(vals) mids[i,1]<-mean(dendat[vs,1]) mids[i,2]<-mean(dendat[vs,2]) } pcfhigh<-mids+rho/2 pcfdown<-mids-rho/2 distat<-lambdas infopointer<-seq(1,lkm) ord<-order(distat) infopointer<-infopointer[ord] parent<-matrix(0,lkm,1) child<-matrix(0,lkm,1) sibling<-matrix(0,lkm,1) volume<-matrix(0,lkm,1) radius<-matrix(0,lkm,1) number<-matrix(0,lkm,1) atomlist<-matrix(0,lkm,lkm) atomnumb<-matrix(0,lkm,1) highestNext<-matrix(0,lkm,1) boundrec<-matrix(0,lkm,2*d) node<-lkm parent[node]<-0 child[node]<-0 sibling[node]<-0 radius[node]<-distat[ord[node]] simple<-complex[infopointer[node],] simp<-dendat[simple,] volume[node]<-voltriangle(simp) number[node]<-1 atomlist[node,1]<-infopointer[node] atomnumb[node]<-1 beg<-node highestNext[node]<-0 note<-infopointer[node] for (i in 1:d){ boundrec[node,2*i-1]<-pcfdown[note,i] boundrec[node,2*i]<-pcfhigh[note,i] } j<-2 while (j<=lkm){ node<-lkm-j+1 highestNext[node]<-beg beg<-node rec1<-matrix(0,2*d,1) note<-infopointer[node] for (i in 1:d){ rec1[2*i-1]<-pcfdown[note,i] rec1[2*i]<-pcfhigh[note,i] } boundrec[node,]<-rec1 radius[node]<-distat[ord[node]] simple<-complex[infopointer[node],] simp<-dendat[simple,] volume[node]<-voltriangle(simp) number[node]<-1 atomlist[node,1]<-infopointer[node] atomnumb[node]<-1 curroot<-highestNext[beg] prevroot<-beg ekatouch<-0 while (curroot>0){ istouch<-touchstep.complex(node,curroot,boundrec,child,sibling, infopointer,pcfdown,pcfhigh,dendat,complex) if (istouch==1){ parent[curroot]<-node if (ekatouch==0) ekatouch<-1 else ekatouch<-0 if (ekatouch==1){ child[node]<-curroot } else{ sibling[lastsib]<-curroot } number[node]<-number[node]+number[curroot] volume[node]<-volume[node]+volume[curroot] atomlist[node,(atomnumb[node]+1):(atomnumb[node]+atomnumb[curroot])]<-atomlist[curroot,1:atomnumb[curroot]] atomnumb[node]<-atomnumb[curroot]+atomnumb[node] radius[node]<-min(distat[ord[node]],distat[ord[curroot]]) rec1<-boundrec[node,] rec2<-boundrec[curroot,] boundrec[node,]<-boundbox(rec1,rec2) highestNext[prevroot]<-highestNext[curroot] } if (istouch==0) prevroot<-curroot else lastsib<-curroot curroot<-highestNext[curroot] } j<-j+1 } root<-1 maxdis<-distat[ord[length(ord)]] center<-t(mids[infopointer,]) lf<-list( parent=parent,volume=volume,center=center,level=radius, root=root, infopointer=infopointer, maxdis=maxdis, dendat=dendat,rho=rho, atomlist=atomlist,atomnumb=atomnumb) return(lf) }
fii2fi <- function(DESIGN,fii,fi){ Dsup <- fastEucCalc(fii,fi) minD <- apply(Dsup,1,min) Group_Assigned=Re(Dsup==repmat(minD,1,ncol(DESIGN))) return(list(distances=Dsup,assignments=Group_Assigned,confusion=t(Group_Assigned) %*% DESIGN)) }
test_that("invalid parameter values are detected", { expect_equal(is_GHvalid(h = c(2, 3, 0, 0.8, 1.2, 18)), TRUE) expect_type(is_GHvalid(h = -3), 'character') expect_type(is_GHvalid(h = c(2, -3, 4, 9)), 'character') })
library(ggplot2) power.analysis.bw = function (d, OR, k, n1, n2, p = 0.05, heterogeneity = "fixed") { odds = FALSE if (missing(OR) & missing(d)) { stop("Either 'd' or 'OR' must be provided.") } if (!(heterogeneity %in% c("fixed", "low", "moderate", "high"))) { stop("'heterogeneity' must be either 'fixed', 'low', 'moderate', 'high'.") } if (missing(d)) { odds = TRUE d = log(OR) * (sqrt(3)/pi) token1 = "log" } else { token1 = "no.log" } es = d if (heterogeneity == "fixed") { het.factor = 1 v.d = ((n1 + n2)/(n1 * n2)) + ((d * d)/(2 * (n1 + n2))) v.m = v.d/k lambda = (d/sqrt(v.m)) plevel = 1 - (p/2) zval = qnorm(p = plevel, 0, 1) power = 1 - (pnorm(zval - lambda)) + (pnorm(-zval - lambda)) token2 = "fixed" } if (heterogeneity == "low") { het.factor = 1.33 v.d = ((n1 + n2)/(n1 * n2)) + ((d * d)/(2 * (n1 + n2))) v.m = v.d/k v.m = 1.33 * v.m lambda = (d/sqrt(v.m)) plevel = 1 - (p/2) zval = qnorm(p = plevel, 0, 1) power = 1 - (pnorm(zval - lambda)) + (pnorm(-zval - lambda)) token2 = "low" } if (heterogeneity == "moderate") { het.factor = 1.67 v.d = ((n1 + n2)/(n1 * n2)) + ((d * d)/(2 * (n1 + n2))) v.m = v.d/k v.m = 1.67 * v.m lambda = (d/sqrt(v.m)) plevel = 1 - (p/2) zval = qnorm(p = plevel, 0, 1) power = 1 - (pnorm(zval - lambda)) + (pnorm(-zval - lambda)) token2 = "moderate" } if (heterogeneity == "high") { het.factor = 2 v.d = ((n1 + n2)/(n1 * n2)) + ((d * d)/(2 * (n1 + n2))) v.m = v.d/k v.m = 2 * v.m lambda = (d/sqrt(v.m)) plevel = 1 - (p/2) zval = qnorm(p = plevel, 0, 1) power = 1 - (pnorm(zval - lambda)) + (pnorm(-zval - lambda)) token2 = "high" } dvec = (1:1000)/1000 if (d > 1) { dvec = (1:(d * 1000))/1000 } powvect = vector() for (i in 1:length(dvec)) { d = dvec[i] v.d = ((n1 + n2)/(n1 * n2)) + ((d * d)/(2 * (n1 + n2))) v.m = v.d/k v.m = het.factor * v.m lambda = (d/sqrt(v.m)) plevel = 1 - (p/2) zval = qnorm(p = plevel, 0, 1) powvect[i] = 1 - (pnorm(zval - lambda)) + (pnorm(-zval - lambda)) } if (odds == FALSE) { plotdat = as.data.frame(cbind(dvec, powvect)) plot = ggplot(data = plotdat, aes(x = dvec, y = powvect)) + geom_line(color = "gray70", size = 2) + geom_point(aes(x = es, y = power), color = "gray30", size = 5) + theme_minimal() + geom_hline(yintercept = 0.8, color = "black", linetype = "dashed") + ylab("Power") + xlab("Effect size (SMD)") } else { dvecs = exp(dvec * (pi/sqrt(3))) dvec.inv = exp(-dvec * (pi/sqrt(3))) dvec = as.vector(rbind(dvec.inv, dvecs)) powvect = as.vector(rbind(powvect, powvect)) plotdat = as.data.frame(cbind(dvec, powvect)) plot = ggplot(data = plotdat, aes(x = dvec, y = powvect)) + geom_line(color = "gray70", size = 2) + geom_point(aes(x = exp(es * (pi/sqrt(3))), y = power), color = "gray30", size = 5) + theme_minimal() + geom_hline(yintercept = 0.8, color = "black", linetype = "dashed") + ylab("Power") + xlab("Effect size (OR)") + scale_x_log10() } return.list = list(Plot = plot, Power = power) class(return.list) = c("power.analysis", token1, token2) invisible(return.list) return.list }
context("Testing ai function works as advertised") a <- c(1, 2, 3, 4, 7) b <- c(1, 3, 2, 5, 3) test_that("ai returns correct classes",{ expect_is(ai(a, b), "ai") }) test_that("ai errors correctly", { expect_error(ai(3, "a")) expect_error(ai(3, 2)) expect_error(ai(3, 2), lambda=-3) expect_error(ai(3, 2), alpha=4) }) ans=ai(x=IPIA$Tomography, y=IPIA$Urography) test_that("ai returns the same value", { expect_equal(round(ans$indexEst["Lin.CCC", "Est"], 3), 0.810) expect_equal(round(ans$indexEst["Lin.CCC", "95LL"], 3), 0.693) expect_equal(round(ans$indexEst["Lin.CCC", "95UL"], 3), 0.885) expect_equal(round(ans$intervalEst["Bland-Altman.LOA", "95LL"], 3), -17.752) expect_equal(round(ans$intervalEst["Bland-Altman.LOA", "95UL"], 3), 21.098) expect_equal(round(ans$intervalEst["Liao.AI", "95LL"], 3), -19.275) expect_equal(round(ans$intervalEst["Liao.AI", "95UL"], 3), 19.275) expect_equal(round(ans$tolProb, 3), 0.485) }) ans=ai(x=IPIA$Urography, y=IPIA$Tomography, clin.limit=c(-15, 15)) test_that("ai returns the same value with clin.limit", { expect_equal(round(ans$alpha.cl, 3), 0.124) expect_equal(ans$k.cl, 5) expect_equal(round(ans$tolProb.cl, 2), 0.64) })
NULL simulate_access <- function() simulate_dbi("ACCESS") dbplyr_edition.ACCESS <- function(con) { 2L } sql_query_select.ACCESS <- function(con, select, from, where = NULL, group_by = NULL, having = NULL, order_by = NULL, limit = NULL, distinct = FALSE, ..., subquery = FALSE) { sql_select_clauses(con, select = sql_clause_select(con, select, distinct, top = limit), from = sql_clause_from(con, from), where = sql_clause_where(con, where), group_by = sql_clause_group_by(con, group_by), having = sql_clause_having(con, having), order_by = sql_clause_order_by(con, order_by, subquery, limit) ) } sql_translation.ACCESS <- function(con) { sql_variant( sql_translator(.parent = base_scalar, as.numeric = sql_prefix("CDBL"), as.double = sql_prefix("CDBL"), as.integer = sql_prefix("INT"), as.logical = sql_prefix("CBOOL"), as.character = sql_prefix("CSTR"), as.Date = sql_prefix("CDATE"), exp = sql_prefix("EXP"), log = sql_prefix("LOG"), log10 = function(x) { sql_expr(log(!!x) / log(10L)) }, sqrt = sql_prefix("SQR"), sign = sql_prefix("SGN"), floor = sql_prefix("INT"), ceiling = function(x) { sql_expr(int(!!x + .9999999999)) }, ceil = function(x) { sql_expr(int(!!x + .9999999999)) }, `^` = function(x, y) { sql_expr((!!x) ^ (!!y)) }, nchar = sql_prefix("LEN"), tolower = sql_prefix("LCASE"), toupper = sql_prefix("UCASE"), substr = function(x, start, stop){ right <- stop - start + 1 left <- stop sql_expr(right(left(!!x, !!left), !!right)) }, trimws = sql_prefix("TRIM"), paste = sql_paste_infix(" ", "&", function(x) sql_expr(CStr(!!x))), paste0 = sql_paste_infix("", "&", function(x) sql_expr(CStr(!!x))), is.null = sql_prefix("ISNULL"), is.na = sql_prefix("ISNULL"), ifelse = function(test, yes, no){ sql_expr(iif(!!test, !!yes, !!no)) }, coalesce = function(x, y) { sql_expr(iif(isnull(!!x), !!y, !!x)) }, pmin = function(x, y) { sql_expr(iif(!!x <= !!y, !!x, !!y)) }, pmax = function(x, y) { sql_expr(iif(!!x <= !!y, !!y, !!x)) }, Sys.Date = sql_prefix("DATE") ), sql_translator(.parent = base_agg, sd = sql_aggregate("STDEV"), var = sql_aggregate("VAR"), cor = sql_not_supported("cor"), cov = sql_not_supported("cov"), n_distinct = sql_not_supported("n_distinct"), ), sql_translator(.parent = base_no_win) ) } sql_table_analyze.ACCESS <- function(con, table, ...) { NULL } sql_escape_logical.ACCESS <- function(con, x) { y <- ifelse(x, -1, 0) y[is.na(x)] <- "NULL" y } sql_escape_date.ACCESS <- function(con, x) { y <- format(x, " y[is.na(x)] <- "NULL" y } sql_escape_datetime.ACCESS <- function(con, x) { y <- format(x, " y[is.na(x)] <- "NULL" y } globalVariables(c("CStr", "iif", "isnull", "text"))
expected <- TRUE test(id=10, code={ argv <- structure(list(x = structure(c(1412799280.04908, 1412799280.04908 ), class = c("POSIXct", "POSIXt")), what = "POSIXt"), .Names = c("x", "what")) do.call('inherits', argv); }, o = expected);
orderMCMCmain<-function(param,iterations,stepsave,MAP=TRUE, posterior=0.5, startorder=c(1:n),moveprobs,plus1=FALSE,chainout=TRUE, scoreout=FALSE,startspace=NULL,blacklist=NULL,gamma=1,verbose=FALSE,alpha=NULL, hardlimit=ifelse(plus1,15,22), cpdag=FALSE,addspace=NULL,scoretable=NULL){ result<-list() maxobj<-list() MCMCtraces<-list() n<-param$n nsmall<-param$nsmall matsize<-ifelse(param$DBN,n+nsmall,n) if(!param$DBN) { if(param$bgn!=0) { updatenodes<-c(1:n)[-param$bgnodes] } else { updatenodes<-c(1:n) } } else { updatenodes<-c(1:nsmall) } maxorder<-startorder if (is.null(blacklist)) { blacklist<-matrix(0,nrow=matsize,ncol=matsize) } diag(blacklist)<-1 if(!is.null(param$bgnodes)) { for(i in param$bgnodes) { blacklist[,i]<-1 } } if (!is.null(scoretable)) { startskel<-scoretable$adjacency blacklist<-scoretable$blacklist scoretable<-scoretable$tables } else { if (is.null(startspace)){ startspace<-definestartspace(alpha,param,cpdag=cpdag,algo="pc") } startskeleton<-1*(startspace&!blacklist) if(!is.null(addspace)) { startskel<-1*((addspace|startskeleton)&!blacklist) } else {startskel<-startskeleton } } blacklistparents<-list() for (i in 1:matsize) { blacklistparents[[i]]<-which(blacklist[,i]==1) } if(verbose) { cat(paste("maximum parent set size is", max(apply(startskel,2,sum))),"\n") } if(max(apply(startskel,2,sum))>hardlimit) { stop("the size of maximal parent set is higher that the hardlimit; redifine the search space or increase the hardlimit!") } tablestart<-Sys.time() ptab<-listpossibleparents.PC.aliases(startskel,isgraphNEL=FALSE,n,updatenodes) if (verbose) { cat("core space defined, score table are being computed \n") flush.console() } if (plus1==FALSE) { parenttable<-ptab$parenttable aliases<-ptab$aliases numberofparentsvec<-ptab$numberofparentsvec numparents<-ptab$numparents rowmaps<-parentsmapping(parenttable,numberofparentsvec,n,updatenodes) if(is.null(scoretable)) { scoretable<-scorepossibleparents.alias(parenttable,aliases,n,param,updatenodes,rowmaps, numparents,numberofparentsvec) } posetparenttable<-poset(parenttable,numberofparentsvec,rowmaps,n,updatenodes) if(MAP==TRUE){ maxmatrices<-posetscoremax(posetparenttable,scoretable,numberofparentsvec,rowmaps, n,plus1lists=NULL,updatenodes) tableend<-Sys.time() MCMCresult<-orderMCMCbasemax(n,nsmall,startorder,iterations,stepsave,moveprobs,parenttable, scoretable,aliases,numparents,rowmaps,maxmatrices, numberofparentsvec,gamma=gamma,bgnodes=param$bgnodes,matsize=matsize) mcmcend<-Sys.time() } else { bannedscore<-poset.scores(posetparenttable,scoretable,numberofparentsvec,rowmaps, n,plus1lists=NULL,ptab$numparents,updatenodes=updatenodes) tableend<-Sys.time() MCMCresult<-orderMCMCbase(n,nsmall,startorder,iterations,stepsave,moveprobs,parenttable, scoretable,aliases,numparents,rowmaps, bannedscore,numberofparentsvec,gamma=gamma, bgnodes=param$bgnodes,matsize=matsize) mcmcend<-Sys.time() } } else { parenttable<-ptab$parenttable aliases<-ptab$aliases numberofparentsvec<-ptab$numberofparentsvec numparents<-ptab$numparents plus1lists<-PLUS1(matsize,aliases,updatenodes,blacklistparents) rowmaps<-parentsmapping(parenttable,numberofparentsvec,n,updatenodes) if(is.null(scoretable)) { scoretable<-scorepossibleparents.PLUS1(parenttable,plus1lists,n,param,updatenodes, rowmaps,numparents,numberofparentsvec) } posetparenttable<-poset(parenttable,numberofparentsvec,rowmaps,n,updatenodes) if(MAP==TRUE){ maxmatrices<-posetscoremax(posetparenttable,scoretable,numberofparentsvec, rowmaps,n,plus1lists=plus1lists,updatenodes) } else { bannedscore<-poset.scores(posetparenttable,scoretable,ptab$numberofparentsvec,rowmaps, n,plus1lists=plus1lists,ptab$numparents,updatenodes) } if(verbose) { cat(paste("score tables computed, orderMCMCis running"),"\n") flush.console() } tableend<-Sys.time() if(MAP) { MCMCresult<-orderMCMCplus1max(n,nsmall,startorder,iterations,stepsave,moveprobs,parenttable, scoretable,aliases,numparents,rowmaps,plus1lists,maxmatrices,numberofparentsvec, gamma=gamma,bgnodes=param$bgnodes,matsize=matsize) } else { MCMCresult<-orderMCMCplus1(n,nsmall,startorder,iterations,stepsave,moveprobs,parenttable, scoretable,aliases,numparents,rowmaps,plus1lists, bannedscore,numberofparentsvec,gamma=gamma, bgnodes=param$bgnodes,matsize=matsize) } mcmcend<-Sys.time() } if(chainout) { if(param$DBN) { MCMCchain<-lapply(MCMCresult$incidence,function(x)DBNtransform(x,param=param)) MCMCtraces$incidence<-MCMCchain MCMCtraces$orders<-lapply(MCMCresult$orders,order2var,varnames=param$firstslice$labels) } else { MCMCtraces$incidence<-lapply(MCMCresult$incidence,function(x)assignLabels(x,param$labels)) MCMCtraces$orders<-lapply(MCMCresult$orders,order2var,varnames=param$labels) } MCMCtraces$orderscores<-MCMCresult$orderscores } maxobj<-storemaxMCMC(MCMCresult,param) maxN<-which.max(MCMCresult$DAGscores) if (scoreout){ if(chainout){output<-4} else{output<-3} } else { if(chainout) {output<-2} else {output<-1} } result$DAG<-maxobj$DAG result$CPDAG<-graph2m(dag2cpdag(m2graph(result$DAG))) result$score<-maxobj$score result$maxorder<-maxobj$order result$info<-list() tabletime<-tableend-tablestart if(units(tabletime)=="mins") { tabletime<-as.numeric(tabletime*60) } mcmctime<-mcmcend-tableend if(units(mcmctime)=="mins") { mcmctime<-as.numeric(mcmctime*60) } result$info$runtimes<-c(tabletime,mcmctime) names(result$info$runtimes)<-c("scoretables","MCMCchain") result$trace<-MCMCresult$DAGscores switch(as.character(output), "1"={ }, "2"={ result$traceadd<-MCMCtraces }, "3"={ result$scoretable<-list() result$scoretable$adjacency<-startskel result$scoretable$tables<-scoretable result$scoretable$blacklist<-blacklist attr(result$scoretable,"class")<-"scorespace" }, "4"={ result$scoretable<-list() result$scoretable$adjacency<-startskel result$scoretable$tables<-scoretable result$scoretable$blacklist<-blacklist attr(result$scoretable,"class")<-"scorespace" result$traceadd<-MCMCtraces } ) attr(result,"class")<-"orderMCMC" 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(zoo) library(ggrepel) library(survey) library(lemon) library(mitools) library(Hmisc) library(tidyverse) folder_name <- "xxxx_scf_wealth_over_time" out_path <- paste0(exportdir, folder_name) dir.create(file.path(paste0(out_path)), showWarnings = FALSE) age_year_groups <- data.frame(year = c(seq(1992, 2019, 3), seq(1995, 2019, 3), seq(1998, 2019, 3), seq(2001, 2019, 3), seq(2004, 2019, 3), seq(2007, 2019, 3)), age_group = c(rep(1, 10), rep(2, 9), rep(3, 8), rep(4, 7), rep(5, 6), rep(6, 5)), min_age = c(seq(64, 91, 3), seq(64, 88, 3), seq(64, 85, 3), seq(64, 82, 3), seq(64, 79, 3), seq(64, 76, 3)), max_age = c(seq(66, 93, 3), seq(66, 90, 3), seq(66, 87, 3), seq(66, 84, 3), seq(66, 81, 3), seq(66, 78, 3))) for(i in 1:nrow(age_year_groups)){ print(i) min_age <- age_year_groups[i, "min_age"] max_age <- age_year_groups[i, "max_age"] yr <- age_year_groups[i, "year"] ag_group <- age_year_groups[i, "age_group"] tmp <- readRDS(paste0(localdir, "0003_scf_stack.Rds")) %>% filter(year == yr, age >= min_age, age <= max_age) %>% mutate(age_group = ag_group, min_max_age = paste0(min_age, "-", max_age)) %>% select(hh_id, imp_id, year, age_group, min_max_age, networth, reteq, wgt) if(i == 1){ df <- tmp } else{ df <- df %>% bind_rows(tmp) } } summary <- df %>% group_by(year, age_group, min_max_age) %>% summarise( median_nw = wtd.quantile(networth, weights = wgt, probs=0.5), median_reteq = wtd.quantile(reteq, weights = wgt, probs=0.5) ) %>% ungroup() %>% gather(-year, -age_group, -min_max_age, key=key, value=value) %>% mutate() to_plot <- summary %>% filter(key == "median_reteq") file_path <- paste0(out_path, "/median_nw_over_time.jpeg") plot <- ggplot(data = to_plot, aes(x = year, y=value, col = as.factor(age_group))) + geom_line() + scale_color_discrete(guide = FALSE) + of_dollars_and_data_theme + labs(x = "Year" , y = "Median Net Worth") + ggtitle(paste0("Median Liquid Net Worth")) ggsave(file_path, plot, width = 15, height = 12, units = "cm")
test_all_formats <- function(zone = TRUE) { out <- paste( "C: %C", "y: %y", "Y: %Y", "b: %b", "h: %h", "B: %B", "m: %m", "d: %d", "a: %a", "A: %A", "w: %w", "g: %g", "G: %G", "V: %V", "u: %u", "U: %U", "W: %W", "j: %j", "D: %D", "x: %x", "F: %F", "H: %H", "I: %I", "M: %M", "S: %S", "p: %p", "R: %R", "T: %T", "X: %X", "r: %r", "c: %c", "%: %%", sep = "\n" ) if (!zone) { return(out) } paste( out, "z: %z", "Ez: %Ez", "Z: %Z", sep = "\n" ) }
coef.alspath <- function(object, s = NULL, type = c("coefficients", "nonzero"), ...) { type <- match.arg(type) b0 <- t(as.matrix(object$b0)) rownames(b0) <- "(Intercept)" nbeta <- rbind2(b0, object$beta) if (!is.null(s)) { vnames <- dimnames(nbeta)[[1]] dimnames(nbeta) <- list(NULL, NULL) lambda <- object$lambda lamlist <- lambda.interp(lambda, s) nbeta <- nbeta[,lamlist$left,drop=FALSE]%*%Diagonal(x=lamlist$frac) + nbeta[,lamlist$right,drop=FALSE]%*%Diagonal(x=1-lamlist$frac) dimnames(nbeta) <- list(vnames, paste(seq(along = s))) } if (type == "coefficients") return(nbeta) if (type == "nonzero") return(nonzero(nbeta[-1, , drop = FALSE], bystep = TRUE)) }
cid_compinfo <- function(...) { .Deprecated("pc_prop", package = "webchem") cid_compinfo(...) } aw_query <- function(...) { .Deprecated("bcpc_query", package = "webchem") bcpc_query(...) }
loadKarsTSFonts <- function() { fontmainbt <- tcltk::tkfont.create(family = "Arial", size = 14, weight = "bold") fontsubbt <- tcltk::tkfont.create(family = "Arial", size = 12, weight = "bold") fontsubbt1 <- tcltk::tkfont.create(family = "Arial", size = 12, weight = "bold", underline = TRUE) fonttitle0pan <- tcltk::tkfont.create(family = "Arial", size = 11, weight = "bold", underline = TRUE) fonttitle1pan <- tcltk::tkfont.create(family = "Arial", size = 11, weight = "bold") fonttitle2pan <- tcltk::tkfont.create(family = "Arial", size = 11, slant = "italic") fontnormpan <- tcltk::tkfont.create(family = "Arial", size = 11) fontaclara <- tcltk::tkfont.create(family = "Arial", size = 11, slant = "italic") KTSEnv$KTSFonts <- list(mainBt = fontmainbt, subBt = fontsubbt, subBt1 = fontsubbt1, explain = fontaclara, T0 = fonttitle0pan, T1 = fonttitle1pan, T2 = fonttitle2pan, normal = fontnormpan) }
extract.ergmito <- function( model, include.aic = TRUE, include.bic = TRUE, include.loglik = TRUE, include.nnets = TRUE, include.offset = TRUE, include.convergence = TRUE, include.timing = TRUE, ... ) { if (!requireNamespace("texreg", quietly = TRUE)) stop("Need to install the `texreg` package.", call. = FALSE) s <- summary(model, ...) coefficient.names <- rownames(s$coefs) coefficients <- s$coefs[, 1] standard.errors <- s$coefs[, "Std. Error"] significance <- s$coefs[, "Pr(>|z|)"] gof <- numeric() gof.names <- character() gof.decimal <- logical() if (include.aic == TRUE && !is.null(s$aic)) { aic <- s$aic gof <- c(gof, aic) gof.names <- c(gof.names, "AIC") gof.decimal <- c(gof.decimal, TRUE) } if (include.bic == TRUE && !is.null(s$bic)) { bic <- s$bic gof <- c(gof, bic) gof.names <- c(gof.names, "BIC") gof.decimal <- c(gof.decimal, TRUE) } if (include.loglik == TRUE && !is.null(model$mle.lik)) { lik <- model$mle.lik[1] gof <- c(gof, lik) gof.names <- c(gof.names, "Log Likelihood") gof.decimal <- c(gof.decimal, TRUE) } if (include.nnets) { gof <- c(gof, nnets(model$network)) gof.names <- c(gof.names, "Num. networks") gof.decimal <- c(gof.decimal, FALSE) } if (include.convergence) { gof <- c(gof, model$optim.out$convergence) gof.names <- c(gof.names, "Convergence") gof.decimal <- c(gof.decimal, FALSE) } model_terms <- terms(formula(model)) if (include.offset && length(noffsets <- attr(model_terms, "offset"))) { offsets <- rownames(attr(model_terms, "factor"))[attr(model_terms, "offset")] offsets <- paste("(offset)", gsub("^offset[(]|[)]$", "", offsets)) coefficient.names <- c(coefficient.names, offsets) coefficients <- c(coefficients, rep(1, length(offsets))) standard.errors <- c(standard.errors, rep(NA, length(offsets))) significance <- c(significance, rep(NA, length(offsets))) } if (inherits(model, "ergmito_boot")) { gof <- c(gof, model$R) gof.names <- c(gof.names, "N replicates") gof.decimal <- c(gof.decimal, FALSE) gof <- c(gof, model$nvalid) gof.names <- c(gof.names, "N Used replicates") gof.decimal <- c(gof.decimal, FALSE) } if (include.timing) { gof <- c( gof, ifelse( inherits(model, "ergmito_boot"), model$timer_boot["total"], model$timer["total"] ) ) gof.names <- c(gof.names, "Time (seconds)") gof.decimal <- c(gof.decimal, TRUE) } return( texreg::createTexreg( coef.names = coefficient.names, coef = coefficients, se = standard.errors, pvalues = significance, gof.names = gof.names, gof = gof, gof.decimal = gof.decimal ) ) } setMethod( "extract", signature = className("ergmito", "ergmito"), definition = extract.ergmito ) setMethod( "extract", signature = className("ergmito_boot", "ergmito"), definition = extract.ergmito )
context("check accuracy of tango.test") data(nydf) coords = as.matrix(nydf[, c("x", "y")]) dc = as.matrix(dist(coords)) kvec = 1 k = 1 p = nydf$pop / sum(nydf$pop) qdat = nydf$cases / sum(nydf$cases) nn = sum(nydf$cases) w = diag(p) - p %*% t(p) rad = kvec[k] ac = exp(-dc / rad) hh = ac %*% w hh2 = hh %*% hh av = sum(diag(hh)) av2 = sum(diag(hh2)) av3 = sum(diag(hh2 %*% hh)) skew1 = 2 * sqrt(2) * av3 / (av2) ^ 1.5 df1 = 8 / skew1 / skew1 eg1 = av vg1 = 2 * av2 gt = (qdat - p) %*% ac %*% (qdat - p) * nn stat1 = (gt - eg1) / sqrt(vg1) aprox = df1 + sqrt(2 * df1) * stat1 w = dweights(coords, kappa = 1) results = tango.test(nydf$cases, nydf$pop, w, nsim = 0) test_that("check accuracy for tango.test for NY data", { expect_equal(df1, results$dfc) expect_equal(aprox[1, 1], results$tstat.chisq) })
context("elliptic_PI") test_that("Comparisons with Wolfram", { expect_equal(0.3468194+0.7198448i, elliptic_PI(1+1i, 2, -2), tolerance = 1e-7) expect_equal(0.67834548+1.05327009i, elliptic_PI(1+1i, 2, -2i), tolerance = 1e-7) expect_equal(0.671398646+0.79618888i, elliptic_PI(1+1i, 2+1i, -2i), tolerance = 1e-7) }) test_that("n=0", { expect_equal(elliptic_PI(7+1i,0,2-1i), elliptic_F(7+1i,2-1i)) }) test_that("n=m", { phi <- 7+1i m <- 2-1i expect_equal( elliptic_E(phi, m), (1-m)*elliptic_PI(phi, m, m) + m*sin(2*phi)/2/sqrt(1-m*sin(phi)^2) ) }) test_that("n=1", { phi <- 1+1i m <- 2-1i expect_equal( elliptic_PI(phi, 1, m), (sqrt(1-m*sin(phi)^2)*tan(phi)-elliptic_E(phi,m))/(1-m) + elliptic_F(phi, m) ) }) test_that("m=0", { z <- 1+1i n <- 3 expect_equal( elliptic_PI(z, n, 0), atanh(sqrt(n-1)*tan(z)) / sqrt(n-1) ) }) test_that("m=1", { z <- 1+1i n <- 3 expect_equal( elliptic_PI(z, n, 1), (sqrt(n) * atanh(sqrt(n)*sin(z)) - atanh(sin(z))) / (n-1) ) }) test_that("misc equalities", { n <- 2+2i m <- 3 expect_equal( elliptic_PI(asin(1/sqrt(m)), n, m), elliptic_PI(pi/2, n/m, 1/m) / sqrt(m) ) }) test_that("Symmetry", { z <- -5 + 3i n <- 3 + 11i m <- -4 - 9i expect_equal( elliptic_PI(Conj(z), Conj(n), Conj(m)), Conj(elliptic_PI(z, n, m)) ) }) test_that("Parity", { z <- -5 + 3i n <- 3 + 11i m <- -4 - 9i expect_equal( elliptic_PI(-z, n, m), -elliptic_PI(z, n, m) ) })
context("test-StoxExport: ICES biotic export") example <- system.file("testresources", "biotic_v3_example.xml", package="RstoxData") data <- RstoxData::ReadBiotic(example) data[[1]]$fishstation[, stationstartdate := stationstopdate] ICESBiotic <- RstoxData::ICESBiotic(data, SurveyName = "NONE", Country = "No", Organisation = 612) ICESBiotic <- RstoxData::WriteICESBiotic(ICESBiotic) expect_equal(dim(ICESBiotic[[1]]), c(96, 45)) context("test-StoxExport: ICES acoustic export example <- system.file("testresources", "ICES_Acoustic_1.xml", package="RstoxData") data <- RstoxData::ReadAcoustic(example) ICESAcoustic2 <- RstoxData::ICESAcoustic(data) ICESAcousticCSV2 <- RstoxData::WriteICESAcoustic(ICESAcoustic2) expect_equal(dim(ICESAcousticCSV2[[1]]), c(19, 25)) context("test-StoxExport: ICES acoustic export example <- system.file("testresources", "ICES_Acoustic_2.xml", package="RstoxData") data <- RstoxData::ReadAcoustic(example) ICESAcoustic2 <- RstoxData::ICESAcoustic(data) ICESAcousticCSV2 <- RstoxData::WriteICESAcoustic(ICESAcoustic2) expect_equal(dim(ICESAcousticCSV2[[1]]), c(23, 25))
SWE <- function(level){ x <- NULL if(level==1){ x1 <- arcgis.se(level = level) x2 <- ourworldindata.org(id = "SWE") x <- full_join(x1, x2, by = "date") } if(level==2){ x <- arcgis.se(level = level) x$id <- id(x$state, iso = "SWE", ds = "arcgis.se", level = level) } return(x) }
setGeneric("filterOrder", def = function(object, ...){ standardGeneric("filterOrder") }) setGeneric("filterCoef", def = function(object, convention, ...){ standardGeneric("filterCoef") } ) setGeneric("filterPolyCoef", function(object, lag_0 = TRUE, ...){ standardGeneric("filterPolyCoef") }) setGeneric("filterPoly", function(object, ...){ standardGeneric("filterPoly") }) setClass("VirtualMonicFilter", contains = c("VIRTUAL")) setClass("VirtualSPFilter", contains = c("VirtualMonicFilter", "VIRTUAL")) setClass("VirtualBJFilter", contains = c("VirtualMonicFilter", "VIRTUAL")) setMethod("filterCoef", c("VirtualBJFilter", "character"), function(object, convention){ co <- filterCoef(object) switch(convention, "BJ" = , "--" = , "-" = co, "SP" = , "++" = , "+" = - co, stop("invalid value for argument `convention'.") ) } ) setMethod("filterCoef", c("VirtualSPFilter", "character"), function(object, convention){ co <- filterCoef(object) switch(convention, "BJ" = , "--" = , "-" = - co, "SP" = , "++" = , "+" = co, stop("invalid value for argument `convention'.") ) } ) setMethod("filterPolyCoef", "VirtualBJFilter", function(object, lag_0 = TRUE){ co <- filterCoef(object) if(lag_0) c(1, - co) else - co } ) setMethod("filterPolyCoef", "VirtualSPFilter", function(object, lag_0 = TRUE){ co <- filterCoef(object) if(lag_0) c(1, co) else co } ) setClass("VirtualMonicFilterSpec", contains = "VIRTUAL", slots = c(coef = "ANY", order = "numeric"), prototype = list(coef = numeric(0), order = 0) ) setMethod("filterOrder", "VirtualMonicFilterSpec", function(object) object@order ) setMethod("filterCoef", c("VirtualMonicFilterSpec", "missing"), function(object) object@coef ) setMethod("filterPoly", "VirtualMonicFilterSpec", function(object) polynom(filterPolyCoef(object))) setClass("MonicFilterSpec", contains = c("VirtualMonicFilterSpec", "VIRTUAL"), slots = c(coef = "numeric") ) setClass("BJFilter", contains = c("MonicFilterSpec", "VirtualBJFilter")) setClass("SPFilter", contains = c("MonicFilterSpec", "VirtualSPFilter")) setMethod("initialize", "MonicFilterSpec", function(.Object, coef, order, ...){ .Object <- callNextMethod() if(missing(coef)){ if(.Object@order > 0) .Object@coef <- rep(NA_real_, .Object@order) }else if(missing(order)) .Object@order <- length(.Object@coef) .Object } ) setMethod("show", signature(object = "MonicFilterSpec"), function (object) { cat("order: ", object@order, "\n") cat("Coefficients:", "\n") print(object@coef) } ) setAs("numeric", "BJFilter", function(from) new("BJFilter", coef = from)) setAs("numeric", "SPFilter", function(from) new("SPFilter", coef = from)) setAs("BJFilter", "SPFilter", function(from) new("SPFilter", coef = - from@coef)) setAs("SPFilter", "BJFilter", function(from) new("BJFilter", coef = - from@coef)) setMethod("filterCoef", c("BJFilter", "character"), function(object, convention){ switch(convention, "BJ" = , "--" = , "-" = object@coef, "SP" = , "++" = , "+" = - object@coef, stop("invalid value for argument `convention'.") ) } ) setMethod("filterCoef", c("SPFilter", "character"), function(object, convention){ switch(convention, "BJ" = , "--" = , "-" = - object@coef, "SP" = , "++" = , "+" = object@coef, stop("invalid value for argument `convention'.") ) } ) setMethod("filterPolyCoef", "BJFilter", function(object, lag_0 = TRUE){ if(lag_0) c(1, - object@coef) else - object@coef } ) setMethod("filterPolyCoef", "SPFilter", function(object, lag_0 = TRUE){ if(lag_0) c(1, object@coef) else object@coef } ) setMethod("filterPoly", "BJFilter", function(object) polynom(c(1, - object@coef)) ) setMethod("filterPoly", "SPFilter", function(object) polynom(c(1, object@coef)) ) setMethod("show", signature(object = "BJFilter"), function (object) { .reportClassName(object, "BJFilter") callNextMethod() } ) setMethod("show", signature(object = "SPFilter"), function (object) { .reportClassName(object, "SPFilter") callNextMethod() } ) setClass("VirtualArmaFilter", contains = c("VirtualMonicFilter", "VIRTUAL"), slots = c(ar = "VirtualMonicFilter", ma = "VirtualMonicFilter"), prototype = list(ar = new("BJFilter"), ma = new("SPFilter")) ) setMethod("filterOrder", "VirtualArmaFilter", function(object){ list(ar = filterOrder(object@ar), ma = filterOrder(object@ma) ) } ) setMethod("filterPoly", "VirtualArmaFilter", function(object){ list(ar = filterPoly(object@ar), ma = filterPoly(object@ma) ) } ) setMethod("filterPolyCoef", "VirtualArmaFilter", function(object, lag_0 = TRUE, ...){ list(ar = filterPolyCoef(object@ar, lag_0 = lag_0, ...), ma = filterPolyCoef(object@ma, lag_0 = lag_0, ...) ) } ) setMethod("filterCoef", c("VirtualArmaFilter", "missing"), function(object){ list(ar = filterCoef(object@ar), ma = filterCoef(object@ma) ) } ) setMethod("filterCoef", c("VirtualArmaFilter", "character"), function(object, convention){ switch(convention, "BJ" = , "--" = , "SP" = , "++" = list(ar = filterCoef(object@ar, convention = convention), ma = filterCoef(object@ma, convention = convention) ), "-+" = , "BD" = list(ar = filterCoef(object@ar, convention = "-"), ma = filterCoef(object@ma, convention = "+") ), "+-" = list(ar = filterCoef(object@ar, convention = "+"), ma = filterCoef(object@ma, convention = "-") ), "+" = , "-" = stop("invalid value for argument `convention'."), stop("invalid value for argument `convention'.") ) } ) setMethod("nSeasons", "VirtualArmaFilter", function(object) nSeasons(object@ar)) setAs("VirtualArmaFilter", "list", function(from){ filterCoef(from) } ) setMethod("show", signature(object = "VirtualArmaFilter"), function (object) { cat('\nslot "ar":\n') show(object@ar) cat('\nslot "ma":\n') show(object@ma) } ) setClass("ArmaFilter", contains = "VirtualArmaFilter", slots = c(ar = "BJFilter", ma = "SPFilter"), ) setMethod("initialize", "ArmaFilter", function(.Object, ..., ar, ma){ if(!missing(ar)) .Object@ar <- as(ar, "BJFilter") if(!missing(ma)) .Object@ma <- as(ma, "SPFilter") .Object <- callNextMethod(.Object, ...) .Object } ) setMethod("show", signature(object = "ArmaFilter"), function (object) { .reportClassName(object, "ArmaFilter") callNextMethod() } ) setClass("ArFilter", contains = "ArmaFilter" ) setClass("MaFilter", contains = "ArmaFilter" ) setMethod("initialize", "ArFilter", function(.Object, ...){ .Object <- callNextMethod() if(.Object@ma@order > 0) stop("Non-trivial moving average part.") .Object } ) setMethod("initialize", "MaFilter", function(.Object, ...){ .Object <- callNextMethod() if(.Object@ar@order > 0) stop("Non-trivial autoregressive part.") .Object } ) setClass("VirtualCascadeFilter", contains = c("VirtualMonicFilter", "VIRTUAL")) setClass("VirtualSarimaFilter", contains = c("VirtualCascadeFilter", "VIRTUAL")) setGeneric("iOrder", def = function(object){ standardGeneric("iOrder") }) setGeneric("siOrder", def = function(object){ standardGeneric("siOrder") }) setGeneric("anyUnitRoots", def = function(object){ standardGeneric("anyUnitRoots") }) setMethod("anyUnitRoots", "VirtualSarimaFilter", function(object){ iOrder(object) > 0 || siOrder(object) > 0 } ) setClass("SarimaFilter", contains = "VirtualSarimaFilter", slots = c(nseasons = "numeric", iorder = "numeric", siorder = "numeric", ar = "BJFilter", ma = "SPFilter", sar = "BJFilter", sma = "SPFilter" ), prototype = list(nseasons = NA_real_, iorder = 0, siorder = 0 ) ) setMethod("initialize", "SarimaFilter", function(.Object, ..., ar, ma, sar, sma){ .Object <- callNextMethod(.Object, ...) if(!missing(ar)) .Object@ar <- as(ar, "BJFilter") if(!missing(ma)) .Object@ma <- as(ma, "SPFilter") if(!missing(sar)) .Object@sar <- as(sar, "BJFilter") if(!missing(sma)) .Object@sma <- as(sma, "SPFilter") .Object } ) setMethod("nSeasons", "SarimaFilter", function(object) object@nseasons) setMethod("iOrder", "SarimaFilter", function(object) object@iorder) setMethod("siOrder", "SarimaFilter", function(object) object@siorder) setReplaceMethod("nSeasons", "SarimaFilter", function(object, ..., value){ object@nseasons <- value object }) setMethod("filterOrder", "SarimaFilter", function(object){ list(nseasons = object@nseasons, iorder = object@iorder, siorder = object@siorder, ar = object@ar@order, ma = object@ma@order, sar = object@sar@order, sma = object@sma@order ) } ) setMethod("filterCoef", c("SarimaFilter", "missing"), function(object){ list(nseasons = object@nseasons, iorder = object@iorder, siorder = object@siorder, ar = filterCoef(object@ar ), ma = filterCoef(object@ma ), sar = filterCoef(object@sar), sma = filterCoef(object@sma) ) } ) setMethod("filterCoef", c("SarimaFilter", "character"), function(object, convention){ co <- switch(convention, "BJ" = , "--" = , "SP" = , "++" = list(ar = filterCoef(object@ar, convention = convention), ma = filterCoef(object@ma, convention = convention), sar = filterCoef(object@sar, convention = convention), sma = filterCoef(object@sma, convention = convention) ), "-+" = , "BD" = list(ar = filterCoef(object@ar, convention = "-"), ma = filterCoef(object@ma, convention = "+"), sar = filterCoef(object@sar, convention = "-"), sma = filterCoef(object@sma, convention = "+") ), "+-" = list(ar = filterCoef(object@ar, convention = "+"), ma = filterCoef(object@ma, convention = "-"), sar = filterCoef(object@sar, convention = "+"), sma = filterCoef(object@sma, convention = "-") ), "+" = , "-" = stop("invalid value for argument `convention'."), filterCoef(object, new(convention)) ) c(list(nseasons = object@nseasons, iorder = object@iorder, siorder = object@siorder), co) } ) setMethod("filterPoly", "SarimaFilter", function(object){ nseas <- object@nseasons b1 <- polynom(c(0,1)) arpoly <- filterPoly(object@ar ) mapoly <- filterPoly(object@ma ) aripoly <- (1-b1)^object@iorder if(is.na(nseas)){ sarpoly <- smapoly <- sarpoly_expanded <- smapoly_expanded <- saripoly_expanded <- polynom(1) fullarpoly <- arpoly * aripoly fullmapoly <- mapoly }else{ bs <- polynom(c(rep(0, nseas), 1)) sarpoly <- filterPoly(object@sar) smapoly <- filterPoly(object@sma) sarpoly_expanded <- predict(sarpoly,bs) smapoly_expanded <- predict(smapoly,bs) saripoly_expanded <- (1-bs)^object@siorder fullarpoly <- arpoly * sarpoly_expanded * aripoly * saripoly_expanded fullmapoly <- mapoly * smapoly_expanded } list(nseasons = nseas, iorder = object@iorder, siorder = object@siorder, ipoly = aripoly, sipoly = saripoly_expanded, arpoly = arpoly, mapoly = mapoly, sarpoly = sarpoly_expanded, smapoly = smapoly_expanded, fullarpoly = fullarpoly, fullmapoly = fullmapoly, core_sarpoly = sarpoly, core_smapoly = smapoly ) } ) setMethod("filterPolyCoef", "SarimaFilter", function(object, lag_0 = TRUE){ res <- filterPoly(object) polycomp <- grep("poly", names(res), value = TRUE) for(nam in polycomp){ res[[nam]] <- coef(res[[nam]]) } if(!lag_0){ for(nam in polycomp){ res[[nam]] <- res[[nam]][-1] } } res } ) summary.SarimaFilter <- function(object, ...){ .reportClassName(object, "SarimaFilter") objpoly <- filterPoly(object) res <- c( if(!is.na(objpoly$nseasons)) paste0("Period: ", objpoly$nseasons) else "" , "" , "Non-stationary part of model" , paste0(" Order of differencing: ", objpoly$iorder) , paste0(" Order of seasonal differencing: ", objpoly$siorder) , paste0(" Differencing polynomial (ari): ", .capturePrint(objpoly$ipoly)) , paste0(" Seasonal differencing polynomial (sari): ", .capturePrint(objpoly$sipoly)) , "" , "Stationary part of model" , .formatNameNumeric(" ar coefficients: ", filterCoef(object@ar)) , .formatNameNumeric(" ma coefficients: ", filterCoef(object@ma)) , .formatNameNumeric(" seasonal ar coefficients: ", filterCoef(object@sar)) , .formatNameNumeric(" seasonal ma coefficients: ", filterCoef(object@sma)) , "" , paste0(" ar polynomial (non-seasonal): ", .capturePrint(objpoly$arpoly)) , paste0(" ma polynomial (non-seasonal): ", .capturePrint(objpoly$mapoly)) , paste0(" seasonal ar polynomial: ", .capturePrint(objpoly$sarpoly)) , paste0(" seasonal ma polynomial: ", .capturePrint(objpoly$smapoly)) , "" , "Fully expanded polynomials:" , paste0(" full ar polynomial: ", .capturePrint(objpoly$fullarpoly)) , paste0(" full ma polynomial: ", .capturePrint(objpoly$fullmapoly)) , "") cat(res, sep="\n") invisible(objpoly) } setMethod("show", signature(object = "SarimaFilter"), function (object){ .reportClassName(object, "SarimaFilter") seasflag <- !is.na(object@nseasons) if(seasflag) cat("Period: ", object@nseasons, "\n") else cat("Non-seasonal model", "\n") cat("Order of differencing: ", object@iorder, "\n") if(seasflag) cat("Order of seasonal differencing: ", object@siorder, "\n") cat(c("", .formatNameNumeric("ar coefficients: ", filterCoef(object@ar)), .formatNameNumeric("ma coefficients: ", filterCoef(object@ma)) ), sep = "\n") if(seasflag) cat(.formatNameNumeric("seasonal ar coefficients: ", filterCoef(object@sar)), .formatNameNumeric("seasonal ma coefficients: ", filterCoef(object@sma)) , sep = "\n") invisible(NULL) } )
prunelev<-function(bt,lambda=NULL,n=NULL){ len<-length(bt$mean) bt$mean<-matrix(1,len,1) if (!is.null(lambda)) bt$ssr<-exmavec(bt$volume,bt$nelem,n,lambda) ini1<-preprocess(bt$ssr,bt$left,bt$right,bt$mean) bt$S<-t(ini1$S) bt$mean<-t(ini1$mean) bt$left<-ini1$left bt$right<-ini1$right treeseq<-pruseqlev(bt) return(treeseq) }
itcONE11 = function(varpar=list(K=1000000, DH=-20000, HD=0.1, N=0.5),stapar=list(P0=0.01, L0=0, Asyr=0.2, V0=1.4195), injV0){ par3=XMt_func(stapar, injV0); XMt0=par3$XMt; Pe = varpar$N*stapar$P0; Km=varpar$K/1E3; Pt=1.0/(1.0/Pe+XMt0/varpar$N/stapar$Asyr); Fi=exp(-injV0/stapar$V0/1E3); Pp=Pt/Fi; At=Pt*XMt0/varpar$N; Ap=stapar$Asyr*(1.0-Pp/Pe); a=1.0+(Km*Ap)+(Km*Pp); b=4.0*Km*Km*Pp*Ap; PAp=(a-sqrt((a*a)-b))/(2*Km); a=1.0+(Km*At)+(Km*Pt); b=4.0*Km*Km*Pt*At; PAt=(a-sqrt((a*a)-b))/(2*Km); (stapar$V0*(varpar$DH*(PAt-Fi*PAp))+varpar$HD)/injV0/stapar$Asyr*1E3; }
yield.dollar = function(cf, times, start, end, endtime){ all=list(cf,times,start,end,endtime) if(any(lapply(all,is.null)==T)) stop("Cannot input any variables as NULL.") one=list(start,end,endtime) if(any(lapply(one,length)!= 1)) stop("start, end, and endtime must be of length 1.") if(length(cf) != length(times)){ stop('length of vectors "cf" and "times" must be equal')} if(any(is.na(cf) | any(is.na(times)) | any(is.na(c(start,end,endtime))))) stop("Cannot input any variables as NA.") if(!is.vector(cf) | !is.vector(times) | !is.numeric(cf) | !is.numeric(times)) stop('variable "cf" and "times" must be numeric vector') num2=list(start,end,endtime) na.num2=num2[which(lapply(num2,is.na)==F)] if(any(lapply(na.num2,is.numeric)==F)) stop("All variables must be numeric.") if(any(cf==Inf) | any(times==Inf) | any(c(start,end,endtime)==Inf)) stop("Cannot input any variables as infinite.") if(any(times<0) | endtime <=0) stop('"times" vector and "endtime" must be positive') if(any(times>endtime)) stop('time of comparison (endtime) must be larger than any number in vector "times"') if(length(cf) != length(times)) stop("length of cashflow vector and times vector must be equal") I = end - start - sum(cf) runsum=0 for(i in 1:length(cf)){ runsum = runsum + cf[i]*(endtime-times[i])} yield = I/(start*endtime+runsum) return(yield) }
boxplot.lengths <- function (x, ..., log = FALSE, zeros.rm = TRUE) { newlen <- x$length + 0 if (zeros.rm & x$zeros) { newlen <- x$length + x$maxcens } if (log) newlen <- log(newlen) boxplot(newlen ~ x$categories, ...) }
print.survHE <- function(x,mod=1,...) { exArgs <- list(...) availables <- load_availables() if(!exists("digits",where=exArgs)){digits=6} else {digits=exArgs$digits} if(!exists("original",where=exArgs)){original=FALSE} else {original=exArgs$original} if(exists("orig",exArgs)){original=exArgs$orig} if(original==TRUE) { do.call( paste0("original_table_",x$method), args=list(x,mod,digits) ) } else { res=do.call( paste0("get_stats_",x$method), args=list(x,mod) ) format_table(x,mod,res,digits) } }
library(mizer) rm(list=ls()) comm_params <- set_community_model(max_w=50e3, beta=100, sigma=1.3, h=20, alpha=0.17, n=0.75, q=0.8, z0=0.2, f0=0.6, r_pp=4, kappa=5, rec_mult=0.01) comm_time_sim <- 800 comm_sim0 <- project(comm_params, t_max=comm_time_sim, effort=0, dt=0.1) plot(comm_sim0) plotBiomass(comm_sim0, start_time=700) comm_sim1 <- project(comm_params, t_max=comm_time_sim, effort=1.5, dt=0.1) plot(comm_sim1) plotBiomass(comm_sim1, start_time=700) trait_params <- set_trait_model(max_w=100e3, no_sp=10, min_w_inf=5, max_w_inf=100e3*0.9, beta=100, sigma=1.3, h=20, alpha=0.6, n=0.75, q=0.8, z0pre=2, f0=0.6, ks=2.4, r_pp=4, kappa=5, k0=5000, min_w_pp = 1e-10) trait_time_sim <- 200 trait_sim0 <- project(trait_params, t_max=trait_time_sim, effort=0, dt=1) plot(trait_sim0) plotBiomass(trait_sim0, start_time=150) trait_sim1 <- project(trait_params, t_max=trait_time_sim, effort=0.6, dt=1) plot(trait_sim1) plotBiomass(trait_sim1, start_time=150) data(NS_species_params) data(inter) NS_species_params$knife_edge_size <- 1000 ms_params <- MizerParams(NS_species_params, inter, max_w=1e6, kappa=9.27e10, q=0.8, n=2/3, z0pre=0.6, min_w_pp = 1e-10) ms_time_sim <- 150 ms_sim0 <- project(ms_params, t_max=ms_time_sim, effort=0) plot(ms_sim0) ms_sim1 <- project(ms_params, t_max=ms_time_sim, effort=0.75) plot(ms_sim1) dim(comm_sim1@n) dimnames(comm_sim1@n) comm_sim1@params@w comm_sim1@params@w_full no_avg_steps <- 400 avg_steps_indices <- (comm_time_sim-no_avg_steps+2):(comm_time_sim+1) comm0_npp <- apply(comm_sim0@n_pp[avg_steps_indices,],2,mean) * comm_sim0@params@w_full comm0_n <- apply(comm_sim0@n[avg_steps_indices,,],2,mean) * comm_sim0@params@w comm1_n <- apply(comm_sim1@n[avg_steps_indices,,],2,mean) * comm_sim1@params@w comm_relative_abundance <- comm1_n / comm0_n trait0_npp <- trait_sim0@n_pp[trait_time_sim+1,] * trait_sim0@params@w_full trait0_n <- sweep(trait_sim0@n[trait_time_sim+1,,],2,trait_sim0@params@w,"*") trait1_n <- sweep(trait_sim1@n[trait_time_sim+1,,],2,trait_sim1@params@w,"*") trait0_n_total <- apply(trait0_n,2,sum) trait1_n_total <- apply(trait1_n,2,sum) trait_relative_abundance <- trait1_n_total / trait0_n_total ms0_npp <- ms_sim0@n_pp[ms_time_sim+1,] * ms_sim0@params@w_full ms0_n <- sweep(ms_sim0@n[ms_time_sim+1,,],2,ms_sim0@params@w,"*") ms1_n <- sweep(ms_sim1@n[ms_time_sim+1,,],2, ms_sim1@params@w,"*") ms0_n_total <- apply(ms0_n,2,sum) ms1_n_total <- apply(ms1_n,2,sum) ms_relative_abundance <- ms1_n_total / ms0_n_total cc_index <- which(comm_sim0@params@w_full == comm_sim0@params@w[1]) comm_base <- (comm_sim0@params@w_full * comm_sim0@params@cc_pp)[cc_index] cc_index <- which(trait_sim0@params@w_full == trait_sim0@params@w[1]) trait_base <- (trait_sim0@params@w_full * trait_sim0@params@cc_pp)[cc_index] cc_index <- which(ms_sim0@params@w_full == ms_sim0@params@w[1]) ms_base <- (ms_sim0@params@w_full * ms_sim0@params@cc_pp)[cc_index] width <- 14 height <- 7 png(filename="Figure1.png", width = width, height = height, units="cm",res=800, pointsize=8) nf <- layout(matrix(1:6,2,3,byrow=TRUE), rep(width/3,3),c(3/6,3/6)*height,TRUE) ylim <- c(1e-10,10) xlim <- c(1e-3,1e4) cascade_ylim <- c(0.1,10) fat_lwd <- 2 fished_lty <- 3 resource_colour <- "green" resource_lwd <- 1 par(mar=c(1,5,2,1)) plot(x=comm_sim0@params@w, y= comm0_n / comm_base, log="xy", type="n", ylab="Biomass relative to carrying capacity", xlim=xlim, ylim=ylim, main = "(a)", xlab="") lines(x=comm_sim0@params@w_full, y= comm0_npp / comm_base, col=resource_colour, lwd=resource_lwd) lines(x=comm_sim0@params@w, y=comm0_n / comm_base, col="red", lwd=fat_lwd) lines(x=comm_sim0@params@w, y=comm1_n / comm_base, col="blue", lwd=fat_lwd, lty=fished_lty) plot(x=trait_sim0@params@w, y= trait0_n_total / trait_base, log="xy", type="n", ylab="", xlim=xlim, ylim=ylim, main = "(b)", xlab="") lines(x=trait_sim0@params@w_full, y= trait0_npp / trait_base, col=resource_colour, lwd=resource_lwd) lines(x=trait_sim0@params@w, y=trait0_n_total / trait_base, col="red", lwd=fat_lwd) lines(x=trait_sim1@params@w, y=trait1_n_total / trait_base, col="blue", lwd=fat_lwd, lty=fished_lty) for (i in 1:10){ lines(x=trait_sim0@params@w, y=trait0_n[i,] / trait_base) } plot(x=ms_sim0@params@w, y= ms0_n_total / ms_base, log="xy", type="n", ylab="", xlim=xlim, ylim=ylim, main = "(c)", xlab="") lines(x=ms_sim0@params@w_full, y=ms0_npp / ms_base, col=resource_colour, lwd=resource_lwd) lines(x=ms_sim0@params@w, y=ms0_n_total / ms_base, col="red", lwd=fat_lwd) lines(x=ms_sim1@params@w, y=ms1_n_total / ms_base, col="blue", lwd=fat_lwd, lty=3) for (i in 1:12){ lines(x=ms_sim0@params@w, y=ms0_n[i,] / ms_base) } par(mar=c(5,5,5,1)) plot(x=comm_sim0@params@w, y=comm_relative_abundance, log="xy", type="n", ylab="Relative abundance", xlim=xlim, ylim=cascade_ylim, main = "", xlab="Body mass (g)", yaxt="n") axis(side = 2, at=c(0.2,1,5)) lines(x=comm_sim0@params@w, y=comm_relative_abundance) lines(x=c(min(comm_sim0@params@w),max(comm_sim0@params@w)), y=c(1,1),lty=2) lines(x=c(1000,1000),y=c(1e-20,1e20),lty=3) plot(x=trait_sim0@params@w, y=trait_relative_abundance, log="xy", type="n", ylab="", xlim=xlim, ylim=cascade_ylim, main = "", xlab="Body mass (g)", yaxt="n") axis(side = 2, at=c(0.2,1,5)) lines(x=trait_sim0@params@w, y=trait_relative_abundance) lines(x=c(min(trait_sim0@params@w),max(trait_sim0@params@w)), y=c(1,1),lty=2) lines(x=c(1000,1000),y=c(1e-20,1e20),lty=3) plot(x=ms_sim0@params@w, y=ms_relative_abundance, log="xy", type="n", xlab = "Body mass (g)", ylab="", xlim=xlim, ylim=cascade_ylim, main = "", yaxt="n") axis(side = 2, at=c(0.2,1,5)) lines(x=ms_sim0@params@w, y=ms_relative_abundance) lines(x=c(min(ms_sim0@params@w),max(ms_sim0@params@w)), y=c(1,1),lty=2) lines(x=c(1000,1000),y=c(1e-20,1e20),lty=3) dev.off() rm(list=ls()) library(mizer) data(NS_species_params) data(inter) NS_species_params$species NS_species_params$gear <- c("Industrial", "Industrial", "Pelagic", "Pelagic", "Beam", "Otter", "Beam", "Otter", "Beam", "Otter", "Otter", "Otter") NS_species_params$knife_edge_size <- NA NS_species_params[NS_species_params$gear == "Industrial", "knife_edge_size"] <- 10 NS_species_params[NS_species_params$gear == "Pelagic", "knife_edge_size"] <- 80 NS_species_params[NS_species_params$gear == "Otter", "knife_edge_size"] <- 270 NS_species_params[NS_species_params$gear == "Beam", "knife_edge_size"] <- 155 NS_species_params NS_params <- MizerParams(NS_species_params, inter) NS_params@catchability time_to_equib <- 100 NS_equib <- project(NS_params, t_max=time_to_equib) plot(NS_equib) n_equib <- NS_equib@n[time_to_equib+1,,] n_pp_equib <- NS_equib@n_pp[time_to_equib+1,] gear_names <- c("Pelagic","Beam","Otter","Industrial") project_time <- 100 fishing_effort <- array(0, dim=c(project_time, 4), dimnames=list(time=1:project_time, gear=gear_names)) fishing_effort[,"Pelagic"] <- c(rep(0,10),seq(from = 0, to = 1, length = 10), rep(1,80)) fishing_effort[,"Beam"] <- c(rep(0,30),seq(from = 0, to = 0.75, length = 10), rep(0.75,60)) fishing_effort[,"Otter"] <- c(rep(0,50),seq(from = 0, to = 0.9, length = 10), rep(0.9,40)) fishing_effort[,"Industrial"] <- c(rep(0,70),seq(from = 0, to = 1.5, length = 10), rep(1.5,20)) plot(x = 1:project_time, y = seq(from=0,to=1,length=project_time), type="n", xlab = "Years", ylab="Fishing effort", ylim=c(0,1.5)) for (i in 1:4){ lines(x=1:project_time, y = fishing_effort[,i], lty=i) } legend(x="bottomright",legend=c("Pelagic", "Beam", "Otter", "Industrial"), lty=1:4) NS_sim <- project(NS_params, effort=fishing_effort, initial_n = n_equib, initial_n_pp = n_pp_equib) plot(NS_sim) plotBiomass(NS_sim) ssb <- getSSB(NS_sim) rescale_ssb <- sweep(ssb,2,ssb[1,],"/") yield <- getYieldGear(NS_sim) max_yield <- apply(yield,c(2,3),max) rescale_yield <- sweep(yield,c(2,3), max_yield, "/") yield[yield==0] <- NA rescale_yield[rescale_yield==0] <- NA min_w <- 10 max_w <- 5000 threshold_w <- 100 lfi <- getProportionOfLargeFish(NS_sim, min_w=min_w, max_w=max_w, threshold_w=threshold_w) mw <- getMeanWeight(NS_sim, min_w=min_w, max_w=max_w) mmw <- getMeanMaxWeight(NS_sim, min_w=min_w, max_w=max_w, measure="biomass") slope <- getCommunitySlope(NS_sim, min_w=min_w, max_w=max_w)[,"slope"] rescale_lfi <- lfi / lfi[1] rescale_mw <- mw / mw[1] rescale_mmw <- mmw / mmw[1] gear_lty <- 1:4 names(gear_lty) <- gear_names species_names <- as.character(NS_params@species_params$species) species_lty <- rep(NA,12) names(species_lty) <- species_names cols <- c("black","blue","magenta","green","red") species_col <- rep(NA,12) names(species_col) <- species_names for (i in gear_names){ gear_idx <- (NS_params@species_params$gear == i) species_col[NS_params@species_params$species[gear_idx]] <- cols[1:(sum(gear_idx))] species_lty[NS_params@species_params$species[gear_idx]] <- 1 } width <- 7 height <- 20 add_effort_lines <- function(){ lwd <- 0.5 lines(x=c(11,11), y=c(-1e20,1e20), lty=gear_lty[1], lwd=lwd) lines(x=c(31,31), y=c(-1e20,1e20), lty=gear_lty[2], lwd=lwd) lines(x=c(51,51), y=c(-1e20,1e20), lty=gear_lty[3], lwd=lwd) lines(x=c(71,71), y=c(-1e20,1e20), lty=gear_lty[4], lwd=lwd) } png(filename="Figure2.png", width = width, height = height, units="cm",res=1000, pointsize=8) rel_heights <- c(0.7,rep(0.5,8),0.5,0.8,1) heights = (height / sum(rel_heights)) * rel_heights nf <- layout(matrix(1:length(rel_heights),length(rel_heights),1,byrow=TRUE), widths = width, heights=heights,TRUE) right_margin <- 4 left_margin <- 4.5 legend_txt_cex <- 0.7 leg_line <- 0.3 seg_len <- 2.5 leg_bty <- "n" leg_box_lwd <- 0 par(mar=c(0,left_margin,0.5,right_margin)) plot(x = 1:project_time, y=1:project_time, type="n", ylim=c(0,max(fishing_effort)), xlab="", ylab=expression(Effort~(y^{-1})), xaxt="n") text(x=5,y=1.4,labels="(a)") for (i in gear_names){ lines(x = 1:project_time, y=NS_sim@effort[,i], lty=gear_lty[i]) } add_effort_lines() legend(x="bottomright", legend = gear_names, lty=gear_lty, cex=legend_txt_cex, pt.lwd=leg_line, seg.len=seg_len, bty=leg_bty, box.lwd=leg_box_lwd) rescale_yield_min <- min(rescale_yield[rescale_yield>0], na.rm=TRUE) rescale_yield_max <- max(rescale_yield[rescale_yield>0], na.rm=TRUE) main_labels <- c("(b)","(c)","(d)","(e)") names(main_labels) <- gear_names for (gear in gear_names){ species_in_gear <- NS_params@species_params$species[NS_params@species_params$gear==gear] par(mar=c(0,left_margin,0,right_margin)) plot(x = 1:project_time, y=1:project_time, type="n", ylim=c(rescale_yield_min, rescale_yield_max), ylab="", xlab="", xaxt="n", yaxt="n") axis(4) text(x=5,y=0.9,labels=main_labels[gear]) mtext(gear, side=2, line=1, cex=0.6) if (gear == gear_names[2]){ mtext("Relative Yield", side=4, line=3, cex=0.6, adj=-3) } add_effort_lines() for (i in species_in_gear){ lines(x = 1:project_time, y=rescale_yield[1:project_time,gear,i], col=species_col[i], lty=species_lty[i]) } legend(x="bottomright", legend=species_in_gear, lty=species_lty[species_in_gear], col=species_col[species_in_gear], cex = legend_txt_cex, ncol=1, pt.lwd=leg_line, seg.len = seg_len, bty=leg_bty, box.lwd=leg_box_lwd) } main_labels <- c("(f)","(g)","(h)","(i)") names(main_labels) <- gear_names for (gear in gear_names){ species_in_gear <- NS_params@species_params$species[NS_params@species_params$gear==gear] par(mar=c(0,left_margin,0,right_margin)) plot(x = 1:project_time, y=1:project_time, type="n", ylim=c(min(rescale_ssb),max(rescale_ssb)), ylab="", xlab="", xaxt="n") if (gear == gear_names[2]){ mtext("Relative SSB", side=2, line=3, cex=0.6, adj=-3) } text(x=5,y=1.75,labels=main_labels[gear]) mtext(gear, side=4, line=1, cex=0.6) add_effort_lines() for (i in species_in_gear){ lines(x = 1:project_time, y=rescale_ssb[ ,i], col=species_col[i], lty=species_lty[i]) } } par(mar=c(0,left_margin,0,right_margin)) ylim <- range(slope) plot(x = 1:project_time, y=1:project_time, type="n", ylab="", xlab="Years", ylim=ylim, yaxt="n", xaxt="n") axis(4) text(x=5,y=-1.5,labels="(j)") mtext("Community slope", side=4, line=3, cex=0.6) add_effort_lines() lines(x = 1:project_time, y = slope[2:(project_time+1)]) par(mar=c(4,left_margin,0,right_margin)) ylim <- c(0,max(rescale_lfi,rescale_mw, rescale_mmw, slope)) plot(x = 1:project_time, y=1:project_time, type="n", ylab="Relative metrics", xlab="Years", ylim=ylim) text(x=5,y=2.5,labels="(k)") lines(x = 1:project_time, y = rescale_lfi[2:(project_time+1)], col=1) lines(x = 1:project_time, y = rescale_mw[2:(project_time+1)], col=2) lines(x = 1:project_time, y = rescale_mmw[2:(project_time+1)], col=3) add_effort_lines() legend(x="bottomright", legend = c("LFI", "MW", "MMW"), lty=1, col=c(1,2,3), cex = legend_txt_cex, ncol=1, pt.lwd=leg_line, seg.len = seg_len, bty=leg_bty, box.lwd=leg_box_lwd) biomass_time <- sweep(apply(NS_sim@n[c(2,21,41,61,81),,],c(1,3),sum),2,NS_sim@params@w,"*") xlim <- c(1,5e4) ylim <- c(5e5,max(biomass_time))/1000 par(mar=c(4,left_margin,1,right_margin)) plot(x=NS_sim@params@w, y = NS_sim@params@w, type="n", ylab="Total biomass (kg)", xlab = "Size (g)", log="xy", ylim = ylim, xlim=xlim) text(x=2,y=1e9,labels="(l)") cols <- c(1,2,3,4,6) for (i in 1:5){ lines(x=NS_sim@params@w, y = biomass_time[i,]/1000, col=cols[i]) } legend(x="bottomleft", legend=c("Unfished", "Year 20: Pelagic", "Year 40: Beam", "Year 60: Otter", "Year 80: Industrial"), lty=1, col=cols, cex = legend_txt_cex, pt.lwd=leg_line, seg.len = seg_len, bty=leg_bty, box.lwd=leg_box_lwd) dev.off()
if(getRversion() >= "2.15.1"){ utils::globalVariables(c("day", "month", "year", "flow", "tp", "baseflow", ".warned"), add = TRUE) } createlfobj <- function(x, ...){ UseMethod("createlfobj") } createlfobj.lfobj <- function(x, hyearstart = NULL, baseflow = NULL, meta = NULL, ...){ if(is.null(baseflow)){ baseflow <- "baseflow" %in% names(x) } if(is.null(meta)){ meta <- attr(x, "lfobj") } dat <- createlfobj.data.frame(x = x, hyearstart = hyearstart, baseflow = baseflow, meta = meta, ...) return(dat) } createlfobj.ts <- function(x, startdate, dateformat = "%d/%m/%Y", ...){ start <- as.Date(startdate, dateformat) time <- seq(from = start, along.with = x, by = "days") df <- data.frame(strsplit_date(time), flow = as.vector(x)) dat <- createlfobj(x = df, ...) return(dat) } createlfobj.data.frame <- function(x, hyearstart = NULL, baseflow = TRUE, meta = list(), ...){ cols <- c("day", "month", "year", "flow") if(!all(cols %in% names(x))) { stop("Your data frame must contain colums named", paste(shQuote(cols), collapse = ", "), "! Please look at the help files for more information.") } if(!(is.null(hyearstart) || hyearstart %in% 1:12)){ stop("if set, hyearstart must be an integer between 1 and 12") } if((is.null(hyearstart))){ hyearstart <- hyear_start(x) } meta <- as.list(meta) meta[["hyearstart"]] <- hyearstart x <- as.data.frame(x) dat <- x[, cols] time <- time.lfobj(x) fullseq <- seq(from = min(time), to = max(time), by = "day") missing <- fullseq[!fullseq %in% time] if(length(missing)) { warning("Irregular time series provided. Missing obervations were padded with NAs.") gaps <- data.frame(strsplit_date(missing), flow = NA) dat <- rbind(dat, gaps) } dat$hyear <- as.numeric(as.character(water_year(time.lfobj(dat), origin = hyearstart))) if(is.unsorted(time) || length(missing)) dat <- dat[order(c(time, missing)), ] rownames(dat) <- NULL if(baseflow) dat$baseflow <- baseflow(dat$flow, ...) attr(dat, "lfobj") <- meta class(dat) <- c("lfobj", "data.frame") return(dat) } as.lfobj <- function(x, ...){ UseMethod("as.lfobj") } as.lfobj.xts <- function(x, ...) { if(!is.null(ncol(x)) && ncol(x) != 1) stop("object with one column expected.") df <- data.frame(strsplit_date(time(x)), flow = as.vector(x)) dat <- createlfobj(x = df, ...) return(dat) } as.lfobj.zoo <- function(x, ...) { as.lfobj.xts(x, ...) } "[.lfobj" <- function (x, i, j, drop = TRUE) { y <- "[.data.frame"(x, i, j, drop) attr(y, "lfobj") <- attr(x, "lfobj") return(y) } time.lfobj <- function(x) { with(x, as.Date(paste(year, month, day, sep = "-"))) } lfcheck <- function(lfobj){ if(!is.lfobj(lfobj)){ stop("This functions is designed for objects of the class 'lfobj'. ", "Please use 'createlfobj()' or see '?createlfobj' for more information") } } is.lfobj <- function(x) { inherits(x, "lfobj") & all(c("day", "month", "year", "flow", "hyear") %in% colnames(x)) }
globalVariables(c("ic", "mods", "k", "loss_index", "set", "pow_sc", "pow_adapt", "_DF_", "_IND_COL_")) other_if_null <- function(x, other) `if`(is.null(x), other, x) block_size <- function(n, ncores = 1) { block.max <- getOption("bigstatsr.block.sizeGB") / ncores max(1, floor(block.max * 1024^3 / (8 * n))) } CutBySize <- function(m, block.size, nb = ceiling(m / block.size)) { bigparallelr::split_len(m, nb_split = nb) } seq2 <- bigparallelr::seq_range bigparallelr::rows_along bigparallelr::cols_along big_increment <- function(X, add, use_lock = FALSE) { if (use_lock) { locked <- bigparallelr::lock(X$backingfile) on.exit(bigparallelr::unlock(locked), add = TRUE) } if (is.matrix(add)) incr_FBM_mat(X, add) else incr_FBM_vec(X, add) } covar_from_df <- function(df) { assert_class(df, "data.frame") if (is.null(names(df))) names(df) <- paste0("V", seq_along(df)) stats::model.matrix.lm(~ ., data = df, na.action = "na.pass")[, -1, drop = FALSE] } as_scaling_fun <- function(center.col, scale.col, ind.col = seq_along(center.col)) { assert_lengths(center.col, scale.col, ind.col) e <- new.env(parent = baseenv()) assign("_DF_", data.frame(center = center.col, scale = scale.col), envir = e) assign("_IND_COL_", ind.col, envir = e) f <- function(X, ind.row, ind.col) { ind <- match(ind.col, `_IND_COL_`) `_DF_`[ind, ] } environment(f) <- e f }
SVM.Regression.Config <- setClass("SVM.Regression.Config", slots = c(cost="numeric", epsilon="numeric", kernel="character") , validity = function(object) { if (object@cost>=0 && object@epsilon>0 && object@kernel %in% c("linear","polynomial","radial","sigmoid")) TRUE else "invalid parameters" } , contains = "Regression.Config" ) SVM.Regression.FitObj <- setClass("SVM.Regression.FitObj", contains = "Regression.FitObj") make.configs.svm.regression <- function(df=expand.grid(cost=c(0.1,0.5,1.0,5.0,10,50,75,100), epsilon=c(0.1,0.25), kernel="radial")) { ret <- lapply(1:nrow(df), function(i) { SVM.Regression.Config(cost=df$cost[i], epsilon=df$epsilon[i], kernel=as.character(df$kernel[i])) }) } setMethod("BaseLearner.Fit", "SVM.Regression.Config", function(object, formula, data, tmpfile=NULL, print.level=1) { respVar <- all.vars(formula)[1] y <- data[,respVar] est <- svm(formula, data, kernel=object@kernel, cost=object@cost, epsilon=object@epsilon) pred <- as.vector(predict(est)) if (!is.null(tmpfile)) { save(est, file=tmpfile, compress=FALSE) rm(est); gc() } ret <- SVM.Regression.FitObj(config=object , est=if (is.null(tmpfile)) est else tmpfile , pred=pred) return (ret) } ) predict.SVM.Regression.FitObj <- function(object, newdata=NULL, ...) { if (is.null(newdata)) return (object@pred) if (is.character(object@est)) object@est <- load.object(object@est) newpred <- as.vector(predict(object@est, newdata=newdata, na.action=na.pass)) return (newpred) }
Mstep.mfa <- function(Y, g, q, pivec, B, mu, D, sigma_type, D_type, tau, ...) { p <- ncol(Y) n <- nrow(Y) pivec <- t(colSums(tau) / n) for (i in 1:g) mu[, i] <- matrix(colSums(sweep(Y, MARGIN=1, tau[, i], '*'))) / sum(tau[, i]) tau <- tau.mfa(Y = Y, g = g, q = q, pivec = pivec, B = B, mu = mu, D = D, sigma_type = sigma_type, D_type = D_type) if (sigma_type == 'common') { inv_D <- diag(1 / diag(D)) B_inv_D <- B * diag(inv_D) beta <- (inv_D - B_inv_D %*% (chol.inv(diag(q) + t(B_inv_D) %*% B)) %*% t(B_inv_D)) %*% B W <- (diag(q) - t(beta) %*% B) V <- matrix(0, nrow = p, ncol = p) for(i in 1 : g) { Ymu <- sweep(Y, 2, mu[, i, drop=FALSE], '-') V <- V + t(Ymu) %*% sweep(Ymu, 1, tau[, i], '*') } B <- try(V %*% beta %*% solve(n * W + t(beta) %*% V %*% beta)) if(any(class(B) %in% 'try-error')) { ERR <- "inversion of a singular matrix" class(ERR) <- "error" return(ERR) } D <- diag(diag(V) + rowSums(B %*% (n * W + t(beta) %*% V %*% beta) * B) - 2 * diag(B %*% t(beta) %*% V)) / n } if(sigma_type == "unique") { if (D_type == "unique") { for(i in 1 : g) { inv_D <- diag(1 / diag(D[,, i])) B_inv_D <- B[,, i] * diag(inv_D) beta <- (inv_D - B_inv_D %*% (chol.inv(diag(q) + t(B_inv_D) %*% B[,, i])) %*% t(B_inv_D)) %*% B[,, i] Ymu <- sweep(Y, 2, mu[, i, drop=FALSE], '-') V <- t(Ymu) %*% sweep(Ymu, 1, tau[, i], '*') W <- diag(q) - t(beta) %*% B[,, i] tau_i <- sum(tau[,i]) B2 <- try(solve(W * tau_i + t(beta) %*% V %*% beta)) if(any(class(B2) %in% 'try-error')) { ERR <- "inversion of a singular matrix" class(ERR) <- "error" return(ERR) } B[,, i] <- V %*% beta %*% B2 D[,, i] <- diag((diag(V) - 2 * diag(B[,, i] %*% t(beta) %*% V) + rowSums((B[,, i] %*% (W * tau_i + t(beta) %*% V %*% beta)) * B[,, i])) / tau_i) } } if (D_type == "common") { inv_D <- diag(1 / diag(D)) D <- array(NA, c(p, p, g)) for (i in 1 : g) { B_inv_D <- sweep(as.matrix(B[,, i]), 1, diag(inv_D), "*") beta <- (inv_D - B_inv_D %*% (chol.inv(diag(q) + t(B_inv_D) %*% B[,, i])) %*% t(B_inv_D)) %*% B[,, i] Ymu <- sweep(Y, 2, mu[, i, drop = FALSE], '-') V <- t(Ymu) %*% sweep(Ymu, 1, tau[, i], '*') W <- diag(q) - t(beta) %*% B[,, i] tau_i <- sum(tau[, i]) B2 <- try(solve(W * tau_i + t(beta) %*% V %*% beta)) if(any(class(B2) %in% 'try-error')) { ERR <- "inversion of a singular matrix" class(ERR) <- "error" return(ERR) } B[,, i] <- V %*% beta %*% B2 D[,, i] <- diag(diag(V) - 2 * diag(B[,, i] %*% t(beta) %*% V) + rowSums((B[,, i] %*% (W * tau_i + t(beta) %*% V %*% beta)) * B[,, i])) } D <- diag(diag(apply(D, c(1, 2), sum))/n) } } model <- list(g = g, q = q, pivec = pivec, B = B, mu = mu, D = D, sigma_type = sigma_type, D_type = D_type) class(model) <- "mfa" return(model) }
predict.bcgam <- function(object, newdata, interval=c("credible"), level=0.95, parameter=c("mu"), ...) { tt <- terms(object) if (!inherits(object, "bcgam")) warning("calling predict.bcgam(<fake-bcgam-object>) ...") if (missing(newdata) || is.null(newdata)) { mm <- X <- model.matrix(object) mmDone <- TRUE offset <- object$offsetn } else { Terms <- delete.response(tt) m <- model.frame(Terms, newdata, na.action = na.pass, xlev = object$levels) if (!is.null(cl <- attr(Terms, "dataClasses"))) .checkMFClasses(cl, m) X <- model.matrix(Terms, m, contrasts.arg = object$contrasts) offset <- rep(0, nrow(X)) if (!is.null(off.num <- attr(tt, "offset"))) for (i in off.num) offset <- offset + eval(attr(tt, "variables")[[i + 1]], newdata) if (!is.null(object$call$offset)) offset <- offset + eval(object$call$offset, newdata) mmDone <- FALSE } n=length(object$y) L=length(object$xmat)/n delta.newdata<-NULL incr<-NULL decr<-NULL zmatb.newdata<-NULL xmat.newdata<-cbind(X) no.rows=dim(newdata)[1] v=1:no.rows*0+1 for(i in 1:L){ Xi=X[,object$ind_nonparam[i]] if(object$shapes[i]==1){ delta.newdata=rbind( delta.newdata,monincr(Xi,object$knots[[i]])$sigma-object$center.delta[[i]] )} if(object$shapes[i]==2){ delta.newdata=rbind( delta.newdata,mondecr(Xi,object$knots[[i]])$sigma-object$center.delta[[i]] )} if(object$shapes[i]==3){ delta.i=convex(Xi, object$knots[[i]], pred.new=TRUE) delta.newdata=rbind( delta.newdata,delta.i$sigma-t(delta.i$x.mat%*%object$center.delta[[i]]) )} if(object$shapes[i]==4){ delta.i=concave(Xi, object$knots[[i]], pred.new=TRUE) delta.newdata=rbind( delta.newdata,delta.i$sigma-t(delta.i$x.mat%*%object$center.delta[[i]]) )} if(object$shapes[i]==5){ delta.newdata=rbind( delta.newdata,incconvex(Xi,object$knots[[i]])$sigma-object$center.delta[[i]] )} if(object$shapes[i]==7){ delta.newdata=rbind( delta.newdata,incconcave(Xi,object$knots[[i]])$sigma-object$center.delta[[i]] )} if(object$shapes[i]==6){ delta.newdata=rbind( delta.newdata,decconvex(Xi,object$knots[[i]])$sigma-object$center.delta[[i]] )} if(object$shapes[i]==8){ delta.newdata=rbind( delta.newdata,decconcave(Xi,object$knots[[i]])$sigma-object$center.delta[[i]] )} if(object$shapes[i]==1|object$shapes[i]==5|object$shapes[i]==7){incr=c(incr,1)}else{incr=c(incr,0)} if(object$shapes[i]==2|object$shapes[i]==6|object$shapes[i]==8){decr=c(decr,1)}else{decr=c(decr,0)} if(incr[i]==0 & decr[i]==0){ zmatb.newdata=cbind(zmatb.newdata,Xi) } } ind.nonparaplusinter=c(1, object$ind_nonparam) if(no.rows==1){ if(object$ind_intercept==1){ zmatb.newdata=c(v,xmat.newdata[,-(ind.nonparaplusinter)],zmatb.newdata) } else{zmatb.newdata=c(xmat.newdata[,-(ind.nonparaplusinter)],zmatb.newdata)} deltazmat=c(t(delta.newdata),zmatb.newdata) pred.sims=object$coefs.sims%*%deltazmat } else{ if(object$ind_intercept==1){ zmatb.newdata=cbind(v,xmat.newdata[,-(ind.nonparaplusinter)],zmatb.newdata) } else{zmatb.newdata=cbind(xmat.newdata[,-(ind.nonparaplusinter)],zmatb.newdata)} deltazmat=cbind(t(delta.newdata),zmatb.newdata) pred.sims=object$coefs.sims%*%t(deltazmat) } alpha.upper=1-(1-level)/2 alpha.lower=(1-level)/2 q.upper=function(x){quantile(x,alpha.upper)} q.lower=function(x){quantile(x,alpha.lower)} get.predgaussian=function(x){rnorm( rep(1,length(x)) ,x , object$sigma.sims)} get.predbinomial=function(x){rbinom( rep(1,length(x)), rep(1,length(x)), x) } get.predpoisson=function(x){rpois( rep(1,length(x)), x) } if(object$family=="gaussian"){ if(interval=="credible"|interval=="prediction"){ cred.mean=apply(pred.sims,2,mean) if(interval=="credible"){ if(parameter=="eta"){ cred.sd=apply(pred.sims,2,sd) cred.upper=apply(pred.sims,2,q.upper) cred.lower=apply(pred.sims,2,q.lower) list(cred.mean=cred.mean, cred.sd=cred.sd, cred.lower=cred.lower, cred.upper=cred.upper, y.lab="Estimated Mean") } else{ if(parameter=="mu"){ cred.sd=apply(pred.sims,2,sd) cred.upper=apply(pred.sims,2,q.upper) cred.lower=apply(pred.sims,2,q.lower) list(cred.mean=cred.mean, cred.sd=cred.sd, cred.lower=cred.lower, cred.upper=cred.upper, y.lab="Estimated Mean") } else{stop("parameter not valid!")} } } else{ pred.gaussian=apply(pred.sims, 2, get.predgaussian) pred.mean=apply(pred.gaussian,2,mean) pred.sd=apply(pred.gaussian,2,sd) pred.upper=apply(pred.gaussian,2,q.upper) pred.lower=apply(pred.gaussian,2,q.lower) list(pred.mean=pred.mean, pred.sd=pred.sd, pred.lower=pred.lower, pred.upper=pred.upper, y.lab="Prediction Mean") } } else{stop("incorrect type of interval!")} } else{ if(object$family=="binomial"){ if(interval=="credible"|interval=="prediction"){ mu.pred.sims=exp(pred.sims)/(1+exp(pred.sims)) if(interval=="credible"){ if(parameter=="eta"){ cred.mean=apply(pred.sims,2,mean) cred.sd=apply(pred.sims,2,sd) cred.upper=apply(pred.sims,2,q.upper) cred.lower=apply(pred.sims,2,q.lower) list(cred.mean=cred.mean, cred.sd=cred.sd, cred.lower=cred.lower, cred.upper=cred.upper, y.lab="Estimated log(odds)") } else{ if(parameter=="mu"){ cred.mean=apply(mu.pred.sims,2,mean) cred.sd=apply(mu.pred.sims,2,sd) cred.upper=apply(mu.pred.sims,2,q.upper) cred.lower=apply(mu.pred.sims,2,q.lower) list(cred.mean=cred.mean, cred.sd=cred.sd, cred.lower=cred.lower, cred.upper=cred.upper, y.lab="Estimated probability") } else{stop("parameter not valid!")} } } else{ pred.binomial<-apply(mu.pred.sims, 2, get.predbinomial) pred.mean<-apply(pred.binomial,2,mean) pred.sd<-apply(pred.binomial,2,sd) list(pred.mean=pred.mean, pred.sd=pred.sd, y.lab="Prediction probability") } } else{stop("incorrect type of interval!")} } else{ if(object$family=="poisson"){ if(interval=="credible"|interval=="prediction"){ mu.pred.sims=exp(pred.sims) if(interval=="credible"){ if(parameter=="eta"){ cred.mean=apply(pred.sims,2,mean) cred.sd=apply(pred.sims,2,sd) cred.upper=apply(pred.sims,2,q.upper) cred.lower=apply(pred.sims,2,q.lower) list(cred.mean=cred.mean, cred.sd=cred.sd, cred.lower=cred.lower, cred.upper=cred.upper, y.lab="Estimated log(counts)") } else{ if(parameter=="mu"){ cred.mean=apply(mu.pred.sims,2,mean) cred.sd=apply(mu.pred.sims,2,sd) cred.upper=apply(mu.pred.sims,2,q.upper) cred.lower=apply(mu.pred.sims,2,q.lower) list(cred.mean=cred.mean, cred.sd=cred.sd, cred.lower=cred.lower, cred.upper=cred.upper, y.lab="Estimated counts") } else{stop("parameter not valid!")} } } else{ pred.poisson<-apply(mu.pred.sims, 2, get.predpoisson) pred.mean<-apply(pred.poisson,2,mean) pred.sd<-apply(pred.poisson,2,sd) list(pred.mean=pred.mean, pred.sd=pred.sd, y.lab="Prediction counts") } } else{stop("incorrect type of interval!")} } } } }
curve_karcher_mean <- function (beta, mode = "O", rotated = T, scale = F, maxit = 20, ms = "mean") { if(ms!="mean"&ms!="median"){warning("ms must be either \"mean\" or \"median\". ms has been set to \"mean\"",immediate. = T)} if(ms!="median"){ms = "mean"} mean_scale=NA mean_scale_q=NA tmp = dim(beta) n = tmp[1] T1 = tmp[2] N = tmp[3] q = array(0, c(n, T1, N)) len = rep(0,N) len_q = rep(0,N) cent = matrix(0,n,N) for (ii in 1:N) { beta1 = beta[,,ii] centroid1 = calculatecentroid(beta1) cent[,ii] = -1*centroid1 dim(centroid1) = c(length(centroid1),1) beta1 = beta1 - repmat(centroid1,1,T1) beta[,,ii] = beta1 out = curve_to_q(beta1) q[, , ii] = out$q len[ii] = out$len len_q[ii] = out$lenq } mu = q[, , 1] bmu = beta[, , 1] delta = 0.5 tolv = 1e-04 told = 5 * 0.001 itr = 1 sumd = rep(0, maxit + 1) sumd[1] = Inf v = array(0, c(n, T1, N)) normvbar = rep(0, maxit + 1) if(ms == "median"){ d_i = rep(0,N) v_d = array(0, c(n, T1, N)) } cat("\nInitializing...\n") gam = matrix(0,T1,N) for (k in 1:N) { out = find_rotation_seed_unqiue(mu,q[, , k],mode) gam[,k] = out$gambest } gam = t(gam) gamI = SqrtMeanInverse(t(gam)) bmu = group_action_by_gamma_coord(bmu, gamI) mu = curve_to_q(bmu)$q mu[is.nan(mu)] <- 0 while (itr < maxit) { cat(sprintf("Iteration: %d\n", itr)) mu = mu/sqrt(innerprod_q2(mu, mu)) if (mode=="C"){ basis = find_basis_normal(mu) } for (i in 1:N) { q1 = q[, , i] out = find_rotation_seed_unqiue(mu,q1,mode) qn_t = out$q2best/sqrt(innerprod_q2(out$q2best,out$q2best)) q1dotq2 = innerprod_q2(mu,qn_t) if (q1dotq2 > 1){ q1dotq2 = 1 } if (q1dotq2 < -1){ q1dotq2 = -1 } dist = acos(q1dotq2) u = qn_t - q1dotq2 * q1 normu = sqrt(innerprod_q2(u,u)) if (normu > 1e-4){ w = u*acos(q1dotq2)/normu } else { w = matrix(0, nrow(beta1), T1) } if (mode=="O"){ v[, , i] = w } else { v[, , i] = project_tangent(w, q1, basis) } if(ms == "median"){ d_i[i] = sqrt(innerprod_q2(v[,,i], v[,,i])) if (d_i[i]>0){ v_d[,,i] = v[,,i]/d_i[i] } else{ v_d[,,i] = v[,,i] } } sumd[itr + 1] = sumd[itr + 1] + dist^2 } if(ms == "median"){ sumv = rowSums(v_d, dims = 2) sum_dinv = sum(1/d_i) vbar = sumv/sum_dinv } else{ sumv = rowSums(v, dims = 2) vbar = sumv/N } normvbar[itr] = sqrt(innerprod_q2(vbar, vbar)) normv = normvbar[itr] if ((sumd[itr]-sumd[itr+1]) < 0){ break } else if ((normv > tolv) && (abs(sumd[itr + 1] - sumd[itr]) > told)) { mu = cos(delta * normvbar[itr]) * mu + sin(delta * normvbar[itr]) * vbar/normvbar[itr] if (mode == "C") { mu = project_curve(mu) } x = q_to_curve(mu) a = -1 * calculatecentroid(x) dim(a) = c(length(a), 1) betamean = x + repmat(a, 1, T1) } else { break } itr = itr + 1 } if (scale){ mean_scale = prod(len)^(1/length(len)) mean_scale_q = prod(len_q)^(1/length(len)) betamean = mean_scale*betamean } ifelse(ms=="median",type<-"Karcher Median",type<-"Karcher Mean") return(list(beta = beta, mu = mu, type = type, betamean = betamean, v = v, q = q, E=normvbar[1:itr], cent = cent, len = len, len_q = len_q, qun = sumd[1:itr], mean_scale = mean_scale, mean_scale_q=mean_scale_q)) }
auroc <- function(score, bool) { n1 <- sum(!bool) n2 <- sum(bool) U <- sum(rank(score)[!bool]) - n1 * (n1 + 1) / 2 return(1 - U / n1 / n2) } set.seed(42) score <- sample(10, 1e3, replace = TRUE) bool <- sample(c(TRUE, FALSE), 1e3, replace = TRUE) pROC::auc(bool, score) mltools::auc_roc(score, bool) ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values[[1]] auroc(score, bool) bigstatsr::AUC(score, bool + 0L) microbenchmark::microbenchmark( pROC::auc(bool, score), mltools::auc_roc(score, bool), ROCR::performance(ROCR::prediction(score, bool), "auc")@y.values, auroc(score, bool), bigstatsr::AUC(score, bool + 0L), times = 5 ) auroc(score, bool) bigstatsr::AUC(score, bool + 0L) microbenchmark::microbenchmark( auroc(score, bool), bigstatsr::AUC(score, bool + 0L), times = 500 ) score <- sample(10, 1e5, replace = TRUE) bool <- sample(c(TRUE, FALSE), 1e5, replace = TRUE) auroc(score, bool) bigstatsr::AUC(score, bool + 0L) microbenchmark::microbenchmark( auroc(score, bool), bigstatsr::AUC(score, bool + 0L), times = 20 ) score <- rnorm(1e5) bool <- sample(c(TRUE, FALSE), 1e5, replace = TRUE) bool2 <- bool + 0L auroc(score, bool) bigstatsr::AUC(score, bool2) microbenchmark::microbenchmark( auroc(score, bool), bigstatsr::AUC(score, bool2), times = 20 )
context("test-summ_separation") classmetric_sep_methods <- c("GM", "OP", "F1", "MCC") test_that("summ_separation works with method 'KS'", { p_f <- new_p(data.frame(x = 1:4, prob = 1:4 / 10), "discrete") p_g <- new_p(data.frame(x = 1:4, prob = 4:1 / 10), "discrete") expect_equal(summ_separation(p_f, p_g, method = "KS"), 2) expect_equal(summ_separation(p_g, p_f, method = "KS"), 2) p_f <- new_p(data.frame(x = 1:4, y = c(1, 0, 0, 1)), "continuous") p_g <- new_p( data.frame(x = c(1.5, 2.5, 4.5), prob = c(0.1, 0.7, 0.3)), "discrete" ) expect_equal(summ_separation(p_f, p_g, method = "KS"), 2) expect_equal(summ_separation(p_g, p_f, method = "KS"), 2) p_f <- new_p(data.frame(x = c(0, 1), y = c(0, 2)), "continuous") p_g <- new_p(data.frame(x = c(0, 1), y = c(2, 0)), "continuous") expect_equal(summ_separation(p_f, p_g, method = "KS"), 0.5) expect_equal(summ_separation(p_g, p_f, method = "KS"), 0.5) }) test_that("summ_separation works with methods from `summ_classmetric`", { p_f <- new_d(1:4, "discrete") p_g <- new_d(2:6 + 0.1, "discrete") expect_equal(summ_separation(p_f, p_g, "GM"), 3, tolerance = 4e-4) expect_equal(summ_separation(p_g, p_f, "GM"), 3, tolerance = 4e-4) p_f <- new_d(seq(-5, 4, by = 1), "discrete") p_g <- as_d(dnorm) expect_equal(summ_separation(p_f, p_g, "GM"), -1, tolerance = 1e-3) expect_equal(summ_separation(p_g, p_f, "GM"), -1, tolerance = 1e-3) p_f <- as_d(dunif, min = -2) p_g <- as_d(dnorm) expect_equal(summ_separation(p_f, p_g, "GM"), -0.331789, tolerance = 3e-8) expect_equal(summ_separation(p_g, p_f, "GM"), -0.331789, tolerance = 3e-8) }) test_that("summ_separation returns smallest among alternatives", { d_1 <- new_d(data.frame(x = 1:4, y = c(0, 1, 0, 0)), "continuous") d_2 <- new_d(data.frame(x = 3:6, y = c(0, 0, 1, 0)), "continuous") expect_equal(summ_separation(d_1, d_2, "KS"), 3) expect_equal(summ_separation(d_1, d_2, "GM"), 3) expect_equal(summ_separation(d_1, d_2, "OP"), 3) expect_equal(summ_separation(d_1, d_2, "F1"), 3) expect_equal(summ_separation(d_1, d_2, "MCC"), 3) }) test_that("summ_separation uses `n_grid` argument", { f_con <- new_d(data.frame(x = c(0, 1), y = c(1, 1)), "continuous") g_con <- new_d(data.frame(x = c(0, 1.5), y = c(1, 1) / 1.5), "continuous") expect_equal( summ_separation(f_con, g_con, method = "GM", n_grid = 4), 0.5 ) }) test_that("summ_separation works with non-overlapping supports", { cur_dis_1 <- new_p(1:4, "discrete") cur_dis_2 <- new_p(5:6, "discrete") cur_con_1 <- new_p(data.frame(x = 1:4, y = c(1, 1) / 3), "continuous") cur_con_2 <- new_p(data.frame(x = 5:6, y = c(1, 1)), "continuous") cur_con_3 <- new_p(data.frame(x = 4:5, y = c(1, 1)), "continuous") cur_dirac_1 <- new_d(1, "continuous") cur_dirac_2 <- new_d(2, "continuous") expect_equal(summ_separation(cur_dis_1, cur_dis_2), 4.5) expect_equal(summ_separation(cur_dis_2, cur_dis_1), 4.5) expect_equal( summ_separation(new_p(1:2, "discrete"), new_p(2:3, "discrete")), 2 ) expect_equal( summ_separation(new_p(2:3, "discrete"), new_p(1:2, "discrete")), 2 ) expect_equal(summ_separation(cur_dis_1, cur_con_2), 4.5) expect_equal(summ_separation(cur_con_2, cur_dis_1), 4.5) expect_equal(summ_separation(cur_dis_1, cur_con_3), 4) expect_equal(summ_separation(cur_con_3, cur_dis_1), 4) expect_equal(summ_separation(cur_con_1, cur_con_2), 4.5) expect_equal(summ_separation(cur_con_2, cur_con_1), 4.5) expect_equal(summ_separation(cur_con_1, cur_con_3), 4) expect_equal(summ_separation(cur_con_3, cur_con_1), 4) expect_equal(summ_separation(cur_dirac_1, cur_dirac_2), 1.5) expect_equal(summ_separation(cur_dirac_2, cur_dirac_1), 1.5) }) test_that("summ_separation validates input", { expect_error(summ_separation("a", d_dis), "`f`.*not pdqr-function") expect_error(summ_separation(d_dis, "a"), "`g`.*not pdqr-function") expect_error(summ_separation(d_dis, d_con, method = 1), "`method`.*string") expect_error( summ_separation(d_dis, d_con, method = "a"), "`method`.*one of" ) expect_error( summ_separation(d_dis, d_con, n_grid = "a"), "`n_grid`.*number" ) expect_error( summ_separation(d_dis, d_con, n_grid = 1:2), "`n_grid`.*single" ) }) test_that("separation_ks works with two 'discrete' functions", { p_f <- new_d(1:3, "discrete") p_g <- new_d(1:3 + 1.5, "discrete") expect_equal(separation_ks(p_f, p_g), 3) expect_equal(separation_ks(p_g, p_f), 3) expect_equal( separation_ks( new_p(data.frame(x = 1:4, prob = 1:4 / 10), "discrete"), new_p(data.frame(x = 1:4, prob = 4:1 / 10), "discrete") ), 2 ) p_f <- as_p(ppois, lambda = 10) p_g <- as_p(ppois, lambda = 5) expect_equal(separation_ks(p_f, p_g), 7) }) test_that("separation_ks works with mixed-type functions", { cur_dis <- new_p(1:10, "discrete") cur_con <- new_p(data.frame(x = c(0, 10), y = c(1, 1) / 10), "continuous") expect_equal(separation_ks(cur_dis, cur_con), 1) expect_equal(separation_ks(cur_con, cur_dis), 1) expect_equal( separation_ks( new_p(data.frame(x = 1:2, y = c(1, 1)), "continuous"), new_p(2, "discrete") ), 2 ) p_dis_2 <- new_p(data.frame(x = 2:3, prob = c(0.5, 0.5)), "discrete") p_con_2 <- new_p(data.frame(x = 1:4, y = c(1, 0, 0, 1)), "continuous") expect_equal(separation_ks(p_dis_2, p_con_2), 2) p_dis_3 <- new_p(2.5, "discrete") p_con_3 <- new_p(data.frame(x = 1:4, y = c(1, 0, 0, 1)), "continuous") expect_equal(separation_ks(p_dis_3, p_con_3), 2) }) test_that("separation_ks works with two 'continuous' functions", { p_f <- new_p(data.frame(x = 0:1, y = c(2, 0)), "continuous") p_g <- new_p(data.frame(x = c(0.5, 1, 1.5), y = c(0, 2, 0)), "continuous") expect_equal(separation_ks(p_f, p_g), 2 / 3) expect_equal(separation_ks(p_g, p_f), 2 / 3) p_f <- new_p( data.frame(x = c(1:3, 5, 7), y = c(0, 0.5, 0, 0.25, 0)), "continuous" ) p_g <- new_p( data.frame(x = c(1:3, 5, 7) + 0.5, y = c(0, 0.5, 0, 0.25, 0)), "continuous" ) expect_equal(separation_ks(p_f, p_g), 2.25) p_f <- as_p(punif) p_g <- as_p(punif, min = -1, max = 3) expect_equal(separation_ks(p_f, p_g), 1) p_f <- new_p(data.frame(x = 1:4, y = c(1, 0, 0, 1)), "continuous") p_g <- new_p(data.frame(x = 0:5, y = c(0, 1, 0, 0, 1, 0) / 2), "continuous") expect_equal(separation_ks(p_f, p_g), 1) p_f <- new_p(data.frame(x = 1:4, y = c(0, 1, 0, 0)), "continuous") p_g <- new_p(data.frame(x = 3:6, y = c(0, 0, 1, 0)), "continuous") expect_equal(separation_ks(p_f, p_g), 3) }) test_that("separation_ks works with identical inputs", { expect_equal(separation_ks(d_dis, d_dis), meta_support(d_dis)[1]) expect_equal(separation_ks(d_con, d_con), meta_support(d_con)[1]) d_dirac <- new_d(2, "continuous") expect_equal( separation_ks(d_dirac, d_dirac), meta_support(d_dirac)[1], tolerance = 1e-9 ) }) test_that("separation_ks works with dirac-like functions", { d_dirac <- new_d(2, "continuous") d_dirac_dis <- new_d(2, "discrete") expect_equal(separation_ks(d_dis, d_dirac), separation_ks(d_dis, d_dirac_dis)) expect_equal(separation_ks(d_dirac, d_dirac_dis), 2, tolerance = 1e-10) expect_equal( separation_ks(d_con, d_dirac), separation_ks(d_con, d_dirac_dis) ) }) test_that("separation_classmetric works with two 'discrete' functions", { f_dis <- new_d(1:4, "discrete") g_dis <- new_d(2:6 + 0.1, "discrete") separations <- vapply( classmetric_sep_methods, separation_classmetric, numeric(1), f = f_dis, g = g_dis ) expect_equal( separations, c(GM = 3, OP = 3, F1 = 2, MCC = 4), tolerance = 5e-4 ) }) test_that("separation_classmetric works with mixed-type functions", { f_dis <- new_d(seq(-5, 4, by = 1), "discrete") g_con <- as_d(dnorm) separations <- vapply( classmetric_sep_methods, separation_classmetric, numeric(1), f = f_dis, g = g_con ) expect_equal( separations, c(GM = -1, OP = 0, F1 = -2, MCC = -2), tolerance = 5e-4 ) }) test_that("separation_classmetric works with two 'continuous' functions", { f_con <- as_d(dunif, min = -2) g_con <- as_d(dnorm) separations <- vapply( classmetric_sep_methods, separation_classmetric, numeric(1), f = f_con, g = g_con ) expect_equal( separations[c("GM", "OP", "F1")], c(GM = -0.331789, OP = -0.2291151, F1 = -1.3043396), tolerance = 6e-8 ) expect_equal(separations["MCC"], c(MCC = 1), tolerance = 2e-4) }) test_that("separation_classmetric works with different pdqr classes", { expect_equal( separation_classmetric(d_dis, d_con, "GM"), separation_classmetric(p_dis, q_con, "GM") ) })
context("compare_models") cds <- load_a549() test_that("compare_models() correctly deems NB better than Poisson",{ test_cds = cds[rowData(cds)$gene_short_name == "ANGPTL4",] zinb_cds = test_cds zinb_fit = fit_models(zinb_cds, expression_family = "zinegbinomial", model_formula_str = "~log_dose") zipoisson_cds = test_cds zipoisson_fit = fit_models(zipoisson_cds,expression_family = "zipoisson", model_formula_str = "~log_dose") nb_cds = test_cds nb_fit = fit_models(nb_cds, model_formula_str = "~log_dose", expression_family = "negbinomial") nb_reduced_fit = fit_models(nb_cds, model_formula_str = "~1", expression_family = "negbinomial") nb_comparison = suppressWarnings(compare_models(nb_fit, nb_reduced_fit)) expect_equal(nb_comparison$p_value[1], 0.0000228, tolerance=1e-3) nb_fit = fit_models(nb_cds, model_formula_str = "~log_dose", clean_model = FALSE, expression_family = "negbinomial") nb_reduced_fit = fit_models(nb_cds, model_formula_str = "~1", clean_model = FALSE, expression_family = "negbinomial") require("lmtest") lmtest_lrt_pval = lmtest::lrtest(nb_fit$model[[1]], nb_reduced_fit$model[[1]])[2,5] expect_equal(nb_comparison$p_value[1], lmtest_lrt_pval) skip("currently failing") nb_vs_zipoisson_comparison = compare_models(nb_fit, zipoisson_fit) expect_equal(nb_vs_zipoisson_comparison$p_value[1], NA_real_) zinb_vs_zipoisson_comparison = compare_models(zinb_fit, zipoisson_fit) expect_equal(zinb_vs_zipoisson_comparison$p_value[1], NA_real_) })
myoptim <- function(no_of_studies, study_optim, ref_dat_optim, X_rbind, X_bdiag_list, C, initial_val, threshold, model_optim, missing_covariance_study_indices, different_intercept, no_of_iter_outer) { beta_old <- as.vector(initial_val) eps_inner <- 0 study <- study_optim ref_dat <- ref_dat_optim threshold_optim <- threshold status = 1 X_abdiag = Reduce(magic::adiag,X_bdiag_list) if(different_intercept == FALSE) { iter = 0 continue <- TRUE r_first_U <- c() r_second_U <- c() U <- matrix(NA, nrow(C), nrow(ref_dat)) Gamma_hat <- matrix(NA, nrow(C), ncol(ref_dat)) while(continue) { r = c() r_first <- c() r_second <- c() Dn_1 <- matrix(NA, ncol(ref_dat), nrow(C)) Dn_2 <- c() W_star_first_list <- list() V <- c() k_j <- 1 W_temp_1 <- as.vector((1/(1 + exp(-ref_dat %*% beta_old)))*(1/(1 + exp(ref_dat %*% beta_old)))) W <- diag(W_temp_1) e1 <- as.vector(1/(1 + exp(-ref_dat %*% beta_old))) e2 <- as.vector((exp(-ref_dat %*% beta_old) - 1)/(exp(-ref_dat %*% beta_old) + 1)) e3 <- as.vector(1/(1 + exp(ref_dat %*% beta_old))) l <- e1*e2*e3 nan_indices <- which(l %in% NaN == TRUE) l[nan_indices] <- 0 L <- diag(l) for(k in 1 : no_of_studies) { r_first[[k]] <- e1 col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) r_second[[k]] <- as.vector(1/(1 + exp(-ref_dat[,col_ind] %*% study[[k]][[1]]))) Dn_2 <- c(Dn_2, as.vector(t(ref_dat[,col_ind]) %*% (r_first[[k]] - r_second[[k]]))) ncol_study <- length(col_ind) Dn_1[,k_j: (k_j + ncol_study -1)] <- t(ref_dat) %*% W %*% ref_dat[, col_ind] W_star_first_list[[k]] <- W %*% ref_dat[,col_ind] k_j <- k_j + ncol_study r = c(r, (r_first[[k]] - r_second[[k]])) } Dn <- Dn_1 %*% C %*% Dn_2 L = diag(rep(l, no_of_studies)) V = as.vector(t(r) %*% X_abdiag %*% C %*% t(X_abdiag) %*% L) W_star_second <- diag(V) W_star_first <- Reduce(magic::adiag,W_star_first_list) %*% C %*% t(Reduce(magic::adiag,W_star_first_list)) W_star <- W_star_first + W_star_second J_n <- t(X_rbind) %*% W_star %*% X_rbind if(det(J_n) == 0) { beta_old <- rep(NA, ncol(ref_dat)) break; } beta_new <- beta_old - (solve(J_n, tol=1e-60) %*% Dn) eps_inner <- sqrt(sum((beta_new - beta_old)^2)) beta_old <- beta_new iter = iter + 1 if(eps_inner < threshold_optim || iter > 2000) { continue <- FALSE if(iter >= 2000 && eps_inner >= threshold_optim) { status = 0 } } } no_of_iter_outer <- no_of_iter_outer + 1 if(sum(is.na(beta_old)) == 0) { study_indices <- seq(1,no_of_studies,1) non_missing_covariance_study_indices <- study_indices[-which(study_indices %in% missing_covariance_study_indices)] lambda_ref <- list() if(length(missing_covariance_study_indices) > 0) { for(k in missing_covariance_study_indices) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) w_lambda_ref_logistic_vec <- (((1/(1 + exp(ref_dat[,col_ind] %*% study[[k]][[1]])))^2)*(1/(1 + exp(-ref_dat %*% beta_old)))) + (((1/(1 + exp(-ref_dat[,col_ind] %*% study[[k]][[1]])))^2)*(1/(1 + exp(ref_dat %*% beta_old)))) W_lambda_ref_logistic <- diag(as.vector(w_lambda_ref_logistic_vec)) lambda_ref[[k]] <- (t(ref_dat[,col_ind]) %*% W_lambda_ref_logistic %*% ref_dat[,col_ind])/(study[[k]][[3]]) } for(k in non_missing_covariance_study_indices) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) temp_weight_logistic <- as.vector((1/(1 + exp(-ref_dat[, col_ind] %*% study[[k]][[1]])))*(1/(1 + exp(ref_dat[,col_ind] %*% study[[k]][[1]])))) W_k <- t(ref_dat[,col_ind]) %*% diag(temp_weight_logistic) %*% ref_dat[,col_ind] lambda_ref[[k]] <- (W_k %*% study[[k]][[2]] %*% t(W_k))/(nrow(ref_dat)) } } if(length(missing_covariance_study_indices) == 0) { for(k in 1 : no_of_studies) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) temp_weight_logistic <- as.vector((1/(1 + exp(-ref_dat[, col_ind] %*% study[[k]][[1]])))*(1/(1 + exp(ref_dat[,col_ind] %*% study[[k]][[1]])))) W_k <- t(ref_dat[,col_ind]) %*% diag(temp_weight_logistic) %*% ref_dat[,col_ind] lambda_ref[[k]] <- (W_k %*% study[[k]][[2]] %*% t(W_k))/(nrow(ref_dat)) } } Lambda_ref <- Reduce(magic::adiag,lambda_ref) k_U = 1 r_first_1 <- as.vector(1/(1 + exp(-ref_dat %*% beta_old))) W_Gamma_temp_1 <- as.vector((1/(1 + exp(-ref_dat %*% beta_old)))*(1/(1 + exp(ref_dat %*% beta_old)))) for(k in 1: no_of_studies) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) r_first_U[[k]] <- r_first_1 r_second_U[[k]] <- as.vector(1/(1 + exp(-ref_dat[,col_ind] %*% study[[k]][[1]]))) U[k_U:(k_U + length(col_ind)-1), ] <- t(ref_dat[ ,col_ind]) %*% diag(r_first_U[[k]]-r_second_U[[k]]) Gamma_hat[k_U:(k_U + length(col_ind)-1), ] <- t(ref_dat[, col_ind]) %*% diag(W_Gamma_temp_1) %*% ref_dat k_U <- k_U + length(col_ind) } Delta_hat <- (U %*% t(U))/(nrow(ref_dat)) C_beta <- solve(Lambda_ref + Delta_hat, tol = 1e-60) Gamma_hat <- Gamma_hat/nrow(ref_dat) info <- (t(Gamma_hat) %*% C_beta %*% Gamma_hat) if(det(info) == 0) { asy_var_opt = NULL }else{ if(no_of_iter_outer == 1) { if(det(t(Gamma_hat) %*% Gamma_hat) == 0) { asy_var_opt = NULL }else{ asy_var_opt <- (solve(t(Gamma_hat) %*% Gamma_hat, tol = 1e-60) %*% (t(Gamma_hat) %*% (Lambda_ref + Delta_hat) %*% Gamma_hat) %*% solve(t(Gamma_hat) %*% Gamma_hat, tol = 1e-60))/(nrow(ref_dat)) } } asy_var_opt <- solve(info, tol = 1e-60)/nrow(ref_dat) } } if(sum(is.na(beta_old)) > 0) { asy_var_opt = NULL C_beta = NULL } return(list("beta_optim" = beta_old, "C_optim" = C_beta, "Asy_var_optim" = asy_var_opt, "iter_IRWLS" = iter - 1, "Status" = status)) } if(different_intercept == TRUE) { W_Gamma <- list() X_rbind_star <- matrix(0, nrow(ref_dat)*no_of_studies, length(beta_old)) k_X_rbind_star <- 1 for(k in 1:no_of_studies) { X_rbind_star[(k_X_rbind_star:(k_X_rbind_star + nrow(ref_dat) -1)),k] <- 1 X_rbind_star[(k_X_rbind_star:(k_X_rbind_star + nrow(ref_dat) -1)), ((no_of_studies + 1):length(beta_old))] <- ref_dat[,-1] k_X_rbind_star <- k_X_rbind_star + nrow(ref_dat) } iter = 0 continue <- TRUE r_first_U <- c() r_second_U <- c() U <- matrix(NA, nrow(C), nrow(ref_dat)) Gamma_hat <- matrix(NA, nrow(C), length(beta_old)) while(continue) { beta_k <- list() for(k in 1:no_of_studies) { beta_k[[k]] <- beta_old[c(k,((no_of_studies + 1):length(beta_old)))] } r_first <- c() r_second <- c() r <- c() Dn_1 <- matrix(NA, length(beta_old), nrow(C)) Dn_2 <- c() W <- list() L <- list() W_star_first_list <- list() V <- c() k_j <- 1 for(k in 1:no_of_studies) { W_temp_1 <- as.vector((1/(1 + exp(-ref_dat %*% beta_k[[k]])))*(1/(1 + exp(ref_dat %*% beta_k[[k]])))) W[[k]] <- diag(W_temp_1) } for(k in 1:no_of_studies) { e1 <- as.vector(1/(1 + exp(-ref_dat %*% beta_k[[k]]))) e2 <- as.vector((exp(-ref_dat %*% beta_k[[k]]) - 1)/(exp(-ref_dat %*% beta_k[[k]]) + 1)) e3 <- as.vector(1/(1 + exp(ref_dat %*% beta_k[[k]]))) l <- e1*e2*e3 nan_indices <- which(l %in% NaN == TRUE) l[nan_indices] <- 0 L[[k]] <- diag(l) } k_j_star <- 1 for(k in 1 : no_of_studies) { r_first[[k]] <- as.vector(1/(1 + exp(-ref_dat %*% beta_k[[k]]))) col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) r_second[[k]] <- as.vector(1/(1 + exp(-ref_dat[,col_ind] %*% study[[k]][[1]]))) Dn_2 <- c(Dn_2, as.vector(t(ref_dat[,col_ind]) %*% (r_first[[k]] - r_second[[k]]))) ncol_study <- length(col_ind) Dn_1[,k_j: (k_j + ncol_study -1)] <- t(X_rbind_star[k_j_star:(k_j_star + nrow(ref_dat) - 1), ]) %*% W[[k]] %*% ref_dat[, col_ind] W_star_first_list[[k]] <- W[[k]] %*% ref_dat[,col_ind] k_j <- k_j + ncol_study k_j_star <- k_j_star + nrow(ref_dat) r = c(r, (r_first[[k]] - r_second[[k]])) } Dn <- Dn_1 %*% C %*% Dn_2 V = as.vector(t(r) %*% X_abdiag %*% C %*% t(X_abdiag) %*% Reduce(magic::adiag,L)) W_star_second <- diag(V) W_star_first <- Reduce(magic::adiag,W_star_first_list) %*% C %*% t(Reduce(magic::adiag,W_star_first_list)) W_star <- W_star_first + W_star_second J_n <- t(X_rbind_star) %*% W_star %*% X_rbind_star if(det(J_n) == 0) { beta_old <- rep(NA, (ncol(ref_dat) - 1 + no_of_studies)) break; } beta_new <- beta_old - (solve(J_n, tol = 1e-60) %*% Dn) eps_inner <- sqrt(sum((beta_new - beta_old)^2)) beta_old <- beta_new iter = iter + 1 if(eps_inner < threshold_optim || iter > 2000) { continue <- FALSE if(iter >= 2000 && eps_inner >= threshold_optim) { status = 0 } } } no_of_iter_outer <- no_of_iter_outer + 1 if(sum(is.na(beta_old)) == 0) { for(k in 1:no_of_studies) { beta_k[[k]] <- beta_old[c(k,((no_of_studies + 1):length(beta_old)))] } study_indices <- seq(1,no_of_studies,1) non_missing_covariance_study_indices <- study_indices[-which(study_indices %in% missing_covariance_study_indices)] lambda_ref <- list() if(length(missing_covariance_study_indices) > 0) { for(k in missing_covariance_study_indices) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) w_lambda_ref_logistic_vec <- (((1/(1 + exp(ref_dat[,col_ind] %*% study[[k]][[1]])))^2)*(1/(1 + exp(-ref_dat %*% beta_k[[k]])))) + (((1/(1 + exp(-ref_dat[,col_ind] %*% study[[k]][[1]])))^2)*(1/(1 + exp(ref_dat %*% beta_k[[k]])))) W_lambda_ref_logistic <- diag(as.vector(w_lambda_ref_logistic_vec)) lambda_ref[[k]] <- (t(ref_dat[,col_ind]) %*% W_lambda_ref_logistic %*% ref_dat[,col_ind])/(study[[k]][[3]]) } for(k in non_missing_covariance_study_indices) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) temp_weight_logistic <- as.vector((1/(1 + exp(-ref_dat[, col_ind] %*% study[[k]][[1]])))*(1/(1 + exp(ref_dat[,col_ind] %*% study[[k]][[1]])))) W_k <- t(ref_dat[,col_ind]) %*% diag(temp_weight_logistic) %*% ref_dat[,col_ind] lambda_ref[[k]] <- (W_k %*% study[[k]][[2]] %*% t(W_k))/(nrow(ref_dat)) } } if(length(missing_covariance_study_indices) == 0) { for(k in 1 : no_of_studies) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) temp_weight_logistic <- as.vector((1/(1 + exp(-ref_dat[, col_ind] %*% study[[k]][[1]])))*(1/(1 + exp(ref_dat[,col_ind] %*% study[[k]][[1]])))) W_k <- t(ref_dat[,col_ind]) %*% diag(temp_weight_logistic) %*% ref_dat[,col_ind] lambda_ref[[k]] <- (W_k %*% study[[k]][[2]] %*% t(W_k))/(nrow(ref_dat)) } } Lambda_ref <- Reduce(magic::adiag,lambda_ref) k_U = 1 k_j_star <- 1 for(k in 1: no_of_studies) { col_ind <- which(colnames(ref_dat) %in% names(study[[k]][[1]]) == TRUE) r_first_U[[k]] <- as.vector(1/(1 + exp(-ref_dat %*% beta_k[[k]]))) r_second_U[[k]] <- as.vector(1/(1 + exp(-ref_dat[,col_ind] %*% study[[k]][[1]]))) U[k_U:(k_U + length(col_ind)-1), ] <- t(ref_dat[ ,col_ind]) %*% diag(r_first_U[[k]]-r_second_U[[k]]) W_Gamma_temp_1 <- as.vector((1/(1 + exp(-ref_dat %*% beta_k[[k]])))*(1/(1 + exp(ref_dat %*% beta_k[[k]])))) Gamma_hat[k_U:(k_U + length(col_ind)-1), ] <- t(ref_dat[, col_ind]) %*% diag(W_Gamma_temp_1) %*% X_rbind_star[k_j_star:(k_j_star + nrow(ref_dat) - 1), ] k_U <- k_U + length(col_ind) k_j_star <- k_j_star + nrow(ref_dat) } Delta_hat <- (U %*% t(U))/(nrow(ref_dat)) C_beta <- solve(Lambda_ref + Delta_hat, tol = 1e-60) Gamma_hat <- Gamma_hat/nrow(ref_dat) info <- (t(Gamma_hat) %*% C_beta %*% Gamma_hat) if(det(info) == 0) { asy_var_opt = NULL }else{ if(no_of_iter_outer == 1) asy_var_opt <- (solve(t(Gamma_hat) %*% Gamma_hat, tol = 1e-60) %*% (t(Gamma_hat) %*% (Lambda_ref + Delta_hat) %*% Gamma_hat) %*% solve(t(Gamma_hat) %*% Gamma_hat, tol = 1e-60))/(nrow(ref_dat)) asy_var_opt <- solve(info, tol = 1e-60)/nrow(ref_dat) } } if(sum(is.na(beta_old)) > 0) { asy_var_opt = NULL C_beta = NULL } return(list("beta_optim" = beta_old, "C_optim" = C_beta, "Asy_var_optim" = asy_var_opt, "iter_IRWLS" = iter - 1, "Status" = status)) } }