code
stringlengths 1
13.8M
|
---|
set.seed(10)
library(mvtnorm)
library(mcmcse)
library(stableGR)
p <- 5
N <- 10000
tail.ind <- floor(N*.80):N
foo <- matrix(.50, nrow=p, ncol=p)
sigma <- foo^(abs(col(foo)-row(foo)))
mu <- sample(10:20, p)
mu2 <- mu[p]
mvn.gibbs <- stableGR:::mvn.gibbs
out.gibbs1 <- mvn.gibbs(N = N, mu = mu, sigma = sigma, p = p)
out.gibbs2 <- mvn.gibbs(N = N, mu = mu, sigma = sigma, p = p)
obj <- list(out.gibbs1, out.gibbs2)
outwithfun <- stable.GR(obj, blather = TRUE, size = "sqroot")
withfun <- outwithfun$mpsrf
blather <- outwithfun$blather
stacked <- rbind(out.gibbs1, out.gibbs2)
That <- mcse.multi(stacked, method = "lug", size = sqrt(N))$cov
Tmat1 <- mcse.multi(out.gibbs1, method = "lug", size = "sqroot")$cov
all.equal(That, blather$AsymVarMatrix)
sloan <- stableGR:::size.and.trim(obj, size = "sqroot")
trimmedchains <- sloan$trimmedchains
stackedchains <- do.call(rbind, trimmedchains)
Smat <- var(stackedchains)
all.equal(Smat, blather$S)
detratio <- det(That)/det(Smat)
all.equal(detratio, det(solve(blather$S, blather$AsymVarMatrix)))
Nchain <- length(obj)
all.equal(2, Nchain)
top <- (N-1) + ((detratio)^(1/p))
byhand <- sqrt(top/N)
all.equal(byhand, withfun)
onechain <- list(out.gibbs1)
withfun <- stable.GR(onechain, size = "sqroot")$mpsrf
Teigen <- eigen(Tmat1)$values
cov1 <- var(out.gibbs1)
Seigen <- eigen(cov1)$values
detT <- (prod(Teigen))
detS <- (prod(Seigen))
detratio <- detT/detS
Nchain <- length(onechain)
all.equal(1, Nchain)
rhat <- (N-1)/N + ((detratio)^(1/p))/N
byhand <- sqrt(rhat)
all.equal(byhand, withfun) |
HELLNO <- FALSE
data.frame <- function ( ..., stringsAsFactors = HELLNO ) {
base::data.frame( ..., stringsAsFactors=stringsAsFactors )
}
as.data.frame <- function (
x, row.names = NULL, optional = FALSE, stringsAsFactors=HELLNO, ...
){
base::as.data.frame(
x, row.names = NULL, optional = FALSE, stringsAsFactors=stringsAsFactors, ...
)
} |
get_custom_metric <- function(accountId, webPropertyId, customMetricId, token) {
path <- sprintf("management/accounts/%s/webproperties/%s/customMetrics/%s",
accountId, webPropertyId, customMetricId)
get_mgmt(path, token)
}
list_custom_metrics <- function(accountId, webPropertyId, start.index = NULL, max.results = NULL, token) {
path <- sprintf("management/accounts/%s/webproperties/%s/customMetrics",
accountId, webPropertyId)
list_mgmt(path, list(start.index = start.index, max.results = max.results), token)
} |
setMethod( f = "plot",
signature = "ViSigrid",
definition = function(x , scal.unit.tps = 10 , unit.tps = "s" , main = " " ,
ncharlabel=30 , size.main = 12 , Fontsize.title = 11 ,
Fontsize.label.Action = 11, Fontsize.label.Time = 11 , Fontsize.label.color = 9,
col.main = "black" , col.grid = "grey" , colgreenzone = "green" , colblackzone = "black" ,
alphainf = 0.8 , alphasup = 1, alphaZones = 0.2 ,
vp0h = 0.6, vp0w = 0.6, linA = 0.7 , rcircle = 15 , lwdline = 2 , lwd.grid = 1 , lty.grid = 1
) {
book <- methods::slot( x , "book" )
sortindex <- sort( book[ ,4] , index.return = TRUE)$ix
if ( any( is.na( book[ , 4] ) ) ) {
for (i in seq( 1 , sum( is.na( book[ , 4] ) ), 1) ) {
sortindex <- mapply( FUN = function(x , y )(return( if (y >= x ) { return( y + 1) }else{return( y ) } ) ) ,
x = which( is.na( book[ , 4] ) )[ i ] ,
y = sortindex )
}
}
inftps <- max( methods::slot( x , "vect_tps" ) )
lgv <- length( sortindex )
lgH <- length( methods::slot( x , "vect_tps" ) ) - 1
newx <- sapply( c( -0.06 , 0 , 0.06 ) , function(x ) { x * cos( seq( -pi , pi , 2 * pi / 8 ) ) }
) - sapply( c( 0 , 0.3 , 0 ) , function(x ) { -x * sin( seq( -pi , pi , 2 * pi / 8 ) ) } ) + 0.5
newy <- sapply( c( -0.06 , 0 , 0.06 ) , function(x ) { x * sin( seq( -pi , pi , 2 * pi / 8 ) ) }
) - sapply( c( 0 , 0.3 , 0 ) , function(x ) { x * cos( seq( -pi , pi , 2 * pi / 8 ) ) } ) + 0.5
vp0 <- grid::viewport( x = grid::unit( (1 - vp0w ) * 2/3 , "npc" ) ,
y = grid::unit( (1 - vp0h ) * 2/3 , "npc" ) ,
width = vp0w ,
height = vp0h ,
just = c( 0 , 0 ) ,
name = "vp0" )
layoutAction <- grid::viewport( layout = grid::grid.layout( lgv , 1 , widths = 1 , heights = 1 ) , name = "layoutAction" )
vplayoutA <- lapply( sortindex , function(x )(
grid::viewport( layout.pos.row = which( sortindex == x ) , layout.pos.col = 1 , name = paste0( "vp" , methods::slot( book , "vars")[ x ] ) ) ))
names(vplayoutA) = paste0( rep("vp" , lgv ) , methods::slot( book , "vars")[ seq( 1 , lgv , 1 ) ] )
grid::grid.newpage()
grid::pushViewport( vp0 )
grid::pushViewport( layoutAction )
for (ia in sortindex ) {
grid::pushViewport( vplayoutA[[ which( sortindex == ia ) ]] )
if (methods::slot( book , "typeA")[ ia ] == "p" ) {
plotgreenzoneP(book,ia,inftps,colgreenzone,alphaZones)
plotblackzoneP(book, ia, inftps, colblackzone, alphaZones)
plotpunctual( mat = methods::slot( x , "MATp" ) ,
iip = which( sortindex[ which( methods::slot( book , "typeA" )[sortindex] == "p" )] == ia ),
book = book, colvect = methods::slot( x , "colvect" ) ,
lgH = lgH ,
method = methods::slot( x , "parameters")$method ,
linA = linA )
plotInformersTests(x,book, inftps, ia, alphainf, lwdline, rcircle, linA ,newx, newy)
if (length( methods::slot( x , "MATpsup" ) ) > 0 ) {
plotpunctualsup(X = methods::slot( x , "MATpsup" ) ,
idsup = methods::slot( x , "idsup" ) ,
iip = which( sortindex[ which( methods::slot( book , "typeA" )[sortindex] == "p" )] == ia ) ,
book = book,
method = methods::slot( x , "parameters")$method ,
linA = linA ,
lgH = lgH ,
colvect = methods::slot( x , "colvect" ) ,
alphasup = alphasup)
}
}else{
iipp = which(methods::slot( book , "vars")[order(book[ , 4 ] )][which(methods::slot( book , "typeA")[order(book[ , 4 ] )] == "l")] == methods::slot( book , "vars" )[ia] )
plotL( L = methods::slot( x , "L" )[ , c( 2 * sum( methods::slot( book , "typeA" )[sortindex][ seq( 1 , which( sortindex == ia ) , 1) ] == "l" ) - 1 ,
2 * sum( methods::slot( book , "typeA" )[sortindex][ seq( 1 , which( sortindex == ia ) , 1) ] == "l" ) ) ] ,
idsort = methods::slot( x , "idsort" )[ ,iipp ] ,
inftps = inftps ,
group = methods::slot( x , "group" ) ,
BZL = methods::slot( x , "BZL" ) ,
Lsup = methods::slot( x , "Lsup" ) ,
idsup = methods::slot( x , "idsup" ) ,
iip = iipp,
t_0 = methods::slot( x , "parameters")$t_0,
cols = methods::slot( x , "colvect" ) ,
linA = linA ,
alphaZones = alphaZones ,
alphasup = alphasup ,
colblackzone = colblackzone)
if (is.null( methods::slot( x , "parameters" )$informer ) == FALSE ) {
plot_long_informer(x, book, sortindex, iipp, ia, inftps,lwdline,linA,newx, newy)
}
}
grid::upViewport()
}
grid::upViewport()
grid::upViewport()
legend_action( book = book ,main = main , size.main = size.main , Fontsize.title = Fontsize.title ,
Fontsize.label.Action = Fontsize.label.Action,
col.main = col.main, ncharlabel=ncharlabel,
vp0h = vp0h, vp0w = vp0w,layoutAction=layoutAction,sortindex=sortindex,
vplayoutA=vplayoutA)
legendgridtimes( vp0, vp0w,vp0h , x , lgv, inftps, scal.unit.tps,col.grid,lwd.grid,lty.grid,Fontsize.label.Time,unit.tps )
legendbottom( x, sortindex, book,vp0w, vp0h, Fontsize.label.color,colblackzone,alphaZones,colgreenzone)
}
) |
blkeig <- function(blk,p,X){
spdensity <- 0.5
if(!is.list(X)){
if(blk[[p,1]] =="s"){
blktmp <- blk[[p,2]]
if(length(blktmp) == 1){
out <- eigen(X)
d <- out$values
V <- out$vectors
}else{
d <- matrix(0,sum(blktmp),1)
V <- matrix(0,max(dim(X)),max(dim(X)))
xx <- mexsvec(blk[p,,drop=FALSE],X,0)
blktmp2 <- blktmp *(blktmp+1)/2
s2 <- c(0, cumsum(blktmp2))
blksub <- matrix(list(),1,2)
blksub[[1,1]] <- "s"
blksub[[1,2]] <- 0
s <- c(0, cumsum(blktmp))
for(i in 1:length(blktmp)){
pos <- c((s[i] +1):s[i+1])
blksub[[2]] <- blktmp[i]
Xsub <- mexsmat(blksub,xx[(s2[i]+1):s2[i+1]],0)
out <- eigen(Xsub)
lam <- out$values
d[pos,1] <- lam
V[pos,pos] <- out$vectors
}
}
}else if(blk[[p,1]] == "l"){
d = X
V <- matrix(1, nrow(X), ncol(X))
}
}else{
d <- matrix(list(),nrow(X), ncol(X))
V <- matrix(list(),nrow(X), ncol(X))
for(p in 1:nrow(blk)){
out<- blkeig(blk,p,X[[p]])
d[[p,1]] <- out$d
V[[p,1]] <- out$V
}
}
return(list(d=d, V=V))
} |
test_that("read_survey() reads data in qualtrics standard and legacy format and converts columns", {
survey <- suppressWarnings(qualtRics::read_survey("files/sample.csv"))
expect_equal(dim(survey)[1], 1)
expect_equal(dim(survey)[2], 20)
expect_true(is.numeric(as.numeric(survey$StartDate)))
expect_true(is.numeric(survey$LocationLatitude))
survey_legacy <- suppressWarnings(
qualtRics::read_survey("files/sample_legacy.csv",
legacy = TRUE)
)
expect_equal(dim(survey_legacy)[1], 1)
expect_equal(dim(survey_legacy)[2], 15)
expect_true(is.numeric(as.numeric(survey_legacy$V8)))
expect_true(is.numeric(survey_legacy$LocationLatitude))
survey <- suppressWarnings(
qualtRics::read_survey("files/sample.csv",
col_types = readr::cols(StartDate = readr::col_character()))
)
expect_equal(dim(survey)[1], 1)
expect_equal(dim(survey)[2], 20)
expect_true(is.character(survey$StartDate))
survey_legacy <- suppressWarnings(qualtRics::read_survey(
"files/sample_legacy.csv",
legacy = TRUE,
col_types = readr::cols(StartDate = readr::col_character()
)
))
expect_equal(dim(survey)[1], 1)
expect_equal(dim(survey)[2], 20)
expect_true(is.character(survey$StartDate))
})
test_that("Survey exists to read from disk", {
expect_error(
qualtRics::read_survey("/users/julia/desktop/error.csv"),
"does not exist"
)
}) |
PPP_Model <- function(FQ = NULL, t = NULL, alpha = NULL, truncation = NULL, truncation_type = "lp", dispersion = 1, Status = 0, Comment = "OK") {
obj <- list(FQ = FQ, t = t, alpha = alpha, truncation = truncation, truncation_type = truncation_type, dispersion = dispersion, Status = Status, Comment = Comment)
class(obj) <- "PPP_Model"
if (!is.valid.PPP_Model(obj)) {
obj <- list(FQ = NULL, t = NULL, alpha = NULL, truncation = NULL, truncation_type = "lp", dispersion = 1, Status = 2, Comment = is.valid.PPP_Model(obj, comment = TRUE))
class(obj) <- "PPP_Model"
}
return(obj)
}
print.PPP_Model <- function(x, ...) {
if (!is.positive.finite.number(x$dispersion)) {
fq_dist <- "Panjer"
} else if (x$dispersion == 1) {
fq_dist <- "Poisson"
} else if (x$dispersion > 1) {
fq_dist <- "Negative Binomial"
} else {
fq_dist <- "Binomial"
}
cat("\nPanjer & Piecewise Pareto model\n\n")
cat("Collective model with a ", fq_dist, " distribution for the claim count and a Piecewise Pareto distributed severity.", sep = "")
cat("\n\n", fq_dist, " Distribution:", sep = "")
cat("\nExpected Frequency: ", x$FQ, sep = "")
if (is.positive.finite.number(x$dispersion) && x$dispersion != 1) {
cat("\nDispersion: ", x$dispersion, sep = "")
if (is.positive.finite.number(x$FQ) && x$dispersion > 1) {
cat(" (i.e. contagion = ", (x$dispersion - 1)/x$FQ, ")", sep = "")
}
}
cat("\n\nPiecewise Pareto Distribution:")
cat("\nThresholds: ", x$t, sep = " ")
cat("\nAlphas: ", x$alpha, sep = " ")
if (!is.null(x$truncation)) {
cat("\nTruncation: ", x$truncation, sep = "")
cat("\nTruncation Type: '", x$truncation_type,"'", sep = "")
} else {
cat("\nThe distribution is not truncated.")
}
cat("\n\nStatus: ", x$Status)
cat("\nComments: ", x$Comment)
if (!is.valid.PPP_Model(x)) {
cat("\n\nThe model is not valid.\n")
cat(is.valid.PPP_Model(x, comment = TRUE))
}
cat("\n\n")
}
is.PPP_Model <- function(x) {
if (class(x) == "PPP_Model") {
return(TRUE)
} else {
return(FALSE)
}
}
is.valid.PPP_Model <- function(x, comment = FALSE) {
if (class(x) != "PPP_Model" || typeof(x) != "list") {
if (!comment) {
return(FALSE)
} else {
return("Object does not have class PPP_Model.")
}
}
required_elements <- c("FQ", "t", "alpha", "truncation", "truncation_type", "dispersion", "Status", "Comment")
available <- required_elements %in% names(x)
if (sum(!available) > 0) {
if (!comment) {
return(FALSE)
} else {
return(paste("Not all required list elements available. Missing elements:", paste(required_elements[!available], collapse = ", ")))
}
}
if (!is.nonnegative.finite.number(x$FQ)) {
if (!comment) {
return(FALSE)
} else {
return("FQ must be a nonnegative number.")
}
}
if (!valid.parameters.PiecewisePareto(x$t, x$alpha, x$truncation, x$truncation_type)) {
if (!comment) {
return(FALSE)
} else {
return(valid.parameters.PiecewisePareto(x$t, x$alpha, x$truncation, x$truncation_type, comment = TRUE))
}
}
if (!is.positive.finite.number(x$dispersion)) {
if (!comment) {
return(FALSE)
} else {
return("dispersion must be a positive number.")
}
}
if (!comment) {
return(TRUE)
} else {
return("OK")
}
}
PPP_Model_Exp_Layer_Loss_s <- function(Cover, AttachmentPoint, PPP_Model) {
if (!is.valid.PPP_Model(PPP_Model)) {
warning(is.valid.PPP_Model(PPP_Model, comment = TRUE))
return(NaN)
} else {
return(PPP_Model$FQ * PiecewisePareto_Layer_Mean(Cover, AttachmentPoint, PPP_Model$t, PPP_Model$alpha, truncation = PPP_Model$truncation, truncation_type = PPP_Model$truncation_type))
}
}
PPP_Model_Exp_Layer_Loss <- function(Cover, AttachmentPoint, PPP_Model) {
.Deprecated("Layer_Mean")
PPP_Model_Exp_Layer_Loss_v(Cover, AttachmentPoint, PPP_Model)
}
PPP_Model_Exp_Layer_Loss_v <- function(Cover, AttachmentPoint, PPP_Model) {
if (is.null(Cover) || (is.atomic(Cover) && length(Cover) == 0)) {
return(numeric())
}
if (is.null(AttachmentPoint) || (is.atomic(AttachmentPoint) && length(AttachmentPoint) == 0)) {
return(numeric())
}
vecfun <- Vectorize(PPP_Model_Exp_Layer_Loss_s, c("Cover", "AttachmentPoint"))
vecfun(Cover, AttachmentPoint, PPP_Model)
}
PPP_Model_Layer_Var_s <- function(Cover, AttachmentPoint, PPP_Model) {
if (!is.valid.PPP_Model(PPP_Model)) {
warning(is.valid.PPP_Model(PPP_Model, comment = TRUE))
return(NaN)
} else {
E_N <- PPP_Model$FQ
Var_N <- E_N * PPP_Model$dispersion
E_X <- PiecewisePareto_Layer_Mean(Cover, AttachmentPoint, PPP_Model$t, PPP_Model$alpha, truncation = PPP_Model$truncation, truncation_type = PPP_Model$truncation_type)
Var_X <- PiecewisePareto_Layer_Var(Cover, AttachmentPoint, PPP_Model$t, PPP_Model$alpha, truncation = PPP_Model$truncation, truncation_type = PPP_Model$truncation_type)
return(E_N * Var_X + Var_N * E_X^2)
}
}
PPP_Model_Layer_Var <- function(Cover, AttachmentPoint, PPP_Model) {
.Deprecated("Layer_Var")
PPP_Model_Layer_Var_v(Cover, AttachmentPoint, PPP_Model)
}
PPP_Model_Layer_Var_v <- function(Cover, AttachmentPoint, PPP_Model) {
if (is.null(Cover) || (is.atomic(Cover) && length(Cover) == 0)) {
return(numeric())
}
if (is.null(AttachmentPoint) || (is.atomic(AttachmentPoint) && length(AttachmentPoint) == 0)) {
return(numeric())
}
vecfun <- Vectorize(PPP_Model_Layer_Var_s, c("Cover", "AttachmentPoint"))
vecfun(Cover, AttachmentPoint, PPP_Model)
}
PPP_Model_Layer_Sd_s <- function(Cover, AttachmentPoint, PPP_Model) {
if (!is.valid.PPP_Model(PPP_Model)) {
warning(is.valid.PPP_Model(PPP_Model, comment = TRUE))
return(NaN)
} else {
return(sqrt(PPP_Model_Layer_Var_v(Cover, AttachmentPoint, PPP_Model)))
}
}
PPP_Model_Layer_Sd <- function(Cover, AttachmentPoint, PPP_Model) {
.Deprecated("Layer_Sd")
PPP_Model_Layer_Sd_v(Cover, AttachmentPoint, PPP_Model)
}
PPP_Model_Layer_Sd_v <- function(Cover, AttachmentPoint, PPP_Model) {
if (is.null(Cover) || (is.atomic(Cover) && length(Cover) == 0)) {
return(numeric())
}
if (is.null(AttachmentPoint) || (is.atomic(AttachmentPoint) && length(AttachmentPoint) == 0)) {
return(numeric())
}
vecfun <- Vectorize(PPP_Model_Layer_Sd_s, c("Cover", "AttachmentPoint"))
vecfun(Cover, AttachmentPoint, PPP_Model)
}
PPP_Model_Excess_Frequency_s <- function(x, PPP_Model) {
if (!is.valid.PPP_Model(PPP_Model)) {
warning(is.valid.PPP_Model(PPP_Model, comment = TRUE))
return(NaN)
} else if (!is.atomic(x) || !is.numeric(x) || length(x) != 1 || is.na(x)) {
warning("x must be a number.")
return(NaN)
} else {
return(PPP_Model$FQ * (1 - pPiecewisePareto(x, PPP_Model$t, PPP_Model$alpha, truncation = PPP_Model$truncation, truncation_type = PPP_Model$truncation_type)))
}
}
PPP_Model_Excess_Frequency <- function(x, PPP_Model) {
.Deprecated("Excess_Frequency")
PPP_Model_Excess_Frequency_v(x, PPP_Model)
}
PPP_Model_Excess_Frequency_v <- function(x, PPP_Model) {
if (is.null(x) || (is.atomic(x) && length(x) == 0)) {
return(numeric())
}
vecfun <- Vectorize(PPP_Model_Excess_Frequency_s, "x")
vecfun(x, PPP_Model)
}
PPP_Model_Simulate <- function(n, PPP_Model) {
.Deprecated("Simulate_Losses")
if (!is.valid.PPP_Model(PPP_Model)) {
warning(is.valid.PPP_Model(PPP_Model, comment = TRUE))
return(NaN)
}
if (!is.positive.finite.number(n)) {
warning("n must be a positive number.")
return(NaN)
} else {
n <- ceiling(n)
}
claim_count <- rPanjer(n, PPP_Model$FQ, PPP_Model$dispersion)
claims <- rPiecewisePareto(sum(claim_count), PPP_Model$t, PPP_Model$alpha, PPP_Model$truncation, PPP_Model$truncation_type)
result <- matrix(NaN, nrow = n, ncol = max(claim_count))
result[col(result) <= claim_count] <- claims
return(result)
} |
FPLdata <- function() {
readr::read_csv("https://raw.githubusercontent.com/andrewl776/fplmodels/master/data/players_by_gameweek_csv.csv")
} |
JackknifeVariance=function(n,r,pi,strata=FALSE,cluster=FALSE,clu=NULL){
if(length(n)!=1){stop("n must be a scalar.")}
if(n<0){stop("n must be a positive number.")}
if(!is.vector(r)){stop("r must be a vector.")}
if(any(is.na(r))){stop("There are missing values in r.")}
if(!is.vector(pi)){stop("pi must be a vector.")}
if(any(is.na(pi))){stop("There are missing values in pi.")}
if(any((pi<=0)|(pi>1))){stop("There are invalid values in pi.")}
if(length(pi)!=length(r)){stop("The lengths of pi and r are different.")}
if(((strata==FALSE)&(cluster==FALSE))|((strata==TRUE)&(cluster==FALSE))){
Je=vector()
for(i in 1:n){
wi=1/(pi[-i]*((n-1)/n))
Je[i]=sum(r[-i]*wi)
}
Jve=(1-mean(pi))*((n-1)/n)*sum((Je-mean(Je))^2)
}
if(((strata==FALSE)&(cluster==TRUE))|((strata==TRUE)&(cluster==TRUE))){
Je=vector()
for(i in levels(clu)){
wi=1/(pi[clu!=i]*((n-1)/n))
Je[i]=sum(r[clu!=i]*wi)
}
Jve=(1-mean(pi))*((n-1)/n)*sum((Je-mean(Je))^2)
}
if(Jve<0){warning("The variance estimation can not be negative.")}
return(Jve)
} |
givens_rot <- function (a, b) {
absa <- abs(a)
if (absa == 0){
realVar <- 0
cplxVar <- 1
} else {
normVariable <- pracma::Norm(cbind(a, b), p = 2)
realVar <- absa / normVariable
cplxVar <- a / absa * (Conj(b) / normVariable)
}
res <- rbind( cbind(realVar, cplxVar), cbind(-Conj(cplxVar), realVar) )
return(res)
} |
LRMI<-function(data_list,nMI,covariates,strata=NULL,...){
form1="Surv(time,cens)~"
form2=NULL
if (missing(strata) |is.null(strata)) {
form<-as.formula(paste("survival::",paste(form1,covariates)))
}
if (!missing(strata) && !is.null(strata)) {
form2=paste(paste("+strata(",paste(strata, collapse="+")),")")
form<-as.formula(paste(paste("survival::",paste(form1,covariates)),form2))
}
data1<-data_list$data_uc
cate_level<-names(table(data1[,covariates]))
cate_n<-length(cate_level)
if (!is.null(nMI) && nMI>0){
n<-nrow(data1)
stat=matrix(0,nrow=nMI,ncol=cate_n)
obs=matrix(0,nrow=nMI,ncol=cate_n)
exp=matrix(0,nrow=nMI,ncol=cate_n)
ngroup=as.numeric(table(data1[,covariates]))
vararray=array(0,dim=c(nMI,cate_n,cate_n))
censor=rep(0,n)
data1$time=rep(0,n)
data1$cens=rep(0,n)
varmean=0
for (isim in 1:nMI) {
for (i in 1:n) {
j=which(cumsum(data_list$weights[[i]])>runif(1))[1]
censor[i]=j
data1$time[i]=data_list$time[[i]][j]
if (censor[i]<data_list$e[i] ) {data1$cens[i]=1}
else if (censor[i]>=data_list$e[i]) {data1$cens[i]=0}
}
lr1=survival::survdiff(form,data=data1,...)
stat[isim,]=c(lr1$obs-lr1$exp)
obs[isim,]=c(lr1$obs)
exp[isim,]=c(lr1$exp)
vararray[isim,,]=lr1$var
varmean=varmean+lr1$var
}
statmean=colMeans(stat)
varmean=varmean/nMI
obsmean=colMeans(obs)
expmean=colMeans(exp)
x=statmean
B=matrix(0,cate_n,cate_n)
for (isim in 1:nMI) {
Bi=matrix(stat[isim,]-x,nrow=cate_n,ncol=1)
B=B+Bi%*%t(Bi)
}
B=B/(nMI-1)
var_MI<-varmean+((nMI+1)/nMI)*B
stat1<-statmean[1:(cate_n-1)]
chisq<-stat1%*%solve(var_MI[1:(cate_n-1),1:(cate_n-1)])%*%matrix(stat1)
p=as.numeric(1-pchisq(chisq,df=(cate_n-1)))
res<-list(est=x,pvalue=p,var=var_MI,est_mat=stat,Var_mat=vararray,chisq=chisq,
between_var=B, within_var=varmean,nMI=nMI,df=cate_n-1,obsmean=obsmean,expmean=expmean,
covariates=covariates,ngroup=ngroup,cate_level=dimnames(lr1$n)[[1]])
attr(res,"est")=x
attr(res,"var")=varmean+((nMI+1)/nMI)*B
attr(res,"Est_mat")=stat
attr(res,"chisq")=chisq
attr(res,"Var_mat")=vararray
attr(res,"Between Var")=B
attr(res,"Within Var")=varmean
attr(res,"nMI")=nMI
attr(res,"pvalue")=p
attr(res,"df")=df
attr(res,"covariates")=covariates
attr(res,"ngroup")=ngroup
attr(res,"Mean observed events")=obsmean
attr(res,"Mean expected events")=expmean
}
if (is.null(nMI)){
LR_cook<-data.frame()
for (z in (0:cate_n)){
Z=data.frame(data1[,c(covariates)])
names(Z)<-c(covariates)
if (z>0){
index<-Z[,c(covariates)]==cate_level[z]
n=sum(as.numeric(index))
}
if (z==0){
index<-c(1:nrow(Z))
n=length(index)
}
e=data_list$e[index]
s=data_list$s[index]
x=data_list$time[index]
w=data_list$weights[index]
Z <- as.matrix(Z)
delta<-vector()
for (i in (1:n) ) {
for (j in 1:(e[[i]])) {
if(j==e[[i]]){
dij=0
}
else{dij=1}
delta<-c(delta,dij)
}
}
times<-unlist(x)
weights<-unlist(w)
Y<-c(rep(cate_level[z],length(times)))
Y<-matrix(Y,ncol=1,byrow=T)
risk.set <- function(t) {which(times >= t)}
event.set <- function(t) {which(times == t)}
rs <- apply(as.matrix(times), 1, risk.set)
es <- apply(as.matrix(times), 1, event.set)
d <- vector()
r<-vector()
for(i in 1:length(rs)) {
r[i] <- sum(weights[rs[[i]]])
d[i] <- sum(weights[es[[i]]]*delta[es[[i]]])
}
if (z==0){
LR_cook<-data.frame(times,d,r)
LR_cook<-LR_cook[order(LR_cook$times),]
}
if (z>0){
temp<-data.frame(times,d,r)
temp<-temp[order(temp$times),]
names(temp)<-c("times",paste("d", z, sep = ""), paste("r", z, sep = ""))
LR_cook<-merge(LR_cook,temp,all.x=TRUE,by = c("times"))
}
}
name_index<-names(LR_cook)
for (i in (1:ncol(LR_cook))){
index<-min(which(!is.na(LR_cook[,i])==TRUE))
if (index>1 & substr(name_index[i],1,1)=="r"){
LR_cook[(1:(index-1)),i]=rep(LR_cook[index,i],(index-1))
}
if (index>1 & substr(name_index[i],1,1)=="d"){
LR_cook[(1:(index-1)),i]=rep(0,(index-1))
}
if (substr(name_index[i],1,1)=="d"){
LR_cook[is.na(LR_cook[,i]),i] <- 0
}
if (substr(name_index[i],1,1)=="r"){
for (j in (2:nrow(LR_cook))){
LR_cook[j,i] <- LR_cook[(j-1),i]-LR_cook[(j-1),(i-1)]
}
}
}
v<-rep(0,cate_n)
w_d<-matrix(rep(0,cate_n*cate_n),nrow=cate_n)
for (z in (1:cate_n)){
v[z]=sum(LR_cook[,(4+(z-1)*2)]-LR_cook[,(5+(z-1)*2)]*(LR_cook[,2])/(LR_cook[,3]))
}
for (i in (1:cate_n)){
for (j in (1:cate_n)){
if (i==j){
w_d[i,j]=sum((LR_cook[,2])*(LR_cook[,(5+(i-1)*2)]/(LR_cook[,3]))*(1-LR_cook[,(5+(i-1)*2)]/LR_cook[,3])*
((LR_cook[,3]-LR_cook[,2])/(LR_cook[,3]-1)))
}
if (i!=j){
w_d[i,j]=-sum(LR_cook[,(5+(j-1)*2)]*LR_cook[,(5+(i-1)*2)]*(LR_cook[,2])*(LR_cook[,3]-LR_cook[,2])/
((LR_cook[,3])^2*(LR_cook[,3]-1)))
}
}
}
lr_c<-t(v[1:(cate_n-1)])%*%solve(w_d[1:(cate_n-1),1:(cate_n-1)])%*%v[1:(cate_n-1)]
p=as.numeric(1-pchisq(lr_c,df=(cate_n-1)))
res<-list(est=v,pvalue=p,Var_matrix=w_d,chisq=lr_c,
df=cate_n-1,nMI=nMI,
column_name=covariates,cate_n=cate_n,cate_level=cate_level)
}
class(res) <- c("LRMI", class(res))
return(res)
} |
library("aroma.affymetrix")
verbose <- Arguments$getVerbose(-8, timestamp=TRUE)
dataSet <- "GSE9890"
chipType <- "HG-U133_Plus_2"
csR <- AffymetrixCelSet$byName(dataSet, chipType=chipType)
print(csR)
ab <- extractAffyBatch(csR, verbose=verbose)
print(ab) |
.juliaobjtable <- new.env(parent = emptyenv())
autowrap <- function(type, fields = NULL, methods = c()){
addExt(type, fields, methods)
cmd <- paste0('@eval JuliaCall begin sexp(x :: Main.',
type,
') = sexp(JuliaObject(x, "',
type,
'")) end;')
julia_command(cmd)
}
addExt <- function(type, fields = NULL, methods = c()){
if (is.null(fields)) {
fields <- tryCatch(julia_call("string.",
julia_eval(paste0("fieldnames(", type, ")"))),
warning = function(...) {c()},
error = function(...) {c()}
)
}
.juliaobjtable[[type]] <- list(fields = fields, methods = methods)
}
extendJuliaObj <- function(env, type){
r <- .juliaobjtable[[type]]
if (!is.null(r)) {
for (field in r$fields) makeAttr(env, field)
for (method in r$methods) makeMethod(env, method)
}
}
makeAttr <- function(env, name){
force(name)
force(env)
makeActiveBinding(name, function() field(env, name), env)
}
makeMethod <- function(env, name){
force(name)
force(env)
assign(name, function(...) julia_call(name, env, ...), env)
} |
taxid2rank <- function(x, db='ncbi', verbose=TRUE, warn=TRUE, ...){
result <- ap_vector_dispatch(
x = x,
db = db,
cmd = 'taxid2rank',
verbose = verbose,
warn = warn,
empty = character(0),
...
)
if(warn && any(is.na(result))){
msg <- "No rank found for %s of %s taxon IDs"
msg <- sprintf(msg, sum(is.na(result)), length(result))
if(verbose){
msg <- paste0(msg, ". The followings are left unrankd: ",
paste0(x[is.na(result)], collapse=', ')
)
}
warning(msg)
}
result
}
itis_taxid2rank <- function(src, x, ...){
if (length(x) == 0) return(character(0))
ranks <- unique(sql_collect(src, 'select * from taxon_unit_types'))
query <- "SELECT tsn,rank_id FROM taxonomic_units WHERE tsn IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
z <- dplyr::left_join(tbl,
unique(dplyr::select(ranks, rank_id, rank_name)),
by = "rank_id")
tolower(z$rank_name[match(x, z$tsn)])
}
wfo_taxid2rank <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT taxonID,taxonRank FROM wfo WHERE taxonID IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tolower(tbl$taxonRank[match(x, tbl$taxonID)])
}
tpl_taxid2rank <- function(src, x, ...){
stop("The TPL database is not supported")
}
col_taxid2rank <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT taxonID,taxonRank FROM taxa WHERE taxonID IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tolower(tbl$taxonRank[match(x, tbl$taxonID)])
}
gbif_taxid2rank <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT taxonID,taxonRank FROM gbif WHERE taxonID IN ('%s')"
query <- sprintf(query, paste0(x, collapse = "','"))
tbl <- sql_collect(src, query)
tolower(tbl$taxonRank[match(x, tbl$taxonID)])
}
ncbi_taxid2rank <- function(src, x, ...){
if (length(x) == 0) return(character(0))
query <- "SELECT tax_id, rank FROM nodes WHERE tax_id IN (%s)"
query <- sprintf(query, sql_integer_list(x))
tbl <- sql_collect(src, query)
as.character(tbl$rank[match(x, tbl$tax_id)])
} |
"pow_int" <- function(x, n, give=FALSE, strict=TRUE){
jj <- process.args(x,n)
x.vec <- jj$arg1
n.vec <- jj$arg2
attr <- jj$attr
jj <- .C("pow_int",
as.double(x.vec),
as.integer(n.vec),
as.integer(length(x.vec)),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
} |
search_albums <- function(album_name, output = c("tidy", "raw", "id"), limit = 20, offset = 0, token = my_token){
output <- match.arg(output)
response = content(GET("https://api.spotify.com/v1/search/", query = list(q = album_name, type = "album", limit = limit, offset = offset), add_headers(Authorization = token)))
items = response$albums$items
tidy <- data.frame(
artist = map(items, "artists") %>% modify_depth(2, "name") %>% map_chr(paste, collapse = " ft. "),
artist_id = map(items, "artists") %>% modify_depth(2, "id") %>% map_chr(paste, collapse = " ft. "),
album = map_chr(items, "name"),
album_id = map_chr(items, "id"),
release_date = map_chr(items, "release_date"),
total_tracks = map_int(items, "total_tracks"),
type = map_chr(items, "type")
)
id = tidy$album_id
out <- switch(output,
tidy = tidy,
raw = response,
id = id)
out
} |
useSteward <- function(colors = c("
speed = 30, angle = -45) {
bg_size <- length(colors) * 200
colors <- paste0(colors, collapse = ", ")
css <- paste0("
.waiter-overlay{
width: 100%;
height: 100vh;
background: linear-gradient(", angle, "deg, ", colors, ");
background-size: ", bg_size, "% ", bg_size, "%;
-webkit-animation: stewardAnimation ", speed, "s ease infinite;
animation: stewardAnimation ", speed, "s ease infinite;
}
@-webkit-keyframes stewardAnimation {
0%{background-position:0% 50%;}
50%{background-position:100% 50%;}
100%{background-position:0% 50%;}
}
@keyframes stewardAnimation {
0%{background-position:0% 50%;}
50%{background-position:100% 50%;}
100%{background-position:0% 50%;}
}
")
singleton(
tags$head(
tags$style(css)
)
)
}
use_steward <- function(
colors = c("
speed = 30,
angle = -45
) {
useSteward(
colors,
speed,
angle
)
} |
read_excel_file <- function (file,
sheetIndexes = NULL,
sheetNames = NULL) {
if (is.null(sheetIndexes) && is.null(sheetNames)) {
sheetNames <- readxl::excel_sheets(file)
} else if (is.null(sheetNames)) {
sheetNames <- readxl::excel_sheets(file)[sheetIndexes]
}
lpt <- list()
for (name in sheetNames) {
ft <- suppressMessages(
readxl::read_excel(
file,
sheet = name,
col_names = FALSE,
col_types = "text",
trim_ws = TRUE
)
)
if (nrow(ft) > 0) {
ft <- as.data.frame(ft)
names(ft) <- paste("X", 1:length(names(ft)), sep = "")
lpt <- c(lpt, list(new_pivot_table(ft, c(file, name))))
}
}
lpt
} |
redist_mergesplit_parallel = function(map, nsims, chains=1, warmup=floor(nsims/2),
init_plan=NULL, counties=NULL, compactness=1,
constraints=list(), constraint_fn=function(m) rep(0, ncol(m)),
adapt_k_thresh=0.975, k=NULL, ncores=NULL,
cl_type="PSOCK", return_all=TRUE, init_name=NULL,
verbose=TRUE, silent=FALSE) {
map = validate_redist_map(map)
V = nrow(map)
adj = get_adj(map)
ndists = attr(map, "ndists")
chains = as.integer(chains)
stopifnot(chains > 1)
if (compactness < 0) stop("Compactness parameter must be non-negative")
if (adapt_k_thresh < 0 | adapt_k_thresh > 1)
stop("`adapt_k_thresh` parameter must lie in [0, 1].")
if (nsims < 1)
stop("`nsims` must be positive.")
exist_name = attr(map, "existing_col")
counties = rlang::eval_tidy(rlang::enquo(counties), map)
if (is.null(init_plan) && !is.null(exist_name)) {
init_plans = matrix(rep(as.integer(as.factor(get_existing(map))), chains), ncol=chains)
if (is.null(init_name))
init_names = rep(exist_name, chains)
else
init_names = rep(init_name, chains)
} else if (!is.null(init_plan)) {
if (is.matrix(init_plan)) {
stopifnot(ncol(init_plan) == chains)
init_plans = init_plan
} else {
init_plans = matrix(rep(as.integer(init_plan), chains), ncol=chains)
}
if (is.null(init_name))
init_names = rep(exist_name, chains)
else
init_names = rep(init_name, chains)
}
if (length(init_plan) == 0L || isTRUE(init_plan == "sample")) {
if (!silent) cat("Sampling initial plans with SMC")
init_plans = get_plans_matrix(
redist_smc(map, chains, counties, compactness, constraints,
TRUE, constraint_fn, adapt_k_thresh, ref_name=FALSE,
verbose=verbose, silent=silent))
if (is.null(init_name))
init_names = paste0("<init> ", seq_len(chains))
else
init_names = paste(init_name, seq_len(chains))
}
stopifnot(nrow(init_plans) == V)
stopifnot(max(init_plans) == ndists)
if (is.null(counties)) {
counties = rep(1, V)
} else {
if (any(is.na(counties)))
stop("County vector must not contain missing values.")
component = contiguity(adj, as.integer(as.factor(counties)))
counties = dplyr::if_else(component > 1,
paste0(as.character(counties), "-", component),
as.character(counties)) %>%
as.factor() %>%
as.integer()
}
constraints = eval_tidy(enquo(constraints), map)
proc = process_smc_ms_constr(constraints, V)
constraints = proc$constraints
n_current = max(constraints$status_quo$current)
verbosity = 1
if (verbose) verbosity = 3
if (silent) verbosity = 0
if (is.null(k)) k = 0
pop_bounds = attr(map, "pop_bounds")
pop = map[[attr(map, "pop_col")]]
init_pop = pop_tally(init_plans, pop, ndists)
if (any(init_pop < pop_bounds[1]) | any(init_pop > pop_bounds[3]))
stop("Provided initialization does not meet population bounds.")
if (any(pop >= get_target(map)))
stop("Units ", which(pop >= get_target(map)),
" have population larger than the district target.\n",
"Redistricting impossible.")
if (!requireNamespace("utils", quietly=TRUE)) stop()
out = utils::capture.output({
x <- ms_plans(1, adj, init_plans[,1], counties, pop, ndists, pop_bounds[2],
pop_bounds[1], pop_bounds[3], compactness,
0, rep(1, ndists), ndists, 0, 0, 0, 1, rep(0, V),
0, 0, 0, rep(1, ndists), 0, beta_fractures = 0, adapt_k_thresh,
0L, verbosity=2)
}, type="output")
rm(x)
k = as.integer(stats::na.omit(stringr::str_match(out, "Using k = (\\d+)")[,2]))
if (is.null(ncores)) ncores = parallel::detectCores()
ncores = min(ncores, chains)
if (!silent)
cl = makeCluster(ncores, setup_strategy="sequential", outfile="", methods=FALSE)
else
cl = makeCluster(ncores, setup_strategy="sequential", methods=FALSE)
registerDoParallel(cl)
on.exit(stopCluster(cl))
each_len = if (return_all) nsims - warmup else 1
plans = foreach(chain=seq_len(chains), .combine=cbind) %dopar% {
if (!silent) cat("Starting chain ", chain, "\n", sep="")
algout = ms_plans(N = nsims+1L, l = adj, init = init_plans[, chain],
counties = counties, pop = pop, n_distr = ndists,
target = pop_bounds[2], lower = pop_bounds[1],
upper = pop_bounds[3], rho = compactness,
beta_sq = constraints$status_quo$strength,
current = constraints$status_quo$current,
n_current = n_current,
beta_vra = constraints$vra$strength,
tgt_min = constraints$vra$tgt_vra_min,
tgt_other = constraints$vra$tgt_vra_other,
pow_vra = constraints$vra$pow_vra,
min_pop = proc$min_pop,
beta_vra_hinge = constraints$hinge$strength,
tgts_min = constraints$hinge$tgts_min,
beta_inc = constraints$incumbency$strength,
incumbents = constraints$incumbency$incumbents,
beta_splits = constraints$splits$strength,
beta_fractures = constraints$multisplits$strength,
thresh = adapt_k_thresh, k = k, verbosity=verbosity)
if (return_all)
algout$plans[, -1:-(warmup+1L), drop=FALSE]
else
algout$plans[, nsims+1L, drop=FALSE]
}
out = new_redist_plans(plans, map, "mergesplit", NULL, FALSE,
compactness = compactness,
constraints = constraints,
adapt_k_thresh = adapt_k_thresh) %>%
mutate(chain = rep(seq_len(chains), each=each_len*ndists))
if (!is.null(init_names) && !isFALSE(init_name)) {
if (all(init_names[1] == init_names)) {
out = add_reference(out, init_plans[, 1], init_names[1])
} else {
out = Reduce(function(cur, idx) {
add_reference(cur, init_plans[, idx], init_names[idx]) %>%
mutate(chain = dplyr::coalesce(chain, idx))
}, rev(seq_len(chains)), init=out)
}
}
dplyr::relocate(out, chain, .after="draw")
}
utils::globalVariables("chain") |
permNormLog = function(target, dataset, xIndex, csIndex, wei = NULL, univariateModels = NULL , hash = FALSE, stat_hash = NULL,
pvalue_hash = NULL, threshold = 0.05, R = 999) {
pvalue = log(1)
stat = 0;
csIndex[which(is.na(csIndex))] = 0;
thres <- threshold * R + 1
if( hash ) {
csIndex2 = csIndex[which(csIndex!=0)]
csIndex2 = sort(csIndex2)
xcs = c(xIndex,csIndex2)
key = paste(as.character(xcs) , collapse=" ");
if ( !is.null(stat_hash[key]) ) {
stat = stat_hash[key];
pvalue = pvalue_hash[key];
results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
}
if ( !is.na( match(xIndex, csIndex) ) ) {
if( hash ) {
stat_hash[key] <- 0;
pvalue_hash[key] <- 1;
}
results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
if( any(xIndex < 0) || any(csIndex < 0) ) {
message(paste("error in testIndPois : wrong input of xIndex or csIndex"))
results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
xIndex = unique(xIndex);
csIndex = unique(csIndex);
x = dataset[ , xIndex];
cs = dataset[ , csIndex];
if ( length(cs)!=0 ) {
if ( is.null(dim(cs)[2]) ) {
if ( identical(x, cs) ) {
if ( hash ) {
stat_hash[key] <- 0;
pvalue_hash[key] <- 1;
}
results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
} else {
for (col in 1:dim(cs)[2]) {
if ( identical(x, cs[, col]) ) {
if( hash ) {
stat_hash[key] <- 0;
pvalue_hash[key] <- 1;
}
results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
}
}
}
if (length(cs) == 0) {
fit2 = glm(target ~ x, family = gaussian(link = log), weights = wei, model = FALSE)
dev2 <- fit2$deviance
stat <- fit2$null.deviance - dev2
if (stat > 0) {
step <- 0
j <- 1
n <- length(target)
while (j <= R & step < thres ) {
xb <- sample(x, n)
bit2 <- glm(target ~ xb, family = gaussian(link = log), weights = wei, model = FALSE)
step <- step + ( bit2$deviance < dev2 )
j <- j + 1
}
pvalue <- log( (step + 1) / (R + 1) )
} else pvalue <- log(1)
} else {
fit1 = glm(target ~ cs, family = gaussian(link = log), weights = wei, model = FALSE)
fit2 = glm(target ~ cs + x, family = gaussian(link = log), weights = wei, model = FALSE)
dev2 <- fit2$deviance
stat = fit1$deviance - dev2
if ( stat > 0 ) {
step <- 0
j <- 1
n <- length(target)
while (j <= R & step < thres ) {
xb <- sample(x, n)
bit2 <- glm(target ~ cs + xb, family = gaussian(link = log), weights = wei, model = FALSE)
step <- step + ( bit2$deviance < dev2 )
j <- j + 1
}
pvalue <- log( (step + 1) / (R + 1) )
} else pvalue <- log(1)
}
if ( is.na(pvalue) || is.na(stat) ) {
pvalue = log(1)
stat = 0;
} else {
if ( hash ) {
stat_hash[key] <- stat;
pvalue_hash[key] <- pvalue;
}
}
results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
} |
stat_ancova <- function(treatment,
baseline_suffix = 'bl',
std.beta = FALSE,
complete.cases = TRUE) {
fns <- list(
'formula_fn' = formula_std,
'fit_fn' = fit_ancova,
'params' = list(
'std.beta' = std.beta,
'complete.cases' = complete.cases
),
'extra_params' = list(
'treatment' = treatment,
'baseline_suffix' = baseline_suffix
)
)
fns$stat_type <- 'ancova'
class(fns) <- 'abaStat'
return(fns)
}
fit_ancova <- function(formula, data, extra_params) {
treatment <- extra_params$treatment
formula <- glue('{formula} + {treatment}')
bl_suffix <- extra_params$baseline_suffix
outcome <- formula %>% strsplit(' ~ ') %>% unlist() %>% head(1)
formula <- glue('{formula} + {outcome}_{bl_suffix}')
model <- stats::lm(stats::formula(formula), data = data)
model$call$formula <- stats::formula(formula)
return(model)
} |
imeansC = function(function1=NULL, function2=NULL, data, digits=2)
{
if(methods::is(data, "survey.design")!=TRUE) message(paste(sep="","Warning: Dataset \"", deparse(substitute(data)), "\" not a design dataset. Try gssD, nesD, statesD, or worldD instead."))
obj1 = svybyC(function1, function2, data)
obj2 = stats::ftable(obj1)
obj2 = round(obj2, digits = digits)
return(obj2)
} |
print.soo_function <- function(x, ...) {
cat(function_name(x), "\n",
" Lower bounds: (", paste(lower_bounds(x), collapse=", "), ")\n",
" Upper bounds: (", paste(upper_bounds(x), collapse=", "), ")\n", sep="")
} |
label_date <- function(format = "%Y-%m-%d", tz = "UTC") {
force_all(format, tz)
function(x) format(x, format, tz = tz)
}
label_date_short <- function(format = c("%Y", "%b", "%d", "%H:%M"), sep = "\n") {
force_all(format, sep)
function(x) {
dt <- unclass(as.POSIXlt(x))
changes <- cbind(
year = changed(dt$year),
month = changed(dt$mon),
day = changed(dt$mday)
)
changes <- t(apply(changes, 1, cumsum)) >= 1
if (inherits(x, "Date") || all(dt$hour == 0 & dt$min == 0, na.rm = TRUE)) {
format[[4]] <- NA
if (all(dt$mday == 1, na.rm = TRUE)) {
format[[3]] <- NA
if (all(dt$mon == 0, na.rm = TRUE)) {
format[[2]] <- NA
}
}
}
for_mat <- cbind(
ifelse(changes[, 1], format[[1]], NA),
ifelse(changes[, 2], format[[2]], NA),
ifelse(changes[, 3], format[[3]], NA),
format[[4]]
)
format <- apply(for_mat, 1, function(x) paste(rev(x[!is.na(x)]), collapse = sep))
format(x, format)
}
}
changed <- function(x) c(TRUE, is.na(x[-length(x)]) | x[-1] != x[-length(x)])
append_if <- function(x, cond, value) {
x[cond] <- lapply(x[cond], c, value)
x
}
label_time <- function(format = "%H:%M:%S", tz = "UTC") {
force_all(format, tz)
function(x) {
if (inherits(x, "POSIXt")) {
format(x, format = format, tz = tz)
} else if (inherits(x, "difftime")) {
format(as.POSIXct(x), format = format, tz = tz)
} else {
stop(
"time_format can't be used with objects of class ", paste(class(x), collapse = "/"),
".",
call. = FALSE
)
}
}
}
date_format <- label_date
time_format <- label_time |
genotype_probabilities <- function(target, fam, geno_freq, trans, penet,
monozyg = NULL) {
dat <- fam[, names(fam) != "family"]
dat <- data.frame(family = rep(1,nrow(fam)), dat)
if (is.null(target) | !target %in% dat$indiv) {
stop("The target cannot be found in the family data", call. = FALSE)
}
parents <- setdiff(c(dat$mother, dat$father), NA)
keep <- dat$indiv == target
if (is.na(dat$mother[keep]) & is.na(dat$father[keep]) & !(target %in% parents)) {
p <- geno_freq * penet[keep,]
if (sum(p) == 0) {return(rep(NA,length(geno_freq)))} else {return(p/sum(p))}
}
nold <- 0
keepIDs <- target
while (nold < length(keepIDs)) {
nold <- length(keepIDs)
new <- dat$indiv[dat$mother %in% keepIDs]
new <- c(new, dat$indiv[dat$father %in% keepIDs])
new <- c(new, dat$mother[dat$indiv %in% keepIDs])
new <- c(new, dat$father[dat$indiv %in% keepIDs])
new <- setdiff(new, NA)
keepIDs <- unique(c(keepIDs, new))
}
keep <- dat$indiv %in% keepIDs
dat <- dat[keep,]
penet <- penet[keep,]
if (length(monozyg) >= 1) {
for (i in 1:length(monozyg)) {
birth_group <- which(dat$indiv %in% monozyg[[i]])
if (length(birth_group) >= 2) {
if (target %in% monozyg[[i]]) {
representative <- which(dat$indiv==target)
} else {
representative <- birth_group[1]
}
p <- apply(penet[birth_group,], 2, prod)
penet[representative,] <- p
dat$mother[!is.na(dat$mother) & dat$mother %in% monozyg[[i]]] <- dat$indiv[representative]
dat$father[!is.na(dat$father) & dat$father %in% monozyg[[i]]] <- dat$indiv[representative]
birth_group <- setdiff(birth_group, representative)
penet <- penet[-birth_group,]
dat <- dat[-birth_group,]
}
}
}
target_id <- which(dat$indiv == target)
dat$mother[which(is.na(dat$mother))] <- ""
dat$father[which(is.na(dat$father))] <- ""
dat <- convert_IDs(dat, convert.IDs.numeric = TRUE)
fam_penet <- list(fam = dat, penet = penet)
p <- pedigree_loglikelihood_g(fam_penet, geno_freq, trans, target_id)
return(p)
} |
context("dtw_disvec")
test_that("correct values univariate", {
WS <- 11
eps <- 1/10^7
lot <- lapply(1:10, function(i){
rnorm(sample(seq(20, 30, 2), 1), log(i+1))
})
Q <- rnorm(20)
dm1 <- dtw_disvec(Q, lot, ws = WS, normalize = TRUE, dist_method = "norm1", ncores=1)
dm2 <- dtw_disvec(Q, lot, ws = WS, normalize = TRUE, dist_method = "norm1", ncores=2)
byhand <- sapply(1:10, function(i){
dtw2vec(Q = Q, lot[[ i ]], dist_method = "norm1", ws = WS)$normalized_distance
})
sum(abs(byhand-dm1$disvec))
sum(abs(byhand-dm2$disvec))
expect_equal(sum(abs(byhand-dm1$disvec)) < eps, TRUE)
expect_equal(sum(abs(byhand-dm2$disvec)) < eps, TRUE)
})
test_that("correct values multivariate", {
WS <- 6
eps <- 1/10^7
lot <- lapply(1:10, function(i){
matrix(rnorm(sample(seq(20, 30, 2), 1), log(i+1)), ncol = 2)
})
Q <- matrix(rnorm(20), ncol = 2)
dm1 <- dtw_disvec(Q, lot, ws = WS, normalize = TRUE, dist_method = "norm1", ncores=1)
dm2 <- dtw_disvec(Q, lot, ws = WS, normalize = TRUE, dist_method = "norm1", ncores=2)
byhand <- sapply(1:10, function(i){
dtw2vec(Q = Q, lot[[ i ]], dist_method = "norm1", ws = WS)$normalized_distance
})
expect_equal(sum(abs(byhand-dm1$disvec)) < eps, TRUE)
expect_equal(sum(abs(byhand-dm2$disvec))< eps, TRUE)
})
test_that("pass names of input", {
lot <- lapply(1:4, function(i){
cumsum(rnorm(10, i))
})
names(lot) <- letters[1:4]
x <- cumsum(rnorm(10))
ret <- dtw_disvec(Q=x, lot = lot, dist_method="norm2")
expect_equal(is.null(labels(ret$disvec)), FALSE)
}) |
ABMPaths <-
function(){
initialprice <- 100
time <- 1
steps <- 250
dt <- time/steps
my.draw <- function(panel) {
mu <- panel$mu
sigma <- panel$sigma
mudt <- mu*dt
sigmasqrtdt <- sigma*sqrt(dt)
paths <- panel$paths
ABMStockprices <- function(initialprice,steps,paths,sigmasqrtdt,mudt){
prices <- matrix(data=NA, nrow=steps+1,ncol=paths)
prices[1,] <- initialprice
for (i in 2:(steps+1)){
prices[i,] <- prices[i-1,]+ (mudt + sigmasqrtdt*rnorm(paths))
}
return(prices)
}
prices <-ABMStockprices(initialprice,steps,paths,sigmasqrtdt,mudt)
x.axis <- seq(0,1,length=steps+1)
my.title <- paste(paths, " Arithmetic Brownian motions", "(mu=", mu, ", sigma=", sigma,")")
matplot(prices,main= my.title,xlab="time", ylab="price",type='l',lwd=2)
panel
}
my.redraw <- function(panel)
{
rp.tkrreplot(panel, my.tkrplot)
panel
}
my.panel <- rp.control(title = "Arithmetic Brownian Motion", mu = 20, sigma = 40,paths=1,size=c(500,400))
rp.doublebutton(panel = my.panel, variable= mu, step = 8, range = c(0, 40),
showvalue=TRUE, title = "Drift", action = my.redraw)
rp.doublebutton(panel = my.panel, variable= sigma, step = 8, range = c(0, 80),
showvalue=TRUE, title = "Volatility", action = my.redraw)
rp.doublebutton(panel = my.panel, variable= paths, step = 1, range = c(1, 10),
showvalue=TRUE, title = "Paths", action = my.redraw)
rp.tkrplot(my.panel, my.tkrplot, my.draw, pos = "right", hscale=2,vscale=1.75)
} |
pred2.env <- function(X, Y, u, Xnew) {
X <- as.matrix(X)
a <- dim(Y)
n <- a[1]
r <- a[2]
p <- ncol(X)
Xnew <- as.matrix(Xnew)
if (nrow(Xnew) == 1) Xnew <- t(Xnew)
A <- qr.Q(qr(Xnew), complete = TRUE)
Ainv <- solve(A)
Z <- tcrossprod(X, Ainv)
X1 <- Z[, 1]
X2 <- Z[, 2:p]
fit <- penv(X1, X2, Y, u)
X1new <- Ainv[1, ] %*% Xnew
X2new <- Ainv[2:p, ] %*% Xnew
tmp <- pred.penv(fit, X1new, X2new)
return(list(value = tmp$value, covMatrix.estm = tmp$covMatrix.estm, SE.estm = tmp$SE.estm, covMatrix.pred = tmp$covMatrix.pred, SE.pred = tmp$SE.pred))
} |
name_backbone <- function(name, rank=NULL, kingdom=NULL, phylum=NULL,
class=NULL, order=NULL, family=NULL, genus=NULL, strict=FALSE, verbose=NULL,
start=NULL, limit=100, curlopts = list()) {
pchk(verbose, "name_backbone")
url <- paste0(gbif_base(), '/species/match')
args <- rgbif_compact(
list(name=name, rank=rank, kingdom=kingdom, phylum=phylum,
class=class, order=order, family=family, genus=genus,
strict=as_log(strict), offset=start, limit=limit))
tt <- gbif_GET(url, args, FALSE, curlopts)
out <- tibble::as_tibble(tt[!names(tt) %in% c("alternatives", "note")])
structure(out, args = args, note = tt$note, type = "single")
}
name_backbone_verbose <- function(name, rank=NULL, kingdom=NULL, phylum=NULL,
class=NULL, order=NULL, family=NULL, genus=NULL, strict=FALSE,
start=NULL, limit=100, curlopts = list()) {
url <- paste0(gbif_base(), '/species/match')
args <- rgbif_compact(
list(name=name, rank=rank, kingdom=kingdom, phylum=phylum,
class=class, order=order, family=family, genus=genus,
strict=as_log(strict), verbose=TRUE, offset=start, limit=limit))
tt <- gbif_GET(url, args, FALSE, curlopts)
alt <- tibble::as_tibble(data.table::setDF(
data.table::rbindlist(
lapply(tt$alternatives, function(x)
lapply(x, function(x) if (length(x) == 0) NA else x)),
use.names = TRUE, fill = TRUE)))
dat <- tibble::as_tibble(
data.frame(tt[!names(tt) %in% c("alternatives", "note")],
stringsAsFactors = FALSE))
out <- list(data = dat, alternatives = alt)
structure(out, args = args, note = tt$note, type = "single")
} |
context(" CVIs")
ols <- ls()
with(persistent, {
test_that("CVIs give the same results as references.", {
skip_on_cran()
expect_known_value(base_cvis, file_name(base_cvis))
expect_known_value(internal_fcvis, file_name(internal_fcvis))
expect_known_value(external_fcvis, file_name(external_fcvis))
expect_known_value(cvis_tadp, file_name(cvis_tadp))
expect_known_value(cvis_hc, file_name(cvis_hc))
expect_known_value(cvis_tadp_cent, file_name(cvis_tadp_cent))
expect_known_value(cvis_hc_cent, file_name(cvis_hc_cent))
})
})
rm(list = setdiff(ls(), ols)) |
'
Authors
Torsten Pook, [email protected]
Copyright (C) 2017 -- 2020 Torsten Pook
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'
alpha_to_beta <- function(alpha,G,Z) {
if (requireNamespace("MASS", quietly = TRUE)) {
crossprod(Z,crossprod(MASS::ginv(G),alpha))
} else{
crossprod(Z,crossprod(solve(G),alpha))
}
}
epi <- function(y,Z, G=NULL) {
n <- length(y)
p <- ncol(Z)
stopifnot(n == nrow(Z))
if(length(G)==0){
G <- tcrossprod(Z)
}
if(requireNamespace("EMMREML", quietly = TRUE)){
fm <- EMMREML::emmreml(
y,
matrix(1,nrow=n),
diag(n),
G)
} else{
stop("Usage of EMMREML without being installed!")
}
beta <- alpha_to_beta(drop(fm$uhat),G,Z)
return(drop(beta))
} |
gamma_Taylor <- function(y, skewness.y = skewness(y), skewness.x = 0,
degree = 3) {
stopifnot(is.numeric(skewness.x),
is.numeric(skewness.y),
length(skewness.y) == 1,
length(skewness.x) == 1,
degree == 1 || degree == 3)
if (skewness.x != 0) {
degree <- 1
}
if (degree == 1) {
gamma.hat <- (skewness.y - skewness.x) / 6
} else if (degree == 3) {
tmp <- skewness.y + sqrt(4 + skewness.y^2)
gamma.hat <- 0.5 * (- (2.0 / tmp)^(1/3) + (tmp / 2.0)^(1/3))
} else {
stop("Only first or third degree approximations are available.")
}
if (skewness.x <= 0) {
mu.tmp <- mean.default(y)
} else {
mu.tmp <- 0
}
bounds <- get_gamma_bounds(y, tau = c("mu_x" = mu.tmp, "sigma_x" = sd(y),
gamma = 0))
return(sign(gamma.hat) * min(abs(gamma.hat), min(abs(bounds))))
} |
library(GGMselect)
itest=2
p=30
n=30
eta=0.13
dmax=3
iG = 7
iS = 9
set.seed(iG)
Gr <- simulateGraph(p,eta)
set.seed(iS*(pi/3.1415)**iG)
X <- rmvnorm(n, mean=rep(0,p), sigma=Gr$C)
K=2.5
print(selectQE(X, dmax, K, verbose=TRUE))
cat ("End of test ", itest, "\n") |
as.data.frame.pstructure <- function(x, row.names = NULL, optional = FALSE, ...,
omit.marginality = FALSE)
{
if (!inherits(x, what = "pstructure"))
stop("Must supply an object of class pstructure")
x <- x[-match("aliasing", names(x))]
if (inherits(x$Q[[1]], what = "projector"))
x$Q <- unlist(lapply(x$Q, degfree))
if (omit.marginality)
x <- as.data.frame.list(x[-4], stringsAsFactors = FALSE)
else
{
if (x$Q[1] == "Mean")
Q <- Q[-1]
x <- as.data.frame.list(x, row.names = row.names, optional = optional,
stringsAsFactors = FALSE)
}
names(x)[1] <- "df"
return(x)
}
print.pstructure <- function(x, which = "all", ...)
{
if (!inherits(x, "pstructure"))
stop("Must supply an object of class pstructure")
options <- c("projectors", "marginality", "aliasing", "all")
print.opt <- options[unlist(lapply(which, check.arg.values, options=options))]
if (any(print.opt %in% c("projectors", "all")))
{
cat("\nProjection matrix summary\n\n")
print(as.data.frame(x, omit.marginality = TRUE))
}
if (any(print.opt %in% c("marginality", "all")))
{
cat("\nMarginality matrix\n\n")
print(x$marginality)
}
if (any(print.opt %in% c("aliasing", "all")))
{
if (is.null(x$aliasing))
cat("\n\nNo aliasing between sources in this pstructure object\n\n")
else
{
print(x$aliasing, ...)
}
}
invisible()
}
"marginality.pstructure" <- function(object, ...)
{ if (!inherits(object, "pstructure"))
stop("Must supply an object of class pstructure as produced by designAnatomy")
if (is.null(object$marginality))
marginality <- NULL
else
{
marginality <- object$marginality
}
return(marginality)
}
print.aliasing <- function(x, which.criteria = c("aefficiency","eefficiency","order"),
...)
{
if (!is.null(x))
{
if (!inherits(x, "aliasing"))
stop("Must supply an object of class aliasing")
if (nrow(x) > 0)
{
criteria <- c("aefficiency", "eefficiency", "mefficiency", "sefficiency", "xefficiency",
"order", "dforthog")
options <- c(criteria, "none", "all")
kcriteria <- options[unlist(lapply(which.criteria, check.arg.values,
options=options))]
if ("all" %in% kcriteria)
kcriteria <- criteria
anycriteria <- !("none" %in% kcriteria)
cols <- c("Source","df")
if (!all(is.na(x$Alias)))
cols <- c(cols, "Alias")
if ("In" %in% names(x))
cols <- c(cols, "In")
if (anycriteria)
{
cols <- c(cols, kcriteria)
if (!all(kcriteria %in% names(x)))
stop("Not all requested efficiency criteria are available in aliasing for printing")
}
cat(attr(x, which = "title"))
y <- x[cols]
for (kcrit in kcriteria)
{
if (kcrit == "order")
{
y[kcrit] <- formatC(y[[kcrit]], format="f", digits=0, width=5)
} else
{
if (kcrit == "dforthog")
{
y[kcrit] <- formatC(y[[kcrit]], format="f", digits=0, width=8)
} else
{
y[kcrit] <- formatC(y[[kcrit]], format="f", digits=4, width=11)
}
}
y[kcrit] <- gsub("NA", " ", y[[kcrit]])
}
print.data.frame(y, na.print=" ", right=FALSE, row.names=FALSE)
}
}
invisible()
}
formSources <- function(term.names, marginality, grandMean = FALSE)
{
if (grandMean)
{
gmterm <- term.names[1]
term.names <- term.names[-1]
}
nterms <- length(term.names)
names(term.names) <- term.names
if (nterms == 1)
sources <- term.names
else
{
sources <- vector(mode = "character", length = nterms)
names(sources) <- term.names
fac.list <- lapply(term.names, fac.getinTerm)
names(fac.list) <- term.names
facs <- unique(unlist(fac.list))
fac.incidence <- do.call(rbind, lapply(fac.list,
function(kfac.list, facs)
{
ind <- rep(FALSE, length(facs))
names(ind) <- facs
ind[kfac.list] <- TRUE
return(ind)
}, facs = facs))
nfac <- length(facs)
k1 <- 0
newterms <- list()
for (k in 1:(nfac-1))
{
k1 <- k1 + 1
facs.identical <- unlist(lapply(facs[(k1+1):nfac],
function(jfac, kfac, fac.incidence)
{
is.same <- all(fac.incidence[,jfac] == fac.incidence[,kfac])
return(is.same)
}, kfac = facs[k1], fac.incidence = fac.incidence))
if (any(facs.identical))
{
facs.identical <- c(facs[k1],
c(facs[(k1+1):nfac])[facs.identical])
nposns <- length(facs.identical)
newterms <- lapply(term.names[fac.incidence[,facs[k1]]],
function(term, fac.list)
{
newterm <- term
kfac.list <- fac.list[[term]]
fac.posns <- sort(match(facs.identical, kfac.list))
if (!any(is.na(fac.posns)))
{
nposns <- length(fac.posns)
if ((nposns-1) == fac.posns[nposns] - fac.posns[1])
{
if (fac.posns[1] == 1 & nposns == length(kfac.list))
newterm <- paste("(",
paste(kfac.list[fac.posns[1]:fac.posns[nposns]],
collapse = "."),
")", sep = "")
else
{
newterm <- paste("(",
paste(kfac.list[fac.posns[1]:fac.posns[nposns]],
collapse = "."),
")", sep = "")
if (fac.posns[1] != 1)
newterm <- paste(c(kfac.list[1:(fac.posns[1] - 1)], newterm),
collapse = ":")
if (fac.posns[nposns] < length(kfac.list))
newterm <- paste(c(newterm,
kfac.list[(fac.posns[nposns]+1):length(kfac.list)]),
collapse = ":")
}
}
}
newterm <- list(term = term, newterm = newterm)
return(newterm)
}, fac.list = fac.list)
if (length(newterms) > 0)
{
term.names <- unlist(lapply(term.names,
function(term, newterms)
{
for (k in 1:length(newterms))
{
if (newterms[[k]]$term == term)
term <- newterms[[k]]$newterm
}
return(term)
}, newterms = newterms))
fac.list <- lapply(term.names, fac.getinTerm)
names(fac.list) <- term.names
colnames(marginality) <- unlist(term.names)
rownames(marginality) <- unlist(term.names)
}
k1 <- k1 + nposns - 1
}
if (k1 >= (nfac-1))
break
}
facs <- unique(unlist(fac.list))
fac.incidence <- do.call(rbind, lapply(fac.list,
function(kfac.list, facs)
{
ind <- rep(FALSE, length(facs))
names(ind) <- facs
ind[kfac.list] <- TRUE
return(ind)
}, facs = facs))
implicit <- vector(mode = "list", length = length(term.names))
names(implicit) <- term.names
for (term in term.names)
{
k <- match(term, rownames(fac.incidence))
kmarg <- as.logical(marginality[, k])
kmarg[k] <- FALSE
if (any(kmarg))
{
kmarg <- rownames(fac.incidence)[kmarg]
implicit[[term]] <- !unlist(lapply(kmarg,
function(kterm, term, fac.list)
{
is.subset <- (length(intersect(fac.list[[term]],
fac.list[[kterm]])) > 0)
return(is.subset)
}, term = term, fac.list = fac.list))
if (any(implicit[[term]]))
for (kimpl in kmarg[implicit[[term]]])
fac.incidence[term, ] <- fac.incidence[term, ] | fac.incidence[kimpl, ]
}
}
marg.compliant <- marginality == 1
kmarg.terms <- vector(mode = "list", length = nterms)
names(kmarg.terms) <- term.names
for (term in term.names)
{
j <- k <- match(term, term.names)
if (j <= 1)
{
kmarg.terms[[term]] <- character()
} else
{
if (!any(marg.compliant[1:(j-1), k]))
kmarg.terms[[term]] <- character()
else
{
repeat
{
if (j <= 0)
break
if (j == 1 | !any(marg.compliant[1:(j-1), k]))
j <- numeric()
else
j <- max(c(1:(j-1))[marg.compliant[1:(j-1), k]])
if (length(j) == 0 || is.infinite(j))
break
if (j > 1 & any(marginality[1:(j-1), j] == 1))
{
marg.compliant[1:(j-1), k][marginality[1:(j-1), j] == 1] <- FALSE
}
}
kmarg.terms[[term]] <- term.names[marg.compliant[,k]]
kmarg.terms[[term]] <- kmarg.terms[[term]][-match(term, kmarg.terms[[term]])]
}
}
}
for (term in term.names)
{
k <- match(term, term.names)
if (length(kmarg.terms[[term]]) == 0)
{
sources[k] <- gsub(".", ":", term, fixed = TRUE)
nch <- nchar(sources[k])
if (substr(sources[k], 1, 1) == "(" & substr(sources[k], nch, nch) == ")")
sources[k] <- substr(sources[k], 2, nch-1)
} else
{
if (length(kmarg.terms[[term]]) == 1)
{
facs.nesting <- fac.list[kmarg.terms[[term]]][[1]]
kfacs <- colnames(fac.incidence)[fac.incidence[kmarg.terms[[term]],]]
facs.nesting <- c(na.omit(setdiff(kfacs, facs.nesting)),
facs.nesting)
facs.nested <- setdiff(fac.list[term][[1]], facs.nesting)
} else
{
facs.nesting <- NULL
facs.nested <- NULL
common.marginals <- TRUE
for (c in match(kmarg.terms[[term]], term.names))
common.marginals <- common.marginals & marginality[,c] == 1
common.marginals <- term.names[common.marginals]
facs.nesting <- character()
for (cterm in common.marginals)
{
facs.nesting <- c(facs.nesting, fac.list[cterm][[1]])
}
facs.nesting <- unique(facs.nesting)
kfacs <- unlist(lapply(kmarg.terms[[term]],
function(kmarg, fac.incidence)
{
fac <- colnames(fac.incidence)[fac.incidence[kmarg,]]
}, fac.incidence = fac.incidence))
kfacs <- c(na.omit(setdiff(kfacs, fac.list[term][[1]])),
fac.list[term][[1]])
kfacs <- kfacs[!(kfacs %in% facs.nesting)]
if (length(kfacs) > 0)
{
for (kfac in kfacs)
{
if (all(fac.incidence[kmarg.terms[[term]], kfac]))
facs.nesting <- c(facs.nesting, kfac)
}
}
facs.nested <- setdiff(fac.list[term][[1]], facs.nesting)
}
sources[k] <- paste(facs.nested, collapse = "
if (length(facs.nested) == 1)
{
nch <- nchar(sources[k])
if (substr(sources[k], 1, 1) == "(" & substr(sources[k], nch, nch) == ")")
sources[k] <- substr(sources[k], 2, nch-1)
}
if (length(facs.nesting) > 0)
{
facs.nesting <- paste(facs.nesting, collapse = ":")
facs.nesting <- gsub("(", "", facs.nesting, fixed = TRUE)
facs.nesting <- gsub(")", "", facs.nesting, fixed = TRUE)
sources[k] <- paste(sources[k], "[", facs.nesting,"]", sep = "")
}
sources[k] <- gsub(".", ":", sources[k], fixed = TRUE)
}
}
}
if (grandMean)
{
sources <- c(gmterm, sources)
names(sources)[1] <- gmterm
}
return(sources)
}
"projs.jandw" <- function(R, Q, which.criteria = c("aefficiency","eefficiency","order"),
aliasing.print = TRUE)
{
if (!is.list(Q))
stop("The matrices to orthogonalize to must be in a list")
criteria <- c("aefficiency", "eefficiency", "mefficiency", "sefficiency", "xefficiency",
"order", "dforthog")
options <- c(criteria, "none", "all")
kcriteria <- options[unlist(lapply(which.criteria, check.arg.values,
options=options))]
if ("all" %in% kcriteria)
kcriteria <- criteria
anycriteria <- !("none" %in% kcriteria)
nc <- 3 + length(criteria)
aliasing <- data.frame(matrix(nrow = 0, ncol=nc))
colnames(aliasing) <- c("Source", "df", "Alias", criteria)
class(aliasing) <- c("aliasing", "data.frame")
eff.crit <- vector(mode="list",length=length(criteria))
names(eff.crit) <- criteria
terms <- names(Q)
aliased <- rep(FALSE, length(terms))
names(aliased) <- terms
for (i in 1:length(terms))
{
decomp <- proj2.combine(R, Q[[terms[i]]])
df <- degfree(decomp$Qconf)
if (df == 0)
{
warning(paste(terms[[i]],"is aliased with previous terms in the formula",
"and has been removed", sep=" "))
eff.crit[criteria] <- 0
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]], df = df,
Alias = "
eff.crit),
stringsAsFactors = FALSE))
} else
{
keff.crit <- efficiency.criteria(decomp$efficiencies)
if ((df - keff.crit[["dforthog"]]) != 0)
{
P <- projector(mat.I(nrow(R)) - R)
decompP <- proj2.combine(P, Q[[terms[i]]])
keff.crit <- efficiency.criteria(decompP$efficiencies)
warning(paste(terms[[i]],"is partially aliased with previous terms in the formula", sep=" "))
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]], df = degfree(decompP$Qconf), Alias = "unknown"),
keff.crit),
stringsAsFactors = FALSE))
}
}
Q[[terms[i]]] <- decomp$Qconf
R <- decomp$Qres
}
if (nrow(aliasing) > 0)
{
rownames(aliasing) <- NULL
class(aliasing) <- c("aliasing", "data.frame")
attr(aliasing, which = "title") <-
"\nTable of information (partially) aliased with previous sources derived from the same formula\n\n"
if (aliasing.print)
{
if (anycriteria)
print(aliasing, which = kcriteria)
else
print(aliasing, which = "none")
}
} else
{
aliasing <- NULL
}
Q <- Q[!aliased]
return(list(Q = Q, aliasing = aliasing))
}
"pstructure.formula" <- function(formula, keep.order = TRUE, grandMean = FALSE,
orthogonalize = "hybrid", labels = "sources",
marginality = NULL, check.marginality = TRUE,
omit.projectors = FALSE,
which.criteria = c("aefficiency","eefficiency","order"),
aliasing.print = TRUE, data = NULL, ...)
{
options <- c("differencing", "eigenmethods", "hybrid")
opt <- options[check.arg.values(orthogonalize, options)]
options <- c("terms", "sources")
lab.opt <- options[check.arg.values(labels, options)]
if (orthogonalize == "eigenmethods" & lab.opt == "sources" & is.null(marginality))
warning("When orthogonalize = eigenmethods and marginality not supplied, labels = sources is ignored")
criteria <- c("aefficiency", "eefficiency", "mefficiency", "sefficiency", "xefficiency",
"order", "dforthog")
options <- c(criteria, "none", "all")
kcriteria <- options[unlist(lapply(which.criteria, check.arg.values,
options=options))]
if ("all" %in% kcriteria)
kcriteria <- criteria
anycriteria <- !("none" %in% kcriteria)
if (is.null(data) | !is.data.frame(data))
stop("Must supply a data.frame for data")
n <- nrow(data)
Q.G = projector(matrix(1, nrow=n, ncol=n)/n)
aliasing <- NULL
if (formula == ~1)
{
if (!grandMean)
warning("formula is for grand mean, yet grandMean is FALSE; it will be saved")
terms <- "Mean"
nterms <- 1
Q <- list(Mean = Q.G)
marginality <- diag(1, nrow = nterms, ncol = nterms)
rownames(marginality) <- terms
colnames(marginality) <- terms
sources <- terms
} else
{
terms <- attr(terms(formula, keep.order = keep.order, ...), which="term.labels")
nterms <- length(terms)
fac.list <- lapply(terms, fac.getinTerm)
names(fac.list) <- terms
facs <- unique(unlist(fac.list))
if (!all(facs %in% names(data)))
stop(paste("Some factor/covariates missing from data:",
paste0(facs[!(facs %in% names(data))], collapse = ", ")))
fac.modl <- model.frame(formula, data=data)
if (grandMean)
{
Q <- vector("list", length=nterms+1)
names(Q) <- c("Mean", terms)
Q[["Mean"]] <- Q.G
} else
{
Q <- vector("list", length=nterms)
names(Q) <- terms
}
for (k in 1:nterms)
{
Q[[terms[k]]] <- model.matrix(as.formula(paste("~ ",terms[k])), data=fac.modl)
Q[[terms[k]]] <- Q[[terms[k]]] %*% ginv(t(Q[[terms[k]]]) %*% Q[[terms[k]]]) %*% t(Q[[terms[k]]])
Q[[terms[k]]] <- projector(Q[[terms[k]]] - Q.G)
}
if (!is.null(marginality))
{
if (nrow(marginality) != nterms | ncol(marginality) != nterms)
stop(paste("The number of rows and columns in the supplied marginality matrix must be ",
"the same as the number of terms in the supplied formula"))
if (!all(rownames(marginality) == terms) | !all(colnames(marginality) == terms))
warning("Not all row and column names for the supplied marginality are the same as the expanded set of term names")
if (!all(marginality == 1 | marginality == 0))
stop("All elements of the supplied marginality matrix must be 0 or 1")
}
marg.mat <- diag(1, nrow = nterms, ncol = nterms)
rownames(marg.mat) <- terms
colnames(marg.mat) <- terms
if (length(terms) == 1)
{
marginality <- as.matrix(c(1))
rownames(marginality) <- colnames(marginality) <- terms
sources <- terms <- names(Q)
aliasing <- NULL
} else
{
if (orthogonalize == "hybrid")
{
nc <- 3 + length(criteria)
aliasing <- data.frame(matrix(nrow = 0, ncol=nc))
colnames(aliasing) <- c("Source", "df", "Alias", criteria)
eff.crit <- vector(mode="list",length=length(criteria))
names(eff.crit) <- criteria
for (i in 2:length(terms))
{
for (j in 1:(i-1))
{
if (marg.mat[i, i] == 1)
{
Qji <- Q[[terms[j]]] %*% Q[[terms[i]]]
if (!is.allzero(Qji))
{
if (is.allzero(Qji-Q[[terms[j]]]))
{
if (is.allzero(Q[[terms[j]]] - Q[[terms[i]]]))
{
aliasstatus <- "full"
marg.mat[terms[i], terms[i]] <- 0
warning(paste(terms[[i]],"is aliased with previous terms in the formula",
"and has been removed", sep=" "))
eff.crit[criteria] <- 1
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]],
df = degfree(Q[[terms[i]]]),
Alias = terms[[j]]),
eff.crit),
stringsAsFactors = FALSE),
data.frame(c(list(Source = terms[[i]],
df = 0,
Alias = "
eff.crit),
stringsAsFactors = FALSE))
} else
{
marg.mat[terms[j], terms[i]] <- 1
Q[[terms[i]]] <- projector(Q[[terms[i]]] - Q[[terms[j]]])
}
}
}
}
}
}
for (i in 2:length(terms))
{
Q.work <- Q[[terms[i]]]
Q.jcum <- Q.G
aliasstatus <- "none"
for (j in 1:(i-1))
{
if (marg.mat[j, j] == 1)
{
Q.jcum <- projector(Q.jcum + Q[[terms[j]]])
if (marg.mat[i, i] == 1)
{
Qji <- Q[[terms[j]]] %*% Q.work
if (!is.allzero(Qji))
{
if (is.allzero(Qji-Q[[terms[j]]]))
{
marg.mat[terms[j], terms[i]] <- 1
Q.work <- projector(Q.work - Q[[terms[j]]])
Q[[terms[i]]] <- Q.work
} else
{
if (is.allzero(Qji - Q.work))
{
aliasstatus <- "full"
marg.mat[terms[i], terms[i]] <- 0
warning(paste(terms[[i]],"is aliased with previous terms in the formula",
"and has been removed", sep=" "))
eff.crit[criteria] <- 1
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]],
df = degfree(Q.work),
Alias = terms[[j]]),
eff.crit),
stringsAsFactors = FALSE))
} else
{
aliasstatus <- "partial"
decompP <- proj2.combine(Q.work, Q[[terms[j]]])
keff.crit <- efficiency.criteria(decompP$efficiencies)
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]],
df = degfree(decompP$Qconf),
Alias = terms[[j]]),
keff.crit[criteria]),
stringsAsFactors = FALSE))
R <- projector(diag(1, nrow = n, ncol = n) - Q.jcum)
decomp <- proj2.combine(R, Q.work)
Q.work <- decomp$Qconf
}
}
}
}
}
}
if (aliasstatus == "partial")
{
decompR <- proj2.combine(Q[[terms[i]]], Q.work)
keff.crit <- efficiency.criteria(decompR$efficiencies)
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]],
df = degfree(decompR$Qconf),
Alias = "
keff.crit[criteria]),
stringsAsFactors = FALSE))
}
if (aliasstatus == "full")
{
keff.crit <- rep(0, length(criteria))
names(keff.crit) <- criteria
aliasing <- rbind(aliasing,
data.frame(c(list(Source = terms[[i]],
df = degfree(Q[[terms[i]]]),
Alias = "
keff.crit[criteria]),
stringsAsFactors = FALSE))
}
Q[[terms[i]]] <- Q.work
}
if (nrow(aliasing) > 0)
{
rownames(aliasing) <- NULL
class(aliasing) <- c("aliasing", "data.frame")
if (lab.opt == "sources")
{
tmp <- marg.mat
diag(tmp) <- 1
sources <- formSources(terms, tmp, grandMean = FALSE)
which.sources <- aliasing$Source %in% names(sources)
if (any(which.sources))
aliasing$Source[which.sources] <- sources[aliasing$Source[which.sources]]
which.sources <- aliasing$Alias %in% names(sources)
if (any(which.sources))
aliasing$Alias[which.sources] <- sources[aliasing$Alias[which.sources]]
}
attr(aliasing, which = "title") <-
"\nTable of information (partially) aliased with previous sources derived from the same formula\n\n"
if (aliasing.print)
{
if (anycriteria)
print(aliasing, which = kcriteria)
else
print(aliasing, which = "none")
}
} else
{
aliasing <- NULL
}
aliased <- (diag(marg.mat) == 0)
if (any(aliased))
{
marg.mat <- marg.mat[!aliased, !aliased]
Q <- Q[!aliased]
}
terms <- names(Q)
if (is.null(marginality))
{
sources <- formSources(terms, marg.mat, grandMean = grandMean)
marginality <- marg.mat
}
else
{
if (check.marginality & all(marg.mat == marginality))
warning("Supplied marginality matrix differs from that computed by pstructure formula")
sources <- formSources(terms, marginality, grandMean = grandMean)
}
if (lab.opt == "sources")
names(Q) <- sources
} else
{
if (orthogonalize == "differencing")
{
nc <- 3
aliasing <- data.frame(matrix(nrow = 0, ncol=nc))
colnames(aliasing) <- c("Source", "df", "Alias")
class(aliasing) <- c("aliasing", "data.frame")
eff.crit <- vector(mode="list",length=length(criteria))
names(eff.crit) <- criteria
orthogonal <- TRUE
fac.mat <- attr(terms(formula, keep.order = keep.order, ...), which="factors")
for (i in 2:length(terms))
{
Q.work <- Q[[terms[i]]]
for (j in 1:length(terms))
{
if (i != j)
{
if (all((fac.mat[,j] != 0) == (fac.mat[,j] & fac.mat[,i])))
{
Q.work <- Q.work - Q[[terms[j]]]
marg.mat[terms[j], terms[i]] <- 1
}
}
}
Q.work <- projector(Q.work)
if (degfree(Q.work) == 0)
{
marg.mat[terms[i], terms[i]] <- 0
warning(paste(terms[[i]],"is aliased with previous terms in the formula",
"and has been removed", sep=" "))
eff.crit[criteria] <- 1
aliasing <- rbind(aliasing,
data.frame(list(Source = terms[[i]], df = 0,
Alias = "unknown"),
eff.crit,
stringsAsFactors = FALSE))
}
else
{
i1 <- i - 1
if (i1 > 0)
for (j in 1:i1)
if (!is.allzero(Q.work %*% Q[[terms[j]]]))
{
warning(paste("** Projection matrices for ",terms[i], " and ", terms[j],
' are not orthogonal\n',
' Try orthogonalize = "hybrid" or "eigenmethods"', sep=""))
eff.crit[criteria] <- NA
aliasing <- rbind(aliasing,
data.frame(list(Source = terms[[i]], df = NA,
Alias = terms[[j]]),
eff.crit,
stringsAsFactors = FALSE))
}
}
Q[[terms[i]]] <- Q.work
}
if (nrow(aliasing) > 0)
{
rownames(aliasing) <- NULL
class(aliasing) <- c("aliasing", "data.frame")
if (lab.opt == "sources")
{
tmp <- marg.mat
diag(tmp) <- 1
sources <- formSources(terms, tmp, grandMean = FALSE)
which.sources <- aliasing$Source %in% names(sources)
if (any(which.sources))
aliasing$Source[which.sources] <- sources[aliasing$Source[which.sources]]
which.sources <- aliasing$Alias %in% names(sources)
if (any(which.sources))
aliasing$Alias <- sources[aliasing$Alias]
}
attr(aliasing, which = "title") <-
"\nTable of information (partially) aliased with previous sources derived from the same formula\n\n"
if (aliasing.print)
print(aliasing, which = "none")
} else
{
aliasing <- NULL
}
aliased <- (diag(marg.mat) == 0)
if (any(aliased))
{
marg.mat <- marg.mat[!aliased, !aliased]
Q <- Q[!aliased]
}
terms <- names(Q)
if (is.null(marginality))
{
sources <- formSources(terms, marg.mat, grandMean = grandMean)
marginality <- marg.mat
}
else
{
if (check.marginality & all(marg.mat == marginality))
warning("Supplied marginality matrix differs from that computed by pstructure formula")
sources <- formSources(terms, marginality, grandMean = grandMean)
}
if (lab.opt == "sources")
names(Q) <- sources
} else
{
R <- projector(diag(1, nrow = n, ncol = n) - Q[[terms[1]]] - Q.G)
if (length(terms) > 1)
{
Qorth <- projs.jandw(R, Q[terms[2:length(terms)]], which.criteria = kcriteria,
aliasing.print = aliasing.print)
Q <- c(Q[1:match(terms[1], names(Q))], Qorth$Q)
aliasing <- Qorth$aliasing
}
terms <- names(Q)
if (is.null(marginality))
{
sources <- terms
lab.opt <- "terms"
}
else
{
aliased <- !(terms %in% names(Q))
if (grandMean)
aliased <- aliased[-1]
marginality <- marginality[!aliased, !aliased]
sources <- formSources(terms, marginality, grandMean = grandMean)
names(Q) <- sources
lab.opt <- "sources"
}
}
}
}
}
struct <- list(Q = Q, terms = terms, sources = sources,
marginality = marginality, aliasing = aliasing)
class(struct) <- c("pstructure", "list")
attr(struct, which = "labels") <- lab.opt
if (omit.projectors)
struct$Q <- unlist(lapply(struct$Q, degfree))
return(struct)
} |
search_for_cis_spliced_peptides <- function(not_linear_list, proteome_db, with_parallel, customCores){
isnot_Linear <- create_spliced_peptides(not_linear_list)
isnot_Linear$id<- gsub("\\.x\\d+", "", rownames(isnot_Linear))
isnot_Linear$splicePattern <- paste0("(",isnot_Linear$Fragment1,
"((?!",isnot_Linear$Fragment1, ").)*?",
isnot_Linear$Fragment2,")")
isnot_Linear$id <- paste0(isnot_Linear$id, "-+*&x", isnot_Linear$spliceType,
"-,&x", isnot_Linear$splicePattern)
nbCores<- parallel::detectCores()
if (with_parallel == TRUE & nbCores > 5){
message('with parallel computing (cores)')
nbCores<- customCores
message(customCores)
cis_spliced_peptides <- cis_parallel(nbCores, isnot_Linear, proteome_db)
} else if (with_parallel == TRUE & nbCores < 5){
message('without parallel computing\n')
isnot_Linear_list<- stats::setNames(as.list(isnot_Linear$splicePattern), isnot_Linear$id)
cis_spliced_peptides <- find_cis_spliced_peptides (isnot_Linear_list, proteome_db)
} else if (with_parallel == FALSE){
message('without parallel computing\n')
isnot_Linear_list<- stats::setNames(as.list(isnot_Linear$splicePattern), isnot_Linear$id)
cis_spliced_peptides <- find_cis_spliced_peptides (isnot_Linear_list, proteome_db)
}
cis_spliced_fd<- data.frame(Fragment=rep(names(cis_spliced_peptides),
sapply(cis_spliced_peptides, length)),
indices=unlist(cis_spliced_peptides),
stringsAsFactors = FALSE)
cis_spliced_fd$ForwardOrReverse<- gsub(".*(\\-\\+\\*\\&x)","", cis_spliced_fd$Fragment)
cis_spliced_fd$ForwardOrReverse<- gsub("(\\-\\,\\&x).*","", cis_spliced_fd$ForwardOrReverse)
cis_spliced_fd$Peptide<- gsub(".*(\\-\\+xx)" ,"", cis_spliced_fd$Fragment, perl=TRUE)
cis_spliced_fd$ALC<- gsub(".*(\\-\\-xx)" ,"", cis_spliced_fd$Peptide, perl=TRUE)
cis_spliced_fd$Peptide<- gsub("(\\-\\-xx).*" ,"", cis_spliced_fd$Peptide, perl=TRUE)
cis_spliced_fd$ALC<- gsub("(\\-\\+\\*\\&x).*" ,"", cis_spliced_fd$ALC, perl=TRUE)
cis_spliced_fd$denovo_id<- gsub("(\\-\\+xx).*" ,"", cis_spliced_fd$Fragment, perl=TRUE)
cis_spliced_fd$splicePattern<- gsub(".*(\\-\\,\\&x)", "", cis_spliced_fd$Fragment)
cis_spliced_fd$spliced_peptide<- gsub("(\\(\\(\\?.*\\?)", "_", cis_spliced_fd$splicePattern)
cis_spliced_fd$spliced_peptide<- gsub("\\(|\\)", "", cis_spliced_fd$spliced_peptide)
cis_spliced_fd$full_annot <- seqinr::getAnnot(proteome_db[as.numeric(cis_spliced_fd$indices)])
cis_spliced_fd$accessionNumber<- names(proteome_db[as.numeric(cis_spliced_fd$indices)])
cis_spliced_fd$frag1 <- gsub("_.*", "", cis_spliced_fd$spliced_peptide)
cis_spliced_fd$frag2 <- gsub(".*_", "", cis_spliced_fd$spliced_peptide)
cis_spliced_fd$id<- paste0(cis_spliced_fd$denovo_id,"++",
cis_spliced_fd$indices,",,,+",
cis_spliced_fd$ForwardOrReverse,"[,.$-+",
cis_spliced_fd$spliced_peptide,"-+]",
cis_spliced_fd$ALC,"{++",
cis_spliced_fd$full_annot,"++}",
"+++", cis_spliced_fd$accessionNumber )
almost_final_cis<- get_detailed_cis_positions(cis_spliced_fd, proteome_db)
cis_spectrum_interim <- almost_final_cis
cis_spectrum_interim$duplid <- paste(cis_spectrum_interim$denovo_id,
cis_spectrum_interim$ReversetoForwardFullseq,
cis_spectrum_interim$GeneName)
cis_spectrum_interim <- cis_spectrum_interim[!duplicated(cis_spectrum_interim$duplid),]
cis_spectrum_interim$duplid <- paste(cis_spectrum_interim$denovo_id,
cis_spectrum_interim$ReversetoForwardFullseq)
cis_spectrum_interim <- cis_spectrum_interim[!duplicated(cis_spectrum_interim$duplid),]
uniquecisids<- unique(cis_spectrum_interim$denovo_id)
cis_spectrum_interim$ALC <- as.numeric(cis_spectrum_interim$ALC)
cis_spectrum_interim2<- by(cis_spectrum_interim, cis_spectrum_interim["denovo_id"],
function(z) z[which(z$ALC[z$denovo_id %in% uniquecisids] == max(z$ALC)),])
cis_spectrum_interim2<- do.call(rbind, cis_spectrum_interim2)
final_cis<- cis_spectrum_interim2
final_df_cis_peptides<- data.frame(Peptide=final_cis$ReversetoForwardFullseq,
Fragment=final_cis$Peptide,
denovo_id= final_cis$denovo_id ,
Length=nchar(final_cis$ReversetoForwardFullseq), Type="cis",
spliceType=final_cis$ForwardOrReverse,
ALC= final_cis$ALC,
stringsAsFactors = FALSE)
not_cis <- data.frame(Names=names(cis_spliced_peptides[unlist(lapply(
cis_spliced_peptides, function(x) length(x)<1))]),stringsAsFactors=FALSE)
not_cis$id<- gsub("\\_x\\d+$","", not_cis$Names)
not_cis$ALC <- gsub(".*(\\-\\-xx)","", not_cis$id)
not_cis$Peptide<- gsub(".*(\\-\\+xx)","", not_cis$id)
not_cis$Peptide <- gsub("(\\-\\-xx).*","", not_cis$Peptide)
not_cis$denovo_id<- gsub("(\\-\\+xx).*","", not_cis$id)
not_cis$ALC <- gsub("(\\-\\+\\*\\&x).*","", not_cis$ALC)
not_cis_ids<- not_cis$denovo_id %in% cis_spectrum_interim2$denovo_id
not_cis <- not_cis[!not_cis_ids,]
not_cis$id <- gsub("(\\-\\+\\*\\&x).*", "", not_cis$id)
not_cis<- not_cis[!duplicated(not_cis$id),]
not_cis_list<- stats::setNames(as.list(not_cis$Peptide), not_cis$id)
not_cis_list <- not_cis_list[which(!is.na(not_cis_list))]
cis_peptides_output<- list(not_cis_list, final_df_cis_peptides)
return(cis_peptides_output)
} |
dotchart <-
function(x, labels = NULL, groups = NULL, gdata = NULL,
cex = par("cex"), pt.cex = cex,
pch = 21, gpch = 21, bg = par("bg"), color = par("fg"),
gcolor = par("fg"), lcolor = "gray",
xlim = range(x[is.finite(x)]),
main = NULL, xlab = NULL, ylab = NULL, ...)
{
opar <- par("mai", "mar", "cex", "yaxs")
on.exit(par(opar))
par(cex = cex, yaxs = "i")
if(!is.numeric(x))
stop("'x' must be a numeric vector or matrix")
n <- length(x)
if (is.matrix(x)) {
if (is.null(labels))
labels <- rownames(x)
if (is.null(labels))
labels <- as.character(1L:nrow(x))
labels <- rep_len(labels, n)
if (is.null(groups))
groups <- col(x, as.factor = TRUE)
glabels <- levels(groups)
} else {
if (is.null(labels)) labels <- names(x)
glabels <- if(!is.null(groups)) levels(groups)
if (!is.vector(x)) {
warning("'x' is neither a vector nor a matrix: using as.numeric(x)")
x <- as.numeric(x)
}
}
plot.new()
linch <-
if(!is.null(labels)) max(strwidth(labels, "inch"), na.rm = TRUE) else 0
if (is.null(glabels)) {
ginch <- 0
goffset <- 0
}
else {
ginch <- max(strwidth(glabels, "inch"), na.rm = TRUE)
goffset <- 0.4
}
if (!(is.null(labels) && is.null(glabels))) {
nmai <- par("mai")
nmai[2L] <- nmai[4L] + max(linch + goffset, ginch) + 0.1
par(mai = nmai)
}
if (is.null(groups)) {
o <- 1L:n
y <- o
ylim <- c(0, n + 1)
}
else {
o <- sort.list(as.numeric(groups), decreasing = TRUE)
x <- x[o]
groups <- groups[o]
color <- rep_len(color, length(groups))[o]
lcolor <- rep_len(lcolor, length(groups))[o]
offset <- cumsum(c(0, diff(as.numeric(groups)) != 0))
y <- 1L:n + 2 * offset
ylim <- range(0, y + 2)
}
plot.window(xlim = xlim, ylim = ylim, log = "")
lheight <- par("csi")
if (!is.null(labels)) {
linch <- max(strwidth(labels, "inch"), na.rm = TRUE)
loffset <- (linch + 0.1)/lheight
labs <- labels[o]
mtext(labs, side = 2, line = loffset, at = y, adj = 0,
col = color, las = 2, cex = cex, ...)
}
abline(h = y, lty = "dotted", col = lcolor)
points(x, y, pch = pch, col = color, bg = bg, cex = pt.cex/cex)
if (!is.null(groups)) {
gpos <- rev(cumsum(rev(tapply(groups, groups, length)) + 2) - 1)
ginch <- max(strwidth(glabels, "inch"), na.rm = TRUE)
goffset <- (max(linch+0.2, ginch, na.rm = TRUE) + 0.1)/lheight
mtext(glabels, side = 2, line = goffset, at = gpos,
adj = 0, col = gcolor, las = 2, cex = cex, ...)
if (!is.null(gdata)) {
abline(h = gpos, lty = "dotted")
points(gdata, gpos, pch = gpch, col = gcolor, bg = bg,
cex = pt.cex/cex, ...)
}
}
axis(1)
box()
title(main=main, xlab=xlab, ylab=ylab, ...)
invisible()
} |
NULL
fastqc <- function(fq.dir = getwd(), qc.dir = NULL, threads = 4, fastqc.path = "~/bin/FastQC/fastqc")
{
.check_if_unix()
if(is.null(qc.dir)) qc.dir <- file.path(fq.dir, "FASTQC")
.create_dir(qc.dir)
cmd <- paste0(fastqc.path, " ", fq.dir, "/* --threads ", threads, " --outdir ", qc.dir)
system(cmd)
} |
add_title=function(x,title="",size=20,color=NULL,before=TRUE,after=TRUE){
bold_face <- shortcuts$fp_bold(font.size = size)
if(!is.null(color)) bold_face=update(bold_face,color=color)
fpar1=fpar(ftext(title, prop = bold_face))
if(before) x <- x %>% body_add_par("",style="Normal")
x <- x %>% body_add_fpar(fpar1)
if(after) x <- x %>% body_add_par("",style="Normal")
x
}
add_self=function(mydoc,data){
if(class(mydoc)=="rpptx"){
mydoc <- mydoc %>% add_slide("Blank",master="Office Theme")
mydoc<-mydoc %>% ph_with(value=df2flextable2(data), location = ph_location(left=1,top=2))
} else{
mydoc<-mydoc %>% body_add_par(value="\n\n",style="Normal")
mydoc<-mydoc %>% body_add_flextable(df2flextable2(data))
mydoc<-mydoc %>% body_add_par(value="\n\n",style="Normal")
}
mydoc
}
add_text2hyperlink=function(mydoc,text){
if(str_detect(text,"\\]\\(")){
devide=function(x){
ref=str_extract(x,"\\(.*\\)")
x=str_remove(x,"\\(.*\\)")
str=str_extract(x,"\\[.*\\]")
text=str_remove(x,"\\[.*\\]")
str=substr(str,2,nchar(str)-1)
ref=substr(ref,2,nchar(ref)-1)
list(text=text,str=str,ref=ref)
}
temp=str_extract_all(text,".*?\\[.*?\\]\\(.*?\\)")
result=lapply(temp,devide)
for(i in 1:length(result[[1]]$text)){
if(i==1) {
mydoc=ph_with(mydoc,value=result[[1]]$text[i],location = ph_location_type(type="body"))
} else{
mydoc=ph_add_text(mydoc,type="body",str=result[[1]]$text[i])
}
mydoc=ph_add_text(mydoc,type="body",str=result[[1]]$str[i],href=result[[1]]$ref[i])
}
} else{
mydoc=ph_with(mydoc, text, location = ph_location_type(type="body"))
}
mydoc
}
add_text=function(mydoc,title="",text="",code="",preprocessing="",echo=FALSE,eval=FALSE,style="Normal",landscape=FALSE){
if(class(mydoc)=="rpptx"){
layout="Title and Content"
if((title=="")&(text=="")) layout="Blank"
else if(text=="") layout="Title Only"
mydoc <- mydoc %>%
add_slide(layout = layout, master = "Office Theme")
if(title!=""){
mydoc <- mydoc %>%
ph_with(value=title, location = ph_location_type(type="title"))
}
if(text!=""){
mydoc <- mydoc %>%
add_text2hyperlink(text=text)
}
pos=1.5
if(echo) {
if(code!=""){
codeft=Rcode2flextable(code,preprocessing=preprocessing,eval=eval,format="pptx")
mydoc<-mydoc %>% ph_with(value=codeft, location = ph_location(left=1,top=pos))
pos=2
}
}
} else{
if(landscape) {
mydoc <- mydoc %>% body_end_section_portrait()
}
mydoc <- mydoc %>% add_title(title)
if(text!="") mydoc<-mydoc %>% body_add_par(value=text,style=style)
if(echo) {
if(code!=""){
codeft=Rcode2flextable(code,eval=eval,format="docx")
mydoc<-mydoc %>% body_add_par(value="\n\n",style="Normal")
mydoc<-mydoc %>% body_add_flextable(codeft)
mydoc<-mydoc %>% body_add_par(value="\n\n",style="Normal")
}
}
}
mydoc
}
add_2ggplots=function(mydoc,plot1,plot2,preprocessing="",width=3,height=2.5,top=2){
if(preprocessing!="") {
eval(parse(text=preprocessing))
}
gg1<-eval(parse(text=plot1))
gg2<-eval(parse(text=plot2))
if(class(mydoc)=="rpptx"){
mydoc<- mydoc %>%
ph_with(dml(code = print(gg1)), location = ph_location(left=0.5,top=top,width=4.5,height=5) ) %>%
ph_with(dml(code = print(gg2)), location = ph_location(left=5,top=top,width=4.5,height=5 ))
} else{
mydoc <- mydoc %>%
body_end_section_continuous()
mydoc <-mydoc %>%
body_add_gg(value=gg1,width=width,height=height) %>%
body_add_gg(value=gg2,width=width,height=height) %>%
body_end_section_columns(widths = c(width, width), space = .05, sep = FALSE)
}
mydoc
}
add_2flextables=function(mydoc,ft1,ft2,echo=FALSE,width=3,code=""){
pos=1.5
if(echo & (code!="")) pos=2
if(class(mydoc)=="rpptx"){
mydoc<-mydoc %>%
ph_with(value=ft1, location = ph_location(left=0.5,top=pos)) %>%
ph_with(value=ft2, location = ph_location(left=5,top=pos))
} else {
mydoc <- mydoc %>%
body_end_section_continuous()
mydoc <-mydoc %>%
body_add_flextable(value=ft1) %>%
body_add_flextable(value=ft2) %>%
slip_in_column_break() %>%
body_end_section_columns()
}
mydoc
}
getCodeOption=function(x,what="echo"){
result=FALSE
x=unlist(strsplit(x,","))
x=x[str_detect(x,what)]
if(length(x)>0){
x=unlist(strsplit(x,"="))[2]
result=eval(parse(text=x))
}
result
} |
ifafgwc <- function (data, pop=NA, distmat=NA, ncluster=2, m=2, distance='euclidean', order=2, alpha=0.7, a=1, b=1,
error=1e-5, max.iter=100,randomN=0,vi.dist="uniform", ei.distr="normal",
fa.same=10, nfly=10, ffly.no=2, ffly.dist='euclidean', ffly.order=2, gamma=1, ffly.beta=1,
ffly.alpha=1, r.chaotic=4,m.chaotic=0.7,ind.levy=1,skew.levy=0,scale.levy=1,ffly.alpha.type=4) {
randomnn <- randomN
ptm<-proc.time()
n <- nrow(data)
d <- ncol(data)
iter=0
gen=1
beta <- 1-alpha
same=0
data <- as.matrix(data)
if (alpha ==1) {
pop <- rep(1,n)
distmat <- matrix(1,n,n)
}
datax <- data
pop <- matrix(pop,ncol=1)
mi.mj <- pop%*%t(pop)
ffly.finalbest <- init.swarm(data, mi.mj, distmat, distance, order, vi.dist, ncluster,
m, alpha, a, b, randomN, 1)
inten.finalbest <- ffly.finalbest$I
conv <- c(inten.finalbest)
ffly.finalpos <- ffly.finalbest$centroid
ffly.finalpos.other <- ffly.finalbest$membership
ffly.new <- init.swarm(data, mi.mj, distmat, distance, order, vi.dist, ncluster,
m, alpha, a, b, randomN, nfly)
ffly.swarm <- ffly.new$centroid
ffly.other <- ffly.new$membership
inten <- ffly.new$I
repeat {
set.seed(randomN)
ffly.alpha <- update_alpha(ffly.alpha,gen,max.iter,ffly.alpha.type)
set.seed(randomN)
ffly.swarm <- ffly.new$centroid <- moving(ffly.new,ffly.no,ffly.beta,gamma,ffly.alpha,ffly.dist,ffly.order,ei.distr,
r.chaotic,m.chaotic,ind.levy,skew.levy,scale.levy,data,m,distance,order,mi.mj,distmat,alpha,beta,a,b,randomN)
ffly.other <- ffly.new$membership <- lapply(1:nfly, function(x) uij(data,ffly.swarm[[x]],m,distance,order))
ffly.other <- ffly.new$membership <- lapply(1:nfly, function(x) renew_uij(data,ffly.new$membership[[x]]$u,mi.mj,distmat,alpha,beta,a,b))
ffly.swarm <- ffly.new$centroid <- lapply(1:nfly, function(x) vi(data,ffly.new$membership[[x]],m))
inten <- ffly.new$I <- sapply(1:nfly, function(x) jfgwcv(data,ffly.new$centroid[[x]],m,distance,order))
best <- which(inten==min(inten))[1]
ffly.curbest <- ffly.swarm[[best]]
ffly.curbest.other <- ffly.other[[best]]
inten.curbest <- inten[best]
conv <- c(conv,inten.finalbest)
if (abs(conv[gen+1]-conv[gen])<error) {
same <- same+1
}
else {
same <- 0
}
if (inten.curbest<=inten.finalbest) {
ffly.finalpos <- ffly.curbest
ffly.finalpos.other <- ffly.curbest.other
inten.finalbest <- inten.curbest
}
gen <- gen+1
randomN <- randomN+nfly
if (gen==max.iter || same==fa.same) break
}
if (any(class(ffly.finalpos.other)=="list")) {
new_uij <- ffly.finalpos.other[[1]]
vi <- ffly.finalpos[[1]]
}
else {
new_uij <- ffly.finalpos.other
vi <- ffly.finalpos
}
finaldata=determine_cluster(datax,new_uij)
cluster=finaldata[,ncol(finaldata)]
ifa <- list("converg"=conv,"f_obj"=jfgwcv(data,vi,m,distance,order),"membership"=new_uij,"centroid"=vi,
"validation"=index_fgwc(data,cluster,new_uij,vi,m,exp(1)), "cluster"=cluster,
"finaldata"=finaldata, "call"=match.call(),"iteration"=gen,"same"=same,"time"=proc.time()-ptm)
print(c(order, ncluster,m, randomN))
class(ifa) <- 'fgwc'
return (ifa)
}
init.swarm <- function(data, pop, distmat, distance, order, vi.dist, ncluster,
m, alpha, a, b, randomN, nfly) {
inten <- rep(0,nfly)
beta <- 1-alpha
start.uij <- lapply(1:nfly, function(x) gen_uij(data,ncluster,nrow(data),randomN+x))
start.uij <- lapply(1:nfly, function (x) renew_uij(data,start.uij[[x]],pop,distmat,alpha,beta,a,b))
start.vi <- lapply(1:nfly, function (x) vi(data,start.uij[[x]],m))
for(i in 1:nfly) {
inten[i] <- jfgwcv(data,start.vi[[i]],m,distance,order)
}
result <- list("membership"=start.uij,"centroid"=start.vi,"I"=inten)
return(result)
}
intel.ffly <- function(ffly.list,no) {
best <- order(ffly.list$I,decreasing = F)[1:no]
intel.uij <- lapply(best, function(x) ffly.list$membership[[x]])
intel.vi <- lapply(best, function(x) ffly.list$centroid[[x]])
inten <- ffly.list$I[best]
result <- list("membership"=intel.uij,"centroid"=intel.vi,"I"=inten)
return(result)
}
swarm_dist <- function (swarm1,swarm2,distance,order) {
return(diag(dist(swarm1,swarm2,distance,order)))
}
moving <- function(ffly.all,no,ff.beta,gamma,ff.alpha,ffly.dist,ffly.order,ei.distr,r.chaotic,m.chaotic,ind.levy,skew.levy,sca.levy,
data,m,distance,order,mi.mj,dist,alpha,beta,a,b,randomN){
times <- 0
intel.ffly <- intel.ffly(ffly.all,no)
dd <- dim(ffly.all$centroid[[1]])
ffly <- ffly.all$centroid
fit <- ffly.all$I
for(i in 1:length(intel.ffly$centroid)){
for(j in 1:length(ffly)){
r <- diag(cdist(ffly[[j]],intel.ffly$centroid[[i]],ffly.dist,ffly.order))
ei <- matrix(eiDist(ei.distr,dd[1]*dd[2],randomN+i+j,r.chaotic,m.chaotic,ind.levy,skew.levy,sca.levy),ncol=dd[2])
if (fit[j] > intel.ffly$I[i]){
ffly[[j]]+beta*exp(-gamma*r^2)*(intel.ffly$centroid[[i]]-ffly[[j]])+(ff.alpha*ei)
}
else{
times <- times+1
if(times==no){
ffly[[j]]+(ff.alpha*ei)
}
}
fit[j] <- jfgwcv2(data,ffly[[j]],m,distance,order,mi.mj,dist,alpha,beta,a,b)
}
}
return(ffly)
} |
selective_flattening <- function(x,
what,
recursionLevel = 0,
silent = justifier::opts$get("silent")) {
msg(spc(recursionLevel),
"Selectively flattening an object called '",
deparse(substitute(x)), "' only selecting ",
what, " specifications.\n",
silent = silent);
justifierClass <-
paste0(
"justifier",
tools::toTitleCase(what)
);
justifierPlural <-
paste0(tolower(what), "s");
if ((inherits(x, justifierClass)) && (inherits(x, "singleJustifierElement"))) {
msg(spc(recursionLevel),
"Single justifier element present with identifier '",
x$id, "'.\n",
silent = silent);
res <- emptyStructuredJustifierObject;
classToUse <- class(res[[justifierPlural]]);
res[[justifierPlural]] <- list(x);
class(res[[justifierPlural]]) <- classToUse;
names(res[[justifierPlural]]) <-
get_ids_from_structured_justifierElements(
res[[justifierPlural]]
);
class(res) <- c("justifier", "justifierStructuredObject", "list");
return(res);
} else if ((inherits(x, justifierClass)) && (inherits(x, "multipleJustifierElements"))) {
msg(spc(recursionLevel),
length(x), " elements present, calling myself recursively to structure them.\n",
silent = silent);
res <-
do.call(
c,
lapply(
x,
selective_flattening,
what = what,
recursionLevel = recursionLevel + 1,
silent = silent
)
);
res <- unlist(res, recursive = FALSE);
class(res) <- c("justifier", "justifierStructuredObject", "list");
return(res);
} else {
stop("You passed an object that isn't a singleJustifierElement of ",
"class ", justifierClass, " or a list of ",
"multipleJustifierElements. Instead, it has class(es) ",
vecTxtQ(class(x)), "...");
}
} |
reassign_gen = function(ped_file){
if (!is.ped(ped_file)) {
stop("\n \n Expecting a ped object. \n Please use new.ped to create an object of class ped.")
}
if(!"Gen" %in% colnames(ped_file)){
ped_file$Gen <- assign_gen(ped_file)
}
if (sum(ped_file$affected[ped_file$available]) == 0) {
stop("\n \n No disease-affected relatives present. \n Cannot reassign generations.")
}
if (sum(ped_file$affected[ped_file$available]) == 1) {
gped <- ped_file[ped_file$affected & ped_file$available, ]
gped$Gen <- 1
warning(paste0("\n \n Family ", gped$FamID, " only contains one disease-affected relative."))
return(gped)
}
gped <- ped_file[ped_file$affected & ped_file$available, ]
d <- 0
while (d == 0) {
readd_dad <- find_missing_parent(gped)
readd_mom <- find_missing_parent(gped, dad = FALSE)
if (length(c(readd_dad, readd_mom)) == 0) {
d <- 1
} else {
readd <- ped_file[which(ped_file$ID %in% c(readd_dad, readd_mom)), ]
gped <- rbind(gped, readd)
}
}
pedgre <- ped2pedigree(gped)
if (any(align.pedigree(pedgre)$spouse == 2)) {
stop("\n \n Inbreeding detected. \n reassign_gen is not intended for pedigrees that contain loops or inbreeding.")
}
id_array <- as.numeric(align.pedigree(pedgre)$nid)
id_array <- id_array[id_array != 0]
if (any(duplicated(id_array))) {
stop("\n \n Loop detected. \n reassign_gen is not intended for pedigrees that contain loops or inbreeding.")
}
kin_mat <- kinship(pedgre)
if (any(kin_mat[gped$affected & gped$available,
gped$affected & gped$available] == 0)) {
ak_mat <- kin_mat[gped$affected & gped$available,
gped$affected & gped$available]
url1 <- colnames(ak_mat)[which(ak_mat == 0, arr.ind = T)[1, 1]]
url2 <- colnames(ak_mat)[which(ak_mat == 0, arr.ind = T)[1, 2]]
stop(paste0("\n \n The disease-affected relatives with ID numbers ", url1, " and ", url2, " are not related. \n Cannot determine most recent common ancestor for unrelated affecteds."))
}
old_gen <- gped$Gen
gped$Gen <- ifelse(gped$affected, gped$Gen, NA)
gen_tab <- table(gped$Gen)
min_gens <- as.numeric(names(gen_tab[c(1, 2)]))
num_in_min_gen <- as.numeric(gen_tab[1])
if (min_gens[1] == 1 | (min_gens[1] == 2 & num_in_min_gen >= 2)) {
return(gped)
} else {
pair_mat <- combn(x = gped$ID[gped$affected & gped$available], m = 2)
mrca <- unique(unlist(lapply(1:ncol(pair_mat), function(x){
find_mrca(gped, pair_mat[1, x], pair_mat[2, x])
})))
if (length(mrca) > 1){
new_gen_diff <- min(old_gen[which(gped$ID %in% mrca)]) - 1
} else {
new_gen_diff <- old_gen[which(gped$ID == mrca)] - 1
}
gped$Gen[!is.na(gped$Gen)] <- gped$Gen[!is.na(gped$Gen)] - new_gen_diff
return(gped)
}
}
censor_ped = function(ped_file, censor_year = NULL){
if (!is.ped(ped_file)) {
stop("\n \n Expecting a ped object. \n Please use new.ped to create an object of class ped.")
}
if (any(is.na(match(c("birthYr", "onsetYr", "deathYr"),
colnames(ped_file))))) {
stop("\n \n Missing date data. \n Please ensure that ped_file includes the following variables:\n birthYr, onsetYr, deathYr" )
}
if (all(is.na(ped_file$birthYr))
& all(is.na(ped_file$onsetYr))
& all(is.na(ped_file$deathYr))) {
stop("\n \n Nothing to censor, all date data is missing.")
}
if (is.null(censor_year)) {
if ("proband" %in% colnames(ped_file)) {
if(sum(ped_file$proband) == 1){
if (is.na(ped_file$onsetYr[ped_file$proband])) {
stop("\n \n Proband's onset year is missing. \n Specify the proband's onset year or specify censor_year.")
} else {
censor_year <- ped_file$onsetYr[ped_file$proband]
}
} else {
stop("\n \n Proband cannot be uniquely identified.\n Please identify a single proband or specify censor_year. \n ")
}
} else {
stop("\n \n Proband cannot be identified. \n Please identify a proband or specify censor_year.")
}
}
ped_file$affected <- ifelse(is.na(ped_file$onsetYr), FALSE,
ifelse(ped_file$onsetYr <= censor_year, T, F))
ped_file$onsetYr <- ifelse(is.na(ped_file$onsetYr), NA,
ifelse(ped_file$onsetYr <= censor_year,
ped_file$onsetYr, NA))
ped_file$deathYr <- ifelse(is.na(ped_file$deathYr), NA,
ifelse(ped_file$deathYr <= censor_year,
ped_file$deathYr, NA))
if ("proband" %in% colnames(ped_file)) {
ped_file$proband[ped_file$proband] <- ifelse(is.na(ped_file$onsetYr[ped_file$proband]),
FALSE, ped_file$proband[ped_file$proband])
}
if (all(is.na(ped_file$birthYr))) {
censored_ped <- ped_file
warning("\n \n Birth data not detected. \n Censoring onset and death data only")
} else {
censored_ped <- ped_file[which(ped_file$birthYr <= censor_year), ]
if (nrow(censored_ped) == 0) {
warning("\n \n No data recorded prior to the specified year.")
return(censored_ped)
} else {
d <- 0
while (d == 0) {
readd_dad <- find_missing_parent(censored_ped)
readd_mom <- find_missing_parent(censored_ped, dad = FALSE)
if (length(c(readd_dad, readd_mom)) == 0) {
d <- 1
} else {
readd <- ped_file[which(ped_file$ID %in% c(readd_dad, readd_mom)), ]
censored_ped <- rbind(censored_ped, readd)
}
}
}
}
return(censored_ped)
}
get_affectedInfo <- function(ped_file){
aLoc <- match(c("available"), colnames(ped_file))
if (is.na(aLoc)) {
ped_file$available <- T
}
dA_loc <- match(c("DA1", "DA2"), colnames(ped_file))
if (length(dA_loc[!is.na(dA_loc)]) == 2) {
ped_file$RVstatus <- ped_file$DA1 + ped_file$DA2
}
keep_cols <- match(c("FamID", "ID",
"birthYr", "onsetYr", "deathYr",
"RR", "proband", "RVstatus", "subtype"), colnames(ped_file))
affected_info <- ped_file[ped_file$affected & ped_file$available,
keep_cols[!is.na(keep_cols)]]
rownames(affected_info) <- NULL
class(affected_info) <- "data.frame"
return(affected_info)
}
get_kinship <- function(ped_file){
aLoc <- match(c("available"), colnames(ped_file))
if (is.na(aLoc)) {
ped_file$available <- T
}
kin_ped <- ped2pedigree(ped_file)
kinMat <- kinship(kin_ped)[ped_file$affected & ped_file$available,
ped_file$affected & ped_file$available]
return(kinMat)
}
get_famInfo <- function(ped_file, s_ID = NULL){
AV <- get_affectedInfo(ped_file)
SRV <- ifelse(any(is.na(match(c("DA1", "DA2"), colnames(ped_file)))), NA,
ifelse(any(ped_file$DA1 == 1) | any(ped_file$DA2 == 1), TRUE, FALSE))
YRcols <- match(c("birthYr", "onsetYr"), colnames(ped_file))
AOO <- ifelse(nrow(AV) > 0 & length(YRcols[!is.na(YRcols)]) == 2,
mean(AV$onsetYr - AV$birthYr, na.rm = T), NA)
AY <- ifelse(nrow(AV) > 0
& !is.na(match(c("proband"), colnames(ped_file))) & sum(AV$proband) == 1,
AV$onsetYr[AV$proband], NA)
AK <- get_kinship(ped_file)
AIBD <- ifelse(nrow(AV) > 0, 2*mean(AK[upper.tri(AK)]), NA)
FamDat <- data.frame(FamID = ped_file$FamID[1],
totalRelatives = nrow(ped_file),
numAffected = nrow(AV),
aveOnsetAge = AOO,
aveIBD = AIBD,
ascertainYear = AY,
segRV = SRV)
if (!is.null(s_ID)) {
k = length(s_ID)
subDat <- as.data.frame(matrix(NA, ncol = k, nrow = 1))
colnames(subDat) = paste0("p_", s_ID)
subDat[1, ] <- sapply(1:length(s_ID), function(x){
sum(AV$subtype == s_ID[x])/nrow(AV)
})
FamDat <- cbind(FamDat, subDat)
}
return(FamDat)
} |
lineups_players <- function(df1,n){
if(ncol(df1)==29){
if(n==1){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM),
by=list(PG=df1$PG), FUN=sum)
PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE)
P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE)
P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE)
PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE)
df1 = cbind(df1,PFG,P3P,P2P,PFT)
df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21))
df1[5][is.na(df1[5])] <- 0
df1[8][is.na(df1[8])] <- 0
df1[11][is.na(df1[11])] <- 0
df1[14][is.na(df1[14])] <- 0
names(df1) = c("PG","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-")
}else if(n==2){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM),
by=list(SG=df1$SG), FUN=sum)
PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE)
P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE)
P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE)
PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE)
df1 = cbind(df1,PFG,P3P,P2P,PFT)
df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21))
df1[5][is.na(df1[5])] <- 0
df1[8][is.na(df1[8])] <- 0
df1[11][is.na(df1[11])] <- 0
df1[14][is.na(df1[14])] <- 0
names(df1) = c("SG","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-")
}else if(n==3){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM),
by=list(SF=df1$SF), FUN=sum)
PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE)
P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE)
P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE)
PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE)
df1 = cbind(df1,PFG,P3P,P2P,PFT)
df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21))
df1[5][is.na(df1[5])] <- 0
df1[8][is.na(df1[8])] <- 0
df1[11][is.na(df1[11])] <- 0
df1[14][is.na(df1[14])] <- 0
names(df1) = c("SF","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-")
}else if(n==4){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM),
by=list(PF=df1$PF), FUN=sum)
PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE)
P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE)
P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE)
PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE)
df1 = cbind(df1,PFG,P3P,P2P,PFT)
df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21))
df1[5][is.na(df1[5])] <- 0
df1[8][is.na(df1[8])] <- 0
df1[11][is.na(df1[11])] <- 0
df1[14][is.na(df1[14])] <- 0
names(df1) = c("PF","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-")
}else if(n==5){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","FGA","Percentage FG","TP","TPA","Percentage 3P","TWP","TWPA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$FGA,df1$TP,df1$TPA,df1$TWP,df1$TWPA,df1$FT,df1$FTA,df1$ORB,df1$DRB,df1$TRB,df1$AST,df1$STL,df1$BLK,df1$TOV,df1$PPF,df1$P,df1$M,df1$PM),
by=list(C=df1$C), FUN=sum)
PFG<-sample(c(round(df1[3]/df1[4],3)), size = 1, replace = TRUE)
P3P<-sample(c(round(df1[5]/df1[6],3)), size = 1, replace = TRUE)
P2P<-sample(c(round(df1[7]/df1[8],3)), size = 1, replace = TRUE)
PFT<-sample(c(round(df1[9]/df1[10],3)), size = 1, replace = TRUE)
df1 = cbind(df1,PFG,P3P,P2P,PFT)
df1 = subset (df1, select=c(1,2,3,4,22,5,6,23,7,8,24,9,10,25,11,12,13,14,15,16,17,18,19,20,21))
df1[5][is.na(df1[5])] <- 0
df1[8][is.na(df1[8])] <- 0
df1[11][is.na(df1[11])] <- 0
df1[14][is.na(df1[14])] <- 0
names(df1) = c("C","MP","FG","FGA","Percentage FG","3P","3PA","Percentage 3P","2P","2PA","Percentage 2P","FT","FTA","Percentage FT",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PF","+","-","+/-")
}
}
else if(ncol(df1)==41){
if(n==1){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB,
df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM),
by=list(PG=df1$PG), FUN=sum)
names(df1) = c("PG","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-")
}else if(n==2){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB,
df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM),
by=list(SG=df1$SG), FUN=sum)
names(df1) = c("SG","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-")
}else if(n==3){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB,
df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM),
by=list(SF=df1$SF), FUN=sum)
names(df1) = c("SF","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-")
}else if(n==4){
names(df1) = c("PG","SG","SF","PPF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB,
df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM),
by=list(PF=df1$PF), FUN=sum)
names(df1) = c("PF","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-")
}else if(n==5){
names(df1) = c("PG","SG","SF","PF","C","MP","FG","oFG","FGA","oFGA","TP","oTP","TPA","oTPA","TWP","oTWP","TWPA","oTWPA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PPF","oPF","P","M","PM")
df1 <- aggregate(cbind(df1$MP,df1$FG,df1$oFG,df1$FGA,df1$oFGA,df1$TP,df1$oTP,df1$TPA,df1$oTPA,df1$TWP,df1$oTWP,df1$TWPA,df1$oTWPA,df1$FT,df1$oFT,df1$FTA,df1$oFTA,df1$ORB,df1$oORB,
df1$DRB,df1$oDRB,df1$TRB,df1$oTRB,df1$AST,df1$oAST,df1$STL,df1$oSTL,df1$BLK,df1$oBLK,df1$TOV,df1$oTOV,df1$PPF,df1$oPF,df1$P,df1$M,df1$PM),
by=list(C=df1$C), FUN=sum)
names(df1) = c("C","MP","FG","oFG","FGA","oFGA","3P","o3P","3PA","o3PA","2P","o2P","2PA","o2PA","FT","oFT","FTA","oFTA",
"ORB","oORB","DRB","oDRB","TRB","oTRB","AST","oAST","STL","oSTL","BLK","oBLK","TOV","oTOV","PF","oPF","+","-","+/-")
}
}
return(df1)
} |
fncPairedpROC <- function(){
varPosListn <- function(vars, var){
if (is.null(var)) return(NULL)
if (any(!var %in% vars)) NULL
else apply(outer(var, vars, "=="), 1, which) - 1
}
defaults <- list(
initial.prediction = NULL, initial.prediction2 = NULL, initial.label = NULL,
initial.narm = 1, initial.percent = 0, initial.direction = "auto",
initial.testmethod = "auto", initial.testalternative = "two.sided",
initial.testbootn = "2000", initial.testbootstratified = 1,
initial.smooth = 0, initial.smoothingmethod = "binormal",
initial.smoothinbandwidth = "nrd0", initial.bandwidthnumeric = "",
initial.bandwidthadjustment = "1", initial.bandwidthwindow = "gaussian",
initial.distributioncontrols = "normal", initial.distributioncases = "normal",
initial.smoothingmethod2 = "binormal",
initial.smoothinbandwidth2 = "nrd0", initial.bandwidthnumeric2 = "",
initial.bandwidthadjustment2 = "1", initial.bandwidthwindow2 = "gaussian",
initial.distributioncontrols2 = "normal", initial.distributioncases2 = "normal",
initial.cicompute = 1, initial.cilevel = "0.95", initial.cimethod = "bootstrap",
initial.cibootn = "2000", initial.cibootstratified = 0,
initial.citype = "se", initial.cithresholds = "local maximas",
initial.civalues = "seq(0, 1, 0.05)", initial.ciplottype = "shape",
initial.civalues2 = "seq(0, 1, 0.05)",
initial.auc = 1, initial.partialauc = 0,
initial.partialfrom = 0, initial.partialto = 1,
initial.partialfocus = "specificity", initial.partialcorrect = 0,
initial.plot = 1,
initial.printauc = 0, initial.aucpolygon = 0, initial.maxaucpolygon = 0,
initial.grid = 0, initial.identity = 1, initial.ciplot = 0, initial.values = 0,
initial.printthresrb = "no", initial.customthres = "c(0.5, 1, 10, 100)",
initial.xlab=gettextRcmdr("<auto>"), initial.ylab=gettextRcmdr("<auto>"),
initial.main=gettextRcmdr("<auto>"),
initial.pvalue = 1,
initial.legendroc=gettextRcmdr("<auto>"), initial.legendroc2=gettextRcmdr("<auto>"),
initial.colorroc=palette()[1], initial.colorroc2=palette()[3],
initial.ltyroc="solid", initial.ltyroc2="solid",
initial.customthres2 = "c(0.5, 1, 10, 100)",
initial.tab=0)
dialog.values <- getDialog("PairedpROC", defaults)
initializeDialog(title=gettext("Paired ROC curves comparison", domain="R-RcmdrPlugin.ROC"), use.tabs=TRUE, tabs=c("dataTab", "smoothingTab", "aucTab", "ciTab", "optionsTab"))
generalFrame <- tkframe(dataTab)
generaldataFrame <- ttklabelframe(generalFrame, text = gettext("Data", domain="R-RcmdrPlugin.ROC"))
predictionBox <- variableListBox(generaldataFrame, Numeric(), title=gettext("Predictions variable 1 (pick one)", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosn(dialog.values$initial.prediction, "numeric"))
prediction2Box <- variableListBox(generaldataFrame, Numeric(), title=gettext("Predictions variable 2 (pick one)", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosn(dialog.values$initial.prediction2, "numeric"))
labelBox <- variableListBox(generaldataFrame, Factors(), title=gettext("Outcome variable (pick one)", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosn(dialog.values$initial.label, "factor"))
checkBoxes(window = generalFrame,
frame = "dataoptionsFrame",
boxes = c("narm", "percent"),
initialValues = c(dialog.values$initial.narm, dialog.values$initial.percent),
labels = gettextRcmdr(c("Remove NAs", "Show/input % instead of 0-1")),
title = gettext("Options", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
radioButtons(dataoptionsFrame,
name="testmethodrb",
buttons=c("auto", "delong", "bootstrap", "venkatraman"),
values=c("auto", "delong", "bootstrap", "venkatraman"),
labels=gettextRcmdr(c("auto", "delong", "bootstrap", "venkatraman")),
title=gettext("Test method", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.testmethod)
radioButtons(dataoptionsFrame,
name="testalternativerb",
buttons=c("two.sided", "less", "greater"),
values=c("two.sided", "less", "greater"),
labels=gettextRcmdr(c("two sided", "less", "greater")),
title=gettext("Alternative", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.testalternative)
testbootnVar <- tclVar(dialog.values$initial.testbootn)
testbootnEntry <- ttkentry(dataoptionsFrame, width = "25", textvariable = testbootnVar)
radioButtons(dataoptionsFrame,
name="directionrb",
buttons=c("auto", "gt", "lt"),
values=c("auto", ">", "<"),
labels=gettextRcmdr(c("auto", "Control > cases", "Control <= cases")),
title=gettext("Direction", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.direction)
smoothingFrame <- tkframe(smoothingTab)
smoothingleftpaneFrame <- tkframe(smoothingFrame)
smoothinggeneralFrame <- ttklabelframe(smoothingleftpaneFrame, text = gettext("General variable 1", domain="R-RcmdrPlugin.ROC"))
smoothingdensityFrame <- ttklabelframe(smoothingleftpaneFrame, text = gettext("Density options", domain="R-RcmdrPlugin.ROC"))
smoothingdistributionFrame <- ttklabelframe(smoothingFrame, text = gettext("Distributions options", domain="R-RcmdrPlugin.ROC"))
smoothingleftpaneFrame2 <- tkframe(smoothingFrame)
smoothinggeneralFrame2 <- ttklabelframe(smoothingleftpaneFrame2, text = gettext("General variable 2", domain="R-RcmdrPlugin.ROC"))
smoothingdensityFrame2 <- ttklabelframe(smoothingleftpaneFrame2, text = gettext("Density options", domain="R-RcmdrPlugin.ROC"))
smoothingdistributionFrame2 <- ttklabelframe(smoothingFrame, text = gettext("Distributions options", domain="R-RcmdrPlugin.ROC"))
radioButtons(smoothinggeneralFrame,
name="smoothingmethodrb",
buttons=c("binormal", "density", "fitdistr", "logcondens", "logcondens.smooth"),
values=c("binormal", "density", "fitdistr", "logcondens", "logcondens.smooth"),
labels=gettextRcmdr(c("binormal", "density", "fit distribution", "logcondens", "logcondens.smooth")),
title=gettext("Smoothing method", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.smoothingmethod)
radioButtons(smoothingdensityFrame,
name="smoothinbandwidthrb",
buttons=c("nrd0", "nrd", "ucv", "bcv", "SJ", "numeric"),
values=c("nrd0", "nrd", "ucv", "bcv", "SJ", "numeric"),
labels=gettextRcmdr(c("nrd0", "nrd", "ucv", "bcv", "SJ", "<numeric>")),
title=gettext("Bandwidth", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.smoothinbandwidth)
bandwidthnumericVar <- tclVar(dialog.values$initial.bandwidthnumeric)
bandwidthnumericEntry <- ttkentry(smoothingdensityFrame, width = "25", textvariable = bandwidthnumericVar)
bandwidthnumericScroll <- ttkscrollbar(smoothingdensityFrame, orient = "horizontal",
command = function(...) tkxview(bandwidthnumericEntry, ...))
tkconfigure(bandwidthnumericEntry, xscrollcommand = function(...) tkset(bandwidthnumericScroll,
...))
tkbind(bandwidthnumericEntry, "<FocusIn>", function() tkselection.clear(bandwidthnumericEntry))
bandwidthadjustmentVar <- tclVar(dialog.values$initial.bandwidthadjustment)
bandwidthadjustmentEntry <- ttkentry(smoothingdensityFrame, width = "25", textvariable = bandwidthadjustmentVar)
radioButtons(smoothingdensityFrame,
name="bandwidthwindowrb",
buttons=c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine"),
values=c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine"),
labels=gettextRcmdr(c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine")),
title=gettext("Kernel", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.bandwidthwindow)
radioButtons(smoothingdistributionFrame,
name="distributioncontrolsrb",
buttons=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
values=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
labels=gettextRcmdr(c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy")),
title=gettext("Distribution of controls", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.distributioncontrols)
radioButtons(smoothingdistributionFrame,
name="distributioncasesrb",
buttons=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
values=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
labels=gettextRcmdr(c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy")),
title=gettext("Distribution of cases", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.distributioncases)
radioButtons(smoothinggeneralFrame2,
name="smoothingmethod2rb",
buttons=c("binormal", "density", "fitdistr", "logcondens", "logcondens.smooth"),
values=c("binormal", "density", "fitdistr", "logcondens", "logcondens.smooth"),
labels=gettextRcmdr(c("binormal", "density", "fit distribution", "logcondens", "logcondens.smooth")),
title=gettext("Smoothing method", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.smoothingmethod2)
radioButtons(smoothingdensityFrame2,
name="smoothinbandwidth2rb",
buttons=c("nrd0", "nrd", "ucv", "bcv", "SJ", "numeric"),
values=c("nrd0", "nrd", "ucv", "bcv", "SJ", "numeric"),
labels=gettextRcmdr(c("nrd0", "nrd", "ucv", "bcv", "SJ", "<numeric>")),
title=gettext("Bandwidth", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.smoothinbandwidth2)
bandwidthnumeric2Var <- tclVar(dialog.values$initial.bandwidthnumeric2)
bandwidthnumeric2Entry <- ttkentry(smoothingdensityFrame2, width = "25", textvariable = bandwidthnumeric2Var)
bandwidthnumeric2Scroll <- ttkscrollbar(smoothingdensityFrame2, orient = "horizontal",
command = function(...) tkxview(bandwidthnumeric2Entry, ...))
tkconfigure(bandwidthnumeric2Entry, xscrollcommand = function(...) tkset(bandwidthnumeric2Scroll,
...))
tkbind(bandwidthnumeric2Entry, "<FocusIn>", function() tkselection.clear(bandwidthnumeric2Entry))
bandwidthadjustment2Var <- tclVar(dialog.values$initial.bandwidthadjustment2)
bandwidthadjustment2Entry <- ttkentry(smoothingdensityFrame2, width = "25", textvariable = bandwidthadjustment2Var)
radioButtons(smoothingdensityFrame2,
name="bandwidthwindow2rb",
buttons=c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine"),
values=c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine"),
labels=gettextRcmdr(c("gaussian", "epanechnikov", "rectangular", "triangular", "biweight", "cosine", "optcosine")),
title=gettext("Kernel", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.bandwidthwindow2)
radioButtons(smoothingdistributionFrame2,
name="distributioncontrols2rb",
buttons=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
values=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
labels=gettextRcmdr(c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy")),
title=gettext("Distribution of controls", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.distributioncontrols2)
radioButtons(smoothingdistributionFrame2,
name="distributioncases2rb",
buttons=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
values=c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy"),
labels=gettextRcmdr(c("normal", "lognormal", "logistic", "exponential", "weibull", "gamma", "cauchy")),
title=gettext("Distribution of cases", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.distributioncases2)
ciFrame <- tkframe(ciTab)
checkBoxes(window = ciFrame, frame = "cibootstrapFrame",
boxes = c("cibootstratified"), initialValues = c(
dialog.values$initial.cibootstratified
),labels = gettextRcmdr(c(
"Stratified")), title = gettext("Bootstrap options", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
checkBoxes(window = ciFrame, frame = "cigeneralFrame",
boxes = c("cicompute"), initialValues = c(
dialog.values$initial.cicompute
),labels = gettextRcmdr(c(
"Compute Confidence Interval (CI)")), title = gettext("General", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
cilevelVar <- tclVar(dialog.values$initial.cilevel)
cilevelEntry <- ttkentry(cigeneralFrame, width = "25", textvariable = cilevelVar)
radioButtons(cigeneralFrame, name="cimethodrb", buttons=c("delong", "bootstrap", "auto"), values=c("delong", "bootstrap", "auto"),
labels=gettextRcmdr(c("delong", "bootstrap", "auto")), title=gettext("Method", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.cimethod)
radioButtons(cigeneralFrame, name="cityperb", buttons=c("auc", "se", "sp", "thresholds"), values=c("auc", "se", "sp", "thresholds"),
labels=gettextRcmdr(c("auc", "se", "sp", "thresholds")), title=gettext("Type of CI", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.citype)
radioButtons(cigeneralFrame, name="cithresholdsrb", buttons=c("all", "localmaximas", "custom"), values=c("all", "local maximas", "custom"),
labels=gettextRcmdr(c("all", "local maximas", "<custom>")), title=gettext("Thresholds", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.cithresholds)
civaluesVar <- tclVar(dialog.values$initial.civalues)
civaluesEntry <- ttkentry(cigeneralFrame, width = "25", textvariable = civaluesVar)
civaluesScroll <- ttkscrollbar(cigeneralFrame, orient = "horizontal",
command = function(...) tkxview(civaluesEntry, ...))
tkconfigure(civaluesEntry, xscrollcommand = function(...) tkset(civaluesScroll,
...))
tkbind(civaluesEntry, "<FocusIn>", function() tkselection.clear(civaluesEntry))
civalues2Var <- tclVar(dialog.values$initial.civalues2)
civalues2Entry <- ttkentry(cigeneralFrame, width = "25", textvariable = civalues2Var)
civalues2Scroll <- ttkscrollbar(cigeneralFrame, orient = "horizontal",
command = function(...) tkxview(civalues2Entry, ...))
tkconfigure(civalues2Entry, xscrollcommand = function(...) tkset(civalues2Scroll,
...))
tkbind(civalues2Entry, "<FocusIn>", function() tkselection.clear(civalues2Entry))
cibootnVar <- tclVar(dialog.values$initial.cibootn)
cibootnEntry <- ttkentry(cibootstrapFrame, width = "5", textvariable = cibootnVar)
tkgrid(labelRcmdr(cibootstrapFrame, text = gettext("Confidence level number of replicates", domain="R-RcmdrPlugin.ROC")), cibootnEntry, sticky = "ew", padx=6)
aucFrame <- tkframe(aucTab)
checkBoxes(window = aucFrame, frame = "generalaucFrame",
boxes = c("auc", "partialauc"), initialValues = c(
dialog.values$initial.auc, dialog.values$initial.partialauc
),labels = gettextRcmdr(c(
"Compute Area Under Curve (AUC)", "Compute partial AUC")), title = gettext("General", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
checkBoxes(window = aucFrame, frame = "partialaucFrame",
boxes = c("partialcorrect"), initialValues = c(
dialog.values$initial.partialcorrect),labels = gettextRcmdr(c(
"Correct partial AUC")), title = gettext("Partial AUC", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
partialfromVar <- tclVar(dialog.values$initial.partialfrom)
partialfromEntry <- ttkentry(partialaucFrame, width = "25", textvariable = partialfromVar)
tkgrid(labelRcmdr(partialaucFrame, text = gettext("From:", domain="R-RcmdrPlugin.ROC")), partialfromEntry, sticky = "ew", padx=6)
partialtoVar <- tclVar(dialog.values$initial.partialto)
partialtoEntry <- ttkentry(partialaucFrame, width = "25", textvariable = partialtoVar)
tkgrid(labelRcmdr(partialaucFrame, text = gettext("To:", domain="R-RcmdrPlugin.ROC")), partialtoEntry, sticky = "ew", padx=6)
radioButtons(partialaucFrame, name="partialfocus", buttons=c("specificity", "sensitivity"), values=c("specificity", "sensitivity"),
labels=gettextRcmdr(c("specificity", "sensitivity")), title=gettext("Focus", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.partialfocus)
optionsParFrame <- tkframe(optionsTab)
optFrame <- ttklabelframe(optionsParFrame, text = gettext("Plot Options", domain="R-RcmdrPlugin.ROC"))
parFrame <- ttklabelframe(optionsParFrame, text = gettext("Plot Labels", domain="R-RcmdrPlugin.ROC"))
legendFrame <- ttklabelframe(optionsParFrame, text = gettext("Legend options", domain="R-RcmdrPlugin.ROC"))
checkBoxes(window = optFrame, frame = "optionsFrame",
boxes = c("plot", "smooth", "grid","identity","ciplot","values"), initialValues = c(
dialog.values$initial.plot, dialog.values$initial.smooth,
dialog.values$initial.grid, dialog.values$initial.identity, dialog.values$initial.ciplot, dialog.values$initial.values),labels = gettextRcmdr(c(
"Plot", "Smooth","Display grid","Display identity line",
"Display confidence interval","Display values (Se, Sp, Thresholds)")), title = gettext("General", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
checkBoxes(window = optFrame, frame = "aucpolygonFrame",
boxes = c("aucpolygon", "maxaucpolygon"), initialValues = c(
dialog.values$initial.aucpolygon, dialog.values$initial.maxaucpolygon),labels = gettextRcmdr(c(
"Polygon of AUC", "Polygon of maximal AUC")), title = gettext("Display area as polygon", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
checkBoxes(window = optFrame, frame = "informationFrame",
boxes = c("printauc", "pvalue"), initialValues = c(
dialog.values$initial.printauc, dialog.values$initial.pvalue),labels = gettextRcmdr(c(
"AUC", "Test p-value")), title = gettext("Display information on plot", domain="R-RcmdrPlugin.ROC"), ttk=TRUE)
radioButtons(informationFrame, name="printthresrb", buttons=c("no", "best", "all", "localmaximas", "customthres"), values=c("no", "best", "all", "local maximas", "customthres"),
labels=gettextRcmdr(c("no", "best: max(sum(Se + Sp))", "all", "local maximas", "<custom>")), title=gettext("Display threshold(s)", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.printthresrb)
customthresVar <- tclVar(dialog.values$initial.customthres)
customthresEntry <- ttkentry(informationFrame, width = "25", textvariable = customthresVar)
customthresScroll <- ttkscrollbar(informationFrame, orient = "horizontal",
command = function(...) tkxview(customthresEntry, ...))
tkconfigure(customthresEntry, xscrollcommand = function(...) tkset(customthresScroll,
...))
tkbind(customthresEntry, "<FocusIn>", function() tkselection.clear(customthresEntry))
customthres2Var <- tclVar(dialog.values$initial.customthres2)
customthres2Entry <- ttkentry(informationFrame, width = "25", textvariable = customthres2Var)
customthres2Scroll <- ttkscrollbar(informationFrame, orient = "horizontal",
command = function(...) tkxview(customthres2Entry, ...))
tkconfigure(customthres2Entry, xscrollcommand = function(...) tkset(customthres2Scroll,
...))
tkbind(customthres2Entry, "<FocusIn>", function() tkselection.clear(customthres2Entry))
xlabVar <- tclVar(dialog.values$initial.xlab)
ylabVar <- tclVar(dialog.values$initial.ylab)
mainVar <- tclVar(dialog.values$initial.main)
xlabEntry <- ttkentry(parFrame, width = "25", textvariable = xlabVar)
xlabScroll <- ttkscrollbar(parFrame, orient = "horizontal",
command = function(...) tkxview(xlabEntry, ...))
tkconfigure(xlabEntry, xscrollcommand = function(...) tkset(xlabScroll,
...))
tkbind(xlabEntry, "<FocusIn>", function() tkselection.clear(xlabEntry))
tkgrid(labelRcmdr(parFrame, text = gettextRcmdr("x-axis label")), xlabEntry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(parFrame, text =""), xlabScroll, sticky = "ew", padx=6)
ylabEntry <- ttkentry(parFrame, width = "25", textvariable = ylabVar)
ylabScroll <- ttkscrollbar(parFrame, orient = "horizontal",
command = function(...) tkxview(ylabEntry, ...))
tkconfigure(ylabEntry, xscrollcommand = function(...) tkset(ylabScroll,
...))
tkgrid(labelRcmdr(parFrame, text = gettextRcmdr("y-axis label")), ylabEntry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(parFrame, text=""), ylabScroll, sticky = "ew", padx=6)
mainEntry <- ttkentry(parFrame, width = "25", textvariable = mainVar)
mainScroll <- ttkscrollbar(parFrame, orient = "horizontal",
command = function(...) tkxview(mainEntry, ...))
tkconfigure(mainEntry, xscrollcommand = function(...) tkset(mainScroll,
...))
tkgrid(labelRcmdr(parFrame, text = gettextRcmdr("Graph title")), mainEntry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(parFrame, text=""), mainScroll, sticky = "ew", padx=6)
radioButtons(parFrame, name="ciplottyperb", buttons=c("shape", "bars"), values=c("shape", "bars"),
labels=gettextRcmdr(c("shape", "bars")), title=gettext("CI plot type", domain="R-RcmdrPlugin.ROC"),
initialValue = dialog.values$initial.ciplottype)
legendrocVar <- tclVar(dialog.values$initial.legendroc)
legendrocEntry <- ttkentry(legendFrame, width = "25", textvariable = legendrocVar)
legendrocScroll <- ttkscrollbar(legendFrame, orient = "horizontal",
command = function(...) tkxview(legendrocEntry, ...))
tkconfigure(legendrocEntry, xscrollcommand = function(...) tkset(legendrocScroll,
...))
tkbind(legendrocEntry, "<FocusIn>", function() tkselection.clear(legendrocEntry))
legendroc2Var <- tclVar(dialog.values$initial.legendroc2)
legendroc2Entry <- ttkentry(legendFrame, width = "25", textvariable = legendroc2Var)
legendroc2Scroll <- ttkscrollbar(legendFrame, orient = "horizontal",
command = function(...) tkxview(legendroc2Entry, ...))
tkconfigure(legendroc2Entry, xscrollcommand = function(...) tkset(legendroc2Scroll,
...))
tkbind(legendroc2Entry, "<FocusIn>", function() tkselection.clear(legendroc2Entry))
colorrocBox <- variableListBox(legendFrame, palette(), title=gettext("Color of ROC 1 (from Palette)", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosListn(palette(), dialog.values$initial.colorroc))
colorroc2Box <- variableListBox(legendFrame, palette(), title=gettext("Color of ROC 2", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosListn(palette(), dialog.values$initial.colorroc2))
ltys <- c("solid", "dashed", "dotted", "dotdash", "longdash", "twodash", "blank")
ltyrocBox <- variableListBox(legendFrame, ltys, title=gettext("Line type of ROC 1 (from Palette)", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosListn(ltys, dialog.values$initial.ltyroc))
ltyroc2Box <- variableListBox(legendFrame, ltys, title=gettext("Line type of ROC 2", domain="R-RcmdrPlugin.ROC"),
initialSelection=varPosListn(ltys, dialog.values$initial.ltyroc2))
onOK <- function(){
tab <- if (as.character(tkselect(notebook)) == dataTab$ID) 0 else 1
prediction <- getSelection(predictionBox)
prediction2 <- getSelection(prediction2Box)
label <- getSelection(labelBox)
narm <- as.character("1" == tclvalue(narmVariable))
percent <- as.character("1" == tclvalue(percentVariable))
direction <- as.character(tclvalue(directionrbVariable))
testmethod <- as.character(tclvalue(testmethodrbVariable))
testalternative <- as.character(tclvalue(testalternativerbVariable))
testbootn <- as.character(tclvalue(testbootnVar))
smoothingmethod <- as.character(tclvalue(smoothingmethodrbVariable))
smoothinbandwidth <- as.character(tclvalue(smoothinbandwidthrbVariable))
bandwidthnumeric <- as.character(tclvalue(bandwidthnumericVar))
bandwidthadjustment <- as.character(tclvalue(bandwidthadjustmentVar))
bandwidthwindow <- as.character(tclvalue(bandwidthwindowrbVariable))
distributioncases <- as.character(tclvalue(distributioncasesrbVariable))
distributioncontrols <- as.character(tclvalue(distributioncontrolsrbVariable))
smoothingmethod2 <- as.character(tclvalue(smoothingmethod2rbVariable))
smoothinbandwidth2 <- as.character(tclvalue(smoothinbandwidth2rbVariable))
bandwidthnumeric2 <- as.character(tclvalue(bandwidthnumeric2Var))
bandwidthadjustment2 <- as.character(tclvalue(bandwidthadjustment2Var))
bandwidthwindow2 <- as.character(tclvalue(bandwidthwindow2rbVariable))
distributioncases2 <- as.character(tclvalue(distributioncases2rbVariable))
distributioncontrols2 <- as.character(tclvalue(distributioncontrols2rbVariable))
cicompute <- as.character("1" == tclvalue(cicomputeVariable))
cilevel <- as.numeric(as.character(tclvalue(cilevelVar)))
cimethod <- as.character(tclvalue(cimethodrbVariable))
citype <- as.character(tclvalue(cityperbVariable))
cithresholds <- as.character(tclvalue(cithresholdsrbVariable))
civalues <- as.character(tclvalue(civaluesVar))
cibootn <- as.integer(as.character(tclvalue(cibootnVar)))
cibootstratified <- as.character("1" == tclvalue(cibootstratifiedVariable))
civalues2 <- as.character(tclvalue(civalues2Var))
auc <- as.character("1" == tclvalue(aucVariable))
partialauc <- as.character("1" == tclvalue(partialaucVariable))
partialfrom <- as.character(tclvalue(partialfromVar))
partialto <- as.character(tclvalue(partialtoVar))
partialfocus <- as.character(tclvalue(partialfocusVariable))
partialcorrect <- as.character("1" == tclvalue(partialcorrectVariable))
plot <- as.character("1" == tclvalue(plotVariable))
smooth <- as.character("1" == tclvalue(smoothVariable))
printauc <- as.character("1" == tclvalue(printaucVariable))
aucpolygon <- as.character("1" == tclvalue(aucpolygonVariable))
maxaucpolygon <- as.character("1" == tclvalue(maxaucpolygonVariable))
grid <- as.character("1" == tclvalue(gridVariable))
identity <- as.character("1" == tclvalue(identityVariable))
ciplot <- as.character("1" == tclvalue(ciplotVariable))
values <- as.character("1" == tclvalue(valuesVariable))
printthresrb <- as.character(tclvalue(printthresrbVariable))
customthres <- as.character(tclvalue(customthresVar))
xlab <- trim.blanks(tclvalue(xlabVar))
xlab <- if (xlab == gettextRcmdr("<auto>"))
""
else paste(", xlab=\"", xlab, "\"", sep = "")
ylab <- trim.blanks(tclvalue(ylabVar))
ylab <- if (ylab == gettextRcmdr("<auto>"))
""
else paste(", ylab=\"", ylab, "\"", sep = "")
main <- trim.blanks(tclvalue(mainVar))
main <- if (main == gettextRcmdr("<auto>"))
""
else paste(", main=\"", main, "\"", sep = "")
ciplottype <- as.character(tclvalue(ciplottyperbVariable))
legendroc <- trim.blanks(tclvalue(legendrocVar))
legendroc <- if (legendroc == gettextRcmdr("<auto>"))
prediction
else legendroc
legendroc2 <- trim.blanks(tclvalue(legendroc2Var))
legendroc2 <- if (legendroc2 == gettextRcmdr("<auto>"))
prediction2
else legendroc2
colorroc <- getSelection(colorrocBox)
colorroc2 <- getSelection(colorroc2Box)
convert <- function (color){
f=col2rgb(color)
rgb(f[1],f[2],f[3],maxColorValue=255)
}
if(substr(colorroc,1,1) != "
if(substr(colorroc2,1,1) != "
ltyroc <- as.character(getSelection(ltyrocBox))
ltyroc2 <- as.character(getSelection(ltyroc2Box))
pvalue <- as.character("1" == tclvalue(pvalueVariable))
customthres2 <- as.character(tclvalue(customthres2Var))
putDialog ("PairedpROC", list(
initial.prediction = prediction, initial.prediction2 = prediction2, initial.label = label,
initial.narm = tclvalue(narmVariable), initial.percent = tclvalue(percentVariable),
initial.direction = as.character(tclvalue(directionrbVariable)),
initial.testmethod = as.character(tclvalue(testmethodrbVariable)), initial.testalternative = as.character(tclvalue(testalternativerbVariable)),
initial.testbootn = as.character(tclvalue(testbootnVar)),
initial.smooth = tclvalue(smoothVariable), initial.smoothingmethod = tclvalue(smoothingmethodrbVariable),
initial.smoothinbandwidth = tclvalue(smoothinbandwidthrbVariable), initial.bandwidthnumeric = tclvalue(bandwidthnumericVar),
initial.bandwidthadjustment = "1", initial.bandwidthwindow = tclvalue(bandwidthwindowrbVariable),
initial.distributioncontrols = tclvalue(distributioncontrolsrbVariable), initial.distributioncases = tclvalue(distributioncasesrbVariable),
initial.smoothingmethod2 = tclvalue(smoothingmethod2rbVariable),
initial.smoothinbandwidth2 = tclvalue(smoothinbandwidth2rbVariable), initial.bandwidthnumeric2 = tclvalue(bandwidthnumeric2Var),
initial.bandwidthadjustment2 = "1", initial.bandwidthwindow2 = tclvalue(bandwidthwindow2rbVariable),
initial.distributioncontrols2 = tclvalue(distributioncontrols2rbVariable), initial.distributioncases2 = tclvalue(distributioncases2rbVariable),
initial.cicompute = tclvalue(cicomputeVariable), initial.cilevel = tclvalue(cilevelVar), initial.cimethod = tclvalue(cimethodrbVariable),
initial.cibootn = tclvalue(cibootnVar), initial.cibootstratified = tclvalue(cibootstratifiedVariable),
initial.citype = tclvalue(cityperbVariable), initial.cithresholds = tclvalue(cithresholdsrbVariable),
initial.civalues = tclvalue(civaluesVar), initial.ciplottype = tclvalue(ciplottyperbVariable),
initial.civalues2 = tclvalue(civalues2Var),
initial.auc = tclvalue(aucVariable), initial.partialauc = tclvalue(partialaucVariable),
initial.partialfrom = tclvalue(partialfromVar), initial.partialto = tclvalue(partialtoVar),
initial.partialfocus = tclvalue(partialfocusVariable), initial.partialcorrect = tclvalue(partialcorrectVariable),
initial.plot = tclvalue(plotVariable),
initial.printauc = tclvalue(printaucVariable), initial.aucpolygon = tclvalue(aucpolygonVariable), initial.maxaucpolygon = tclvalue(maxaucpolygonVariable),
initial.grid = tclvalue(gridVariable), initial.identity = tclvalue(identityVariable),
initial.ciplot = tclvalue(ciplotVariable), initial.values = tclvalue(valuesVariable), initial.printthresrb = tclvalue(printthresrbVariable), initial.customthres = as.character(tclvalue(customthresVar)),
initial.xlab=tclvalue(xlabVar), initial.ylab=tclvalue(ylabVar),
initial.main=tclvalue(mainVar),
initial.legendroc = as.character(tclvalue(legendrocVar)), initial.legendroc2 = as.character(tclvalue(legendroc2Var)),
initial.colorroc = getSelection(colorrocBox), initial.colorroc2 = getSelection(colorroc2Box),
initial.ltyroc = getSelection(ltyrocBox), initial.ltyroc2 = getSelection(ltyroc2Box),
initial.pvalue = tclvalue(pvalueVariable),
initial.customthres2 = as.character(tclvalue(customthres2Var)),
initial.tab=tab))
closeDialog()
if (0 == length(prediction)) {
errorCondition(recall=fncPairedpROC, message=gettext("You must select a prediction variable 1.", domain="R-RcmdrPlugin.ROC"))
return()
}
if (0 == length(prediction2)) {
errorCondition(recall=fncPairedpROC, message=gettext("You must select a prediction variable 2.", domain="R-RcmdrPlugin.ROC"))
return()
}
if (0 == length(label)) {
errorCondition(recall=fncPairedpROC, message=gettext("No outcome variable selected.", domain="R-RcmdrPlugin.ROC"))
return()
}
if (percent == "TRUE") {
percentupper = 100
pvaluepos = "50"
} else {
percentupper = 1
pvaluepos = "0.5"
}
if (cicompute == "TRUE") {
if (0 == length(cilevel)) {
errorCondition(recall=fncPairedpROC, message=gettext("You must set a confidence interval level.", domain="R-RcmdrPlugin.ROC"))
return()
}
cilevel = as.numeric(cilevel)
if ((cilevel < 0) || (cilevel > 1)) {
errorCondition(recall=fncPairedpROC, message=gettext("Confidence interval level outside of range.", domain="R-RcmdrPlugin.ROC"))
return()
}
if (0 == length(cibootn)) {
errorCondition(recall=fncPairedpROC, message=gettext("You must set a confidence interval number of replicates.", domain="R-RcmdrPlugin.ROC"))
return()
}
if (cibootn < 0) {
errorCondition(recall=fncPairedpROC, message=gettext("Confidence interval number of replicates should be a pozitive number.", domain="R-RcmdrPlugin.ROC"))
return()
}
}
if (partialauc == "TRUE") {
if (0 == length(partialto)) {
errorCondition(recall=fncPairedpROC, message=gettext("You must set a partial AUC 'to' limit.", domain="R-RcmdrPlugin.ROC"))
return()
}
partialto = as.numeric(partialto)
partialfrom = as.numeric(partialfrom)
if ((partialto < 0) | (partialto > percentupper)) {
errorCondition(recall=fncPairedpROC, message=gettext("Partial AUC 'to' limit outside of range.", domain="R-RcmdrPlugin.ROC"))
return()
}
if (0 == length(partialfrom)) {
errorCondition(recall=fncPairedpROC, message=gettext("You must set a partial AUC 'from' limit.", domain="R-RcmdrPlugin.ROC"))
return()
}
if ((partialfrom < 0) | (partialfrom > percentupper)) {
errorCondition(recall=fncPairedpROC, message=gettext("Partial AUC 'from' limit outside of range.", domain="R-RcmdrPlugin.ROC"))
return()
}
if ((max(c(partialfrom, partialto)) <= 1) & (percent=="TRUE")) {
Message(message="Maybe you didn't specified well the values, you probably wanted to set the values between 0-100 instead of between 0-1, since percent is checked", type="warning")
}
if ((max(c(partialfrom, partialto)) > 1) & (percent=="FALSE")) {
Message(message="Maybe you didn't specified well the values, you probably wanted to set the values between 0-1 instead of between 0-100, since percent is not checked", type="warning")
}
}
if ((printthresrb == "custom") & (0 == length(customthres))) {
errorCondition(recall=fncPairedpROC, message=gettext("Custom threshold for variable 1 should not be empty.", domain="R-RcmdrPlugin.ROC"))
return()
}
if ((printthresrb == "custom") & (0 == length(customthres2))) {
errorCondition(recall=fncPairedpROC, message=gettext("Custom threshold for variable 2 should not be empty.", domain="R-RcmdrPlugin.ROC"))
return()
}
.activeDataSet <- ActiveDataSet()
if (printthresrb == "customthres") {
threshold = customthres
threshold2 = customthres2
} else {
threshold = paste("'", printthresrb, "'", sep="")
threshold2 = paste("'", printthresrb, "'", sep="")
}
if (partialauc == "TRUE") {
partialauc = paste("c(", partialfrom, ", ", partialto, ")", sep="")
}
command <- paste("roc.obj <- pROC::roc(", label, " ~ ", prediction, ", data=", .activeDataSet, ", na.rm=", narm, ", percent=", percent, ", direction='", direction, "'",
", partial.auc=", partialauc, ", partial.auc.focus='", partialfocus, "'", ", partial.auc.correct=", partialcorrect,
", auc=", auc, ", plot=FALSE, ci=TRUE, of='auc', conf.level=", cilevel, ", ci.method='", cimethod,"', boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
if (plot == "TRUE") {
command <- paste("plot(roc.obj, add=FALSE",
", print.auc=", printauc, ", auc.polygon=", aucpolygon, ", max.auc.polygon=", maxaucpolygon,
", print.auc.x=ifelse(roc.obj$percent, 50, .5), print.auc.y=ifelse(roc.obj$percent, 45, .45), print.auc.pattern='AUC: %.2f (%.2f, %.2f)'",
", auc.polygon.col='", colorroc, "AA'", ", max.auc.polygon.col='", colorroc, "22'",
", grid=", grid, ", identity=", identity, ", col='", colorroc, "', lty='", ltyroc, "'",
", print.thres=", threshold, ", print.thres.adj=c(0,0.5), print.thres.cex=0.7, print.thres.pattern='%.2f (%.2f, %.2f)'",
xlab, ylab, main, ")", sep = "")
doItAndPrint(command)
}
command <- paste("roc.obj$levels[1]
doItAndPrint(command)
command <- paste("roc.obj$levels[2]
doItAndPrint(command)
command <- paste("roc.obj2 <- pROC::roc(", label, " ~ ", prediction2, ", data=", .activeDataSet, ", na.rm=", narm, ", percent=", percent, ", direction='", direction, "'",
", partial.auc=", partialauc, ", partial.auc.focus='", partialfocus, "'", ", partial.auc.correct=", partialcorrect,
", auc=", auc, ", plot=FALSE, ci=TRUE, of='auc', conf.level=", cilevel, ", ci.method='", cimethod,"', boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
if (plot == "TRUE") {
command <- paste("plot(roc.obj2, add=TRUE",
", print.auc=", printauc, ", auc.polygon=", aucpolygon, ", max.auc.polygon=", maxaucpolygon,
", print.auc.x=ifelse(roc.obj$percent, 50, .5), print.auc.y=ifelse(roc.obj2$percent, 40, .40), print.auc.pattern='AUC: %.2f (%.2f, %.2f)'",
", auc.polygon.col='", colorroc2, "AA'", ", max.auc.polygon.col='", colorroc2, "22'",
", grid=", grid, ", identity=", identity, ", col='", colorroc2, "', lty='", ltyroc2, "'",
", print.thres=", threshold2, ", print.thres.adj=c(1,0.5), print.thres.cex=0.7, print.thres.pattern='%.2f (%.2f, %.2f)'",
xlab, ylab, main, ")", sep = "")
doItAndPrint(command)
}
if (testmethod == "auto") {
testmethod = ""
} else {
testmethod = paste(", method='", testmethod, "'", sep="")
}
command <- paste("roc.test.obj <- roc.test(roc.obj, roc.obj2, paired=TRUE", testmethod,", alternative='", testalternative, "', boot.n=", testbootn,")", sep = "")
doItAndPrint(command)
if (pvalue == "TRUE") {
command <- paste("text(", pvaluepos, ", ", pvaluepos, ", labels=paste('p-value = ', format.pval(roc.test.obj$p.value), sep=''), adj=c(0, .5))", sep = "")
doItAndPrint(command)
}
command <- paste("roc.test.obj", sep = "")
doItAndPrint(command)
command <- paste("legend('bottomright', legend=c('", legendroc, "', '", legendroc2, "'), col=c('", colorroc, "', '", colorroc2, "'), lwd=2, lty=c('", ltyroc, "', '", ltyroc2, "'))", sep = "")
doItAndPrint(command)
if (cicompute == "TRUE") {
cilevel = paste(", conf.level=", cilevel, sep="")
cimethod = paste(", method='", cimethod, "'", sep="")
}
if (ciplot == "TRUE") {
if (citype == "thresholds") {
if (cithresholds == "custom") {
threshold = civalues
threshold2 = civalues2
} else {
threshold = paste("'", cithresholds, "'", sep="")
threshold2 = paste("'", cithresholds, "'", sep="")
}
command <- paste("roc.ci.obj <- ci(roc.obj, of='thresholds', thresholds=", threshold, cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
command <- paste("plot(roc.ci.obj, type='", ciplottype, "', col='", colorroc, "AA')", sep = "")
doItAndPrint(command)
command <- paste("roc.ci.obj2 <- ci(roc.obj2, of='thresholds', thresholds=", threshold2, cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
command <- paste("plot(roc.ci.obj2, type='", ciplottype, "', col='", colorroc, "AA')", sep = "")
doItAndPrint(command)
} else {
if ((citype == "se") & (citype == "sp")) {
if ((max(eval(parse(text=as.character(civalues)))) <= 1) & (percent=="TRUE")) {
Message(message="Maybe you didn't specified well the values, you probably wanted to set seq(0,100,5) (or values between 0-100%) instead of seq(0,1,0.05), since percent is checked", type="warning")
}
if ((max(eval(parse(text=as.character(civalues)))) > 1) & (percent=="FALSE")) {
Message(message="Maybe you didn't specified well the values, you probably wanted to set seq(0,1,0.05) (or values between 0-1) instead of seq(0,100,5), since percent is not checked", type="warning")
}
if ((max(eval(parse(text=as.character(civalues2)))) <= 1) & (percent=="TRUE")) {
Message(message="Maybe you didn't specified well the values, you probably wanted to set seq(0,100,5) (or values between 0-100%) instead of seq(0,1,0.05), since percent is checked", type="warning")
}
if ((max(eval(parse(text=as.character(civalues2)))) > 1) & (percent=="FALSE")) {
Message(message="Maybe you didn't specified well the values, you probably wanted to set seq(0,1,0.05) (or values between 0-1) instead of seq(0,100,5), since percent is not checked", type="warning")
}
}
if (citype == "se") {
command <- paste("roc.ci.obj <- ci(roc.obj, of='se', specificities=", civalues, cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
command <- paste("roc.ci.obj2 <- ci(roc.obj2, of='se', specificities=", civalues2, cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
}
if (citype == "sp") {
command <- paste("roc.ci.obj <- ci(roc.obj, of='sp', sensitivities=", civalues, cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
command <- paste("roc.ci.obj2 <- ci(roc.obj2, of='sp', sensitivities=", civalues2, cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
}
if (citype == "auc") {
command <- paste("roc.ci.obj <- ci(roc.obj, of='auc'", cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
doItAndPrint("roc.ci.obj")
command <- paste("roc.ci.obj2 <- ci(roc.obj2, of='auc'", cilevel, cimethod,", boot.n=", cibootn, ", boot.stratified=", cibootstratified,")", sep = "")
doItAndPrint(command)
doItAndPrint("roc.ci.obj2")
}
command <- paste("plot(roc.ci.obj, type='", ciplottype, "', col='", colorroc, "AA')", sep = "")
doItAndPrint(command)
command <- paste("plot(roc.ci.obj2, type='", ciplottype, "', col='", colorroc2, "AA')", sep = "")
doItAndPrint(command)
}
}
if (smooth == "TRUE") {
bandwidth = ""
density = ""
if (smoothingmethod == "density") {
if (smoothinbandwidth == "numeric") {
bandwidth = paste(", bw=", bandwidthnumeric, "", sep="")
} else {
bandwidth = paste(", bw='", smoothinbandwidth, "'", sep="")
}
}
if (smoothingmethod == "fitdistr") {
density = paste(", density.cases='", distributioncases, "', density.controls='", distributioncontrols, "'", sep="")
}
command <- paste("lines(smooth(roc.obj, method = '", smoothingmethod, "'", bandwidth, density, "), col='", colorroc, "', lty='dotdash')", sep = "")
doItAndPrint(command)
bandwidth2 = ""
density2 = ""
if (smoothingmethod2 == "density") {
if (smoothinbandwidth2 == "numeric") {
bandwidth2 = paste(", bw=", bandwidthnumeric2, "", sep="")
} else {
bandwidth2 = paste(", bw='", smoothinbandwidth2, "'", sep="")
}
}
if (smoothingmethod2 == "fitdistr") {
density2 = paste(", density.cases='", distributioncases2, "', density.controls='", distributioncontrols2, "'", sep="")
}
command <- paste("lines(smooth(roc.obj2, method = '", smoothingmethod2, "'", bandwidth2, density2, "), col='", colorroc2, "', lty='dotdash')", sep = "")
doItAndPrint(command)
}
if (values == "TRUE") {
doItAndPrint("roc.obj$sensitivities")
doItAndPrint("roc.obj$specificities")
doItAndPrint("roc.obj$thresholds")
doItAndPrint("roc.obj2$sensitivities")
doItAndPrint("roc.obj2$specificities")
doItAndPrint("roc.obj2$thresholds")
}
command <- paste("remove(roc.obj)", sep = "")
doItAndPrint(command)
command <- paste("remove(roc.obj2)", sep = "")
doItAndPrint(command)
if (ciplot == "TRUE") {
command <- paste("remove(roc.ci.obj)", sep = "")
doItAndPrint(command)
command <- paste("remove(roc.ci.obj2)", sep = "")
doItAndPrint(command)
}
activateMenus()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="plot.roc", reset = "fncPairedpROC", apply="fncPairedpROC")
tkgrid(getFrame(predictionBox), getFrame(prediction2Box), getFrame(labelBox), sticky = "nw", padx=6, pady=c(6, 6))
tkgrid(testmethodrbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(testalternativerbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(labelRcmdr(dataoptionsFrame, text = gettext("Number of replicates", domain="R-RcmdrPlugin.ROC")), testbootnEntry, sticky = "ew", padx=6)
tkgrid(directionrbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(generaldataFrame , dataoptionsFrame, sticky = "nswe", padx=6, pady=6)
tkgrid(generalFrame, sticky = "we")
tkgrid(smoothingmethodrbFrame, sticky = "w", padx=6, pady=c(6, 6))
tkgrid(smoothinbandwidthrbFrame, sticky = "w", padx=6, pady=c(6, 0))
tkgrid(labelRcmdr(smoothingdensityFrame, text = gettext("Numeric bandwidth", domain="R-RcmdrPlugin.ROC")), bandwidthnumericEntry, sticky = "ew", padx=6, pady=c(6, 0))
tkgrid(labelRcmdr(smoothingdensityFrame, text =""), bandwidthnumericScroll, sticky = "ew", padx=6)
tkgrid(labelRcmdr(smoothingdensityFrame, text = gettext("Adjustment", domain="R-RcmdrPlugin.ROC")), bandwidthadjustmentEntry, sticky = "ew", padx=6, pady=c(6, 0))
tkgrid(distributioncontrolsrbFrame, sticky = "w", padx=6, pady=c(6, 0))
tkgrid(distributioncasesrbFrame, sticky = "w", padx=6, pady=c(6, 6))
tkgrid(smoothinggeneralFrame, sticky = "w")
tkgrid(smoothingdensityFrame, sticky = "w")
tkgrid(smoothingmethod2rbFrame, sticky = "w", padx=6, pady=c(6, 6))
tkgrid(smoothinbandwidth2rbFrame, sticky = "w", padx=6, pady=c(6, 0))
tkgrid(labelRcmdr(smoothingdensityFrame2, text = gettext("Numeric bandwidth", domain="R-RcmdrPlugin.ROC")), bandwidthnumeric2Entry, sticky = "ew", padx=6, pady=c(6, 0))
tkgrid(labelRcmdr(smoothingdensityFrame2, text =""), bandwidthnumeric2Scroll, sticky = "ew", padx=6)
tkgrid(labelRcmdr(smoothingdensityFrame2, text = gettext("Adjustment", domain="R-RcmdrPlugin.ROC")), bandwidthadjustment2Entry, sticky = "ew", padx=6, pady=c(6, 0))
tkgrid(distributioncontrols2rbFrame, sticky = "w", padx=6, pady=c(6, 0))
tkgrid(distributioncases2rbFrame, sticky = "w", padx=6, pady=c(6, 6))
tkgrid(smoothinggeneralFrame2, sticky = "w")
tkgrid(smoothingdensityFrame2, sticky = "w")
tkgrid(smoothingleftpaneFrame , smoothingdistributionFrame, smoothingleftpaneFrame2 , smoothingdistributionFrame2, sticky = "nswe", padx=6, pady=6)
tkgrid(smoothingFrame, sticky = "we")
tkgrid(labelRcmdr(cigeneralFrame, text = gettext("Confidence level", domain="R-RcmdrPlugin.ROC")), cilevelEntry, sticky = "ew", padx=6)
tkgrid(cimethodrbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(cityperbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(cithresholdsrbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(labelRcmdr(cigeneralFrame, text = gettext("Values (Se/Sp/Custom thres.) for variable 1", domain="R-RcmdrPlugin.ROC")), civaluesEntry, sticky = "ew", padx=6, pady=c(0, 6))
tkgrid(labelRcmdr(cigeneralFrame, text =""), civaluesScroll, sticky = "ew", padx=6, pady=c(0, 6))
tkgrid(labelRcmdr(cigeneralFrame, text = gettext("Values (Se/Sp/Custom thres.) for variable 2", domain="R-RcmdrPlugin.ROC")), civalues2Entry, sticky = "ew", padx=6, pady=c(0, 6))
tkgrid(labelRcmdr(cigeneralFrame, text =""), civalues2Scroll, sticky = "ew", padx=6, pady=c(0, 6))
tkgrid(cigeneralFrame , cibootstrapFrame, sticky = "nswe", padx=6, pady=6)
tkgrid(ciFrame, sticky = "we")
tkgrid(partialfocusFrame, sticky = "w", padx=6, pady=c(6, 6))
tkgrid(generalaucFrame , partialaucFrame, sticky = "nswe", padx=6, pady=6)
tkgrid(aucFrame, sticky = "we")
tkgrid(labelRcmdr(legendFrame, text = gettext("Legend of ROC 1", domain="R-RcmdrPlugin.ROC")), legendrocEntry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(legendFrame, text =""), legendrocScroll, sticky = "ew", padx=6)
tkgrid(getFrame(colorrocBox), sticky = "w", padx=6, pady=c(6, 0))
tkgrid(getFrame(ltyrocBox), sticky = "w", padx=6, pady=c(6, 18))
tkgrid(labelRcmdr(legendFrame, text = gettext("Legend of ROC 2", domain="R-RcmdrPlugin.ROC")), legendroc2Entry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(legendFrame, text =""), legendroc2Scroll, sticky = "ew", padx=6)
tkgrid(getFrame(colorroc2Box), sticky = "w", padx=6, pady=c(6, 0))
tkgrid(getFrame(ltyroc2Box), sticky = "w", padx=6, pady=c(6, 6))
tkgrid(optionsFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(aucpolygonFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(printthresrbFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(labelRcmdr(informationFrame, text = gettext("Custom threshold for variable 1", domain="R-RcmdrPlugin.ROC")), customthresEntry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(informationFrame, text =""), customthresScroll, sticky = "ew", padx=6)
tkgrid(labelRcmdr(informationFrame, text = gettext("Custom threshold for variable 2", domain="R-RcmdrPlugin.ROC")), customthres2Entry, sticky = "ew", padx=6)
tkgrid(labelRcmdr(informationFrame, text =""), customthres2Scroll, sticky = "ew", padx=6)
tkgrid(informationFrame, sticky = "w", padx=6, pady=c(0, 6))
tkgrid(ciplottyperbFrame, sticky = "w", padx=6, pady=c(6, 6))
tkgrid(optFrame, parFrame, legendFrame, sticky = "nswe", padx=6, pady=6)
tkgrid(optionsParFrame, sticky = "we")
tkgrid(ttklabel(dataTab, text=""))
tkgrid(ttklabel(dataTab, text=""))
tkgrid(labelRcmdr(top, text = " "), padx=6)
dialogSuffix(use.tabs=TRUE, grid.buttons=TRUE, tabs=c("dataTab", "smoothingTab", "aucTab", "ciTab", "optionsTab"),
tab.names=c("General", "Smoothing", "AUC", "CI", "Plot"))
} |
source("test.prolog.R")
library(earth)
options(warn=1)
sex <- factor(c("m","f","f","f","f"))
pclass <- factor(c("1st", "2nd", "3rd", "3rd", "3rd"))
x.short <- data.frame(dose=1L:5L,
numericx=c(1.1,1.2,1.3,1.4,1.5),
logicalx=c(TRUE,FALSE,TRUE,FALSE,TRUE),
sex=sex,
pclass=pclass)
y.short <- data.frame(success=c(1,2,3,0,1),
fail =c(1,1,1,0,0))
short <- data.frame(x.short, y.short)
x.short.unsorted <- x.short[nrow(x.short):1, ]
y.short.unsorted <- y.short[nrow(y.short):1, ]
short.unsorted <- data.frame(x.short.unsorted, y.short.unsorted)
long <- data.frame(
success =c( F, T, F, T, T, F, T, T, T, F, T),
dose =c( 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 5L),
numericx=c( 1.1, 1.1, 1.2, 1.2, 1.2, 1.3, 1.3, 1.3, 1.3, 1.4, 1.5),
logicalx=c( T, T, F, F, F, T, T, T, T, F, T),
sex =factor(c( "m", "m", "f", "f", "f", "f", "f", "f", "f", "f", "f")),
pclass =factor(c("1st","1st","2nd","2nd","2nd","3rd","3rd","3rd","3rd","3rd","3rd")))
bpairs.index <- c(1L, 3L, 6L, 10L, 11L)
ynames <- c("success", "fail")
check.expanded.bpairs <- function(long.expanded, long.ref, bpairs.index.ref, ynames.ref)
{
stopifnot(rownames(long.expanded)[1] == "row1.1")
stripped.long.expanded <- long.expanded
rownames(stripped.long.expanded) <- 1:nrow(long.expanded)
attr(stripped.long.expanded, "bpairs.index") <- NULL
attr(stripped.long.expanded, "ynames") <- NULL
if(!identical(stripped.long.expanded, long.ref)) {
printf("\n---print.default(stripped.long.expanded)------\n")
print.default(stripped.long.expanded)
printf("\n---print.default(long.ref)--------------------\n")
print.default(long.ref)
printf("\n----------------------------------------------\n")
stop("!identical(stripped.long.expanded, long.ref), see above prints")
}
stopifnot(identical(attr(long.expanded, "bpairs.index"), bpairs.index.ref))
stopifnot(identical(attr(long.expanded, "ynames"), ynames.ref))
}
cat("expand.bpairs(x.short, y.short)\n")
long.default <- expand.bpairs(x.short, y.short)
check.expanded.bpairs(long.default, long, bpairs.index, ynames)
long.default.sort <- expand.bpairs(x.short.unsorted, y.short.unsorted, sort=TRUE)
attr(long.default.sort, "row.names") <- NULL
attr(long.default.sort, "ynames") <- NULL
long1 <- long
rownames(long1) <- NULL
attr(long1, "row.names") <- NULL
attr(long1, "bpairs.index") <- NULL
stopifnot(all.equal(long.default.sort, long1))
cat("expand.bpairs(expand.bpairs(short$dose, y.short)\n")
long.default.dose <- expand.bpairs(short$dose, y.short)
colnames(long.default.dose)[2] <- "dose"
check.expanded.bpairs(long.default.dose, long[,c("success", "dose")], bpairs.index, ynames)
cat("expand.bpairs(short.data.frame, c(6,7))\n")
short.data.frame <- data.frame(x.short, y.short)
long.colindex <- expand.bpairs(short.data.frame, c(6,7))
check.expanded.bpairs(long.colindex, long, bpairs.index, ynames)
cat("expand.bpairs(short.data.frame.dose, c(2,3))\n")
short.data.frame.dose <- data.frame(dose=x.short$dose, y.short)
long.default.dose <- expand.bpairs(short.data.frame.dose, c(2,3))
check.expanded.bpairs(long.default.dose, long[,c("success", "dose")], bpairs.index, ynames)
cat("expand.bpairs(short.data.frame, c(\"success\",\"fail\"))\n")
short.data.frame <- data.frame(x.short, y.short)
long.charindex <- expand.bpairs(short.data.frame, c("success", "fail"))
check.expanded.bpairs(long.charindex, long, bpairs.index, ynames)
cat("expand.bpairs(short.data.frame.dose, c(2,3))\n")
short.data.frame.dose <- data.frame(dose=x.short$dose, y.short)
long.default.charindex.dose <- expand.bpairs(short.data.frame.dose, c(2,3))
check.expanded.bpairs(long.default.charindex.dose, long[,c("success", "dose")], bpairs.index, ynames)
expect.err(try(expand.bpairs()), "expand.bpairs: no y argument")
expect.err(try(expand.bpairs(short.data.frame.dose)), "expand.bpairs: no y argument")
expect.err(try(expand.bpairs(short.data.frame.dose, c(2,3), nonesuch=99)), "expand.bpairs.default: unrecognized argument 'nonesuch'")
expect.err(try(expand.bpairs(short.data.frame, c(5,6))), "short.data.frame[,c(5,6)] is not a two-column matrix of binomial pairs")
expect.err(try(expand.bpairs(short.data.frame, 1)), "expand.bpairs: bad y argument '1'")
expect.err(try(expand.bpairs(short.data.frame, c(1,2,3))), "bad y argument 'c(1, 2, 3)'")
expect.err(try(expand.bpairs(short.data.frame, c(1,2))), "expand.bpairs: short.data.frame[,c(1,2)] is not a two-column matrix of binomial pairs")
expect.err(try(expand.bpairs(short.data.frame, c(99,100))), "'ycolumns' is out of range, allowed values are 1 to 7")
expect.err(try(expand.bpairs(short.data.frame, c("success99", "fail"))), "undefined columns selected")
expect.err(try(expand.bpairs(short.data.frame, c("nonesuch", "fail"))), "undefined columns selected")
expect.err(try(expand.bpairs(short.data.frame, "nonesuch")), "bad y argument 'nonesuch'")
expect.err(try(expand.bpairs(short.data.frame, nonesuch)), "object 'nonesuch' not found")
options(warn=2)
expect.err(try(expand.bpairs(short.data.frame, c("nonesuch", "fail"))), "\"nonesuch\" in ycolumns does not match any names")
expect.err(try(expand.bpairs(short.data.frame, c("fail", "nonesuch99"))), "\"nonesuch99\" in ycolumns does not match any names")
expect.err(try(expand.bpairs(short.data.frame, c("", "fail"))), "ycolumns[1] is an empty string \"\"")
expect.err(try(expand.bpairs(short.data.frame, c("success", ""))), "ycolumns[2] is an empty string \"\"")
options(warn=1)
try(expand.bpairs(short.data.frame, c("success", "")))
cat("expand.bpairs(success.fail~., data=x.short)\n")
success.fail <- cbind(success=short$success, fail=short$fail)
long.formula.matrix <- expand.bpairs(success.fail~., data=x.short)
check.expanded.bpairs(long.formula.matrix, long, bpairs.index, ynames)
cat("expand.bpairs(success+fail~., data=x.short)\n")
xy.short <- data.frame(y.short, x.short)
long.formula <- expand.bpairs(success+fail~., data=xy.short)
check.expanded.bpairs(long.formula, long, bpairs.index, ynames)
long.formula.sort <- expand.bpairs(x.short, y.short, sort=TRUE)
long.formula.sort <- expand.bpairs(x.short.unsorted, y.short.unsorted, sort=TRUE)
attr(long.formula.sort, "row.names") <- NULL
attr(long.formula.sort, "ynames") <- NULL
long1 <- long
rownames(long1) <- NULL
attr(long1, "row.names") <- NULL
attr(long1, "bpairs.index") <- NULL
stopifnot(all.equal(long.formula.sort, long1))
expand.bpairs(success+fail+fail~., data=xy.short)
expect.err(try(expand.bpairs(success~., data=xy.short)), "expand.bpairs: 'success' does not have two columns")
expect.err(try(expand.bpairs(success+success~., data=xy.short)), "expand.bpairs: 'success + success' does not have two columns")
cat("expand.bpairs(success.fail~., data=x.short)\n")
success.fail <- cbind(success=short$success, fail=short$fail)
long.formula.matrix <- expand.bpairs(success.fail~., data=x.short)
check.expanded.bpairs(long.formula.matrix, long, bpairs.index, ynames)
cat("expand.bpairs(data.frame(success.fail)~., data=x.short)\n")
expect.err(try(expand.bpairs(data.frame(success.fail)~., data=x.short)), "invalid type (list) for variable 'data.frame(success.fail)'")
cat("expand.bpairs(expand.bpairs(success+fail~dose, data=xy.short)\n")
long.formula.dose <- expand.bpairs(success+fail~dose, data=xy.short)
check.expanded.bpairs(long.formula.dose, long[,c("success", "dose")], bpairs.index, ynames)
trues <- xy.short$success
falses <- xy.short$fail
cat("expand.bpairs(expand.bpairs(trues+falses~dose, data=x.short)\n")
long.formula.dose <- expand.bpairs(trues+falses~~dose, data=xy.short)
stopifnot(identical(colnames(long.formula.dose), c("trues", "dose")))
colnames(long.formula.dose) <- c("success", "dose")
attr(long.formula.dose, "ynames") <- c("success", "fail")
check.expanded.bpairs(long.formula.dose, long[,c("success", "dose")], bpairs.index, ynames)
cat("expand.bpairs(expand.bpairs(trues+falses~., data=x.short)\n")
long.formula <- expand.bpairs(trues+falses~., data=xy.short)
stopifnot(identical(colnames(long.formula), c("trues", "success", "fail", "dose", "numericx", "logicalx", "sex", "pclass")))
cat("expand.bpairs(expand.bpairs(success.fail~dose, data=x.short)\n")
long.formula.dose <- expand.bpairs(success.fail~dose, data=x.short)
check.expanded.bpairs(long.formula.dose, long[,c("success", "dose")], bpairs.index, ynames)
cat("expand.bpairs(expand.bpairs(success.fail~dose, data=xy.short)\n")
long.formula.dose <- expand.bpairs(success.fail~dose, data=xy.short)
check.expanded.bpairs(long.formula.dose, long[,c("success", "dose")], bpairs.index, ynames)
x.short.na <- x.short
x.short.na$dose[3] <- NA
long.na <- long
long.na$dose[6:9] <- NA
cat("expand.bpairs(success.fail~., data=x.short.na)\n")
long.formula.na <- expand.bpairs(success.fail~., data=x.short.na)
check.expanded.bpairs(long.formula.na, long.na, bpairs.index, ynames)
cat("expand.bpairs(success.fail~dose., data=x.short.na)\n")
long.formula.dose.na <- expand.bpairs(success.fail~dose, data=x.short.na)
check.expanded.bpairs(long.formula.dose.na, long.na[,c("success", "dose")], bpairs.index, ynames)
expect.err(try(expand.bpairs(nonesuch~., data=x.short)), "object 'nonesuch' not found")
expect.err(try(expand.bpairs(dose~., data=x.short)), "'dose' does not have two columns")
expect.err(try(expand.bpairs(dose~success.fail, data=x.short)), "'dose' does not have two columns")
long.formula <- expand.bpairs(success.fail~., data=xy.short)
check.expanded.bpairs(long.formula, long, bpairs.index, ynames)
long.formula.dose <- expand.bpairs(success.fail~dose, data=xy.short)
check.expanded.bpairs(long.formula.dose, long[,c("success", "dose")], bpairs.index, ynames)
old.success.fail <- success.fail
success.fail <- 99
expect.err(try(expand.bpairs(success.fail~., data=xy.short)), "variable lengths differ (found for 'success')")
success.fail <- old.success.fail
short <- matrix(c( 5, 2, 2, 9, 5, 9,
20,20,30,20,20,30), ncol=2)
colnames(short) <- c("dose", "temp")
success.fail <- matrix(c(1,2,0,2,2,0,
3,3,1,0,1,0), ncol=2)
long <- matrix(c(
0, 5, 20,
0, 5, 20,
0, 5, 20,
1, 5, 20,
0, 2, 20,
0, 2, 20,
0, 2, 20,
1, 2, 20,
1, 2, 20,
0, 2, 30,
1, 9, 20,
1, 9, 20,
0, 5, 20,
1, 5, 20,
1, 5, 20,
0, 9, 30),
ncol=3, byrow=TRUE)
colnames(long) <- c("V1", "dose", "temp")
long <- as.data.frame(long)
bpairs.index <- c(1L, 5L, 10L, 11L, 13L, 16L)
ynames <- c("V1", "V2")
long.default <- expand.bpairs(short, success.fail)
long.default$V1 <- as.numeric(long.default$V1)
check.expanded.bpairs(long.default, long, bpairs.index, ynames)
example(expand.bpairs)
survived <- c(3,2,1,1)
died <- c(0,1,2,2)
dose <- c(10,10,20,20)
sex <- factor(c("male", "female", "male", "female"))
short.data <- data.frame(survived, died, dose, sex)
long.data <- expand.bpairs(survived + died ~ ., short.data)
print(long.data)
stopifnot(identical(expand.bpairs(data=short.data, y=cbind(survived, died)), long.data))
stopifnot(identical(expand.bpairs(short.data, c(1,2)), long.data))
stopifnot(identical(expand.bpairs(short.data, c("survived", "died")), long.data))
pairs(short.data, main="short.data")
pairs(long.data, main="long.data")
short.unsorted.nocolnames <- short.unsorted
colnames(short.unsorted.nocolnames) <- NULL
temp <- expand.bpairs(short.unsorted, 6:7)
temp.nocolnames <- expand.bpairs(short.unsorted.nocolnames, 6:7)
stopifnot(all.equal(colnames(temp.nocolnames), c("true", "X1", "X2", "X3", "X4", "X5")))
colnames(temp.nocolnames) <- colnames(temp)
attr(temp, "ynames") <- NULL
stopifnot(identical(temp.nocolnames, temp))
source("test.epilog.R") |
NULL
if (getRversion() >= "2.15.1") {
utils::globalVariables(".")
utils::globalVariables("where")
} |
ISOClassification <- R6Class("ISOClassification",
inherit = ISOCodeListValue,
private = list(
xmlElement = "MD_ClassificationCode",
xmlNamespacePrefix = "GMD"
),
public = list(
initialize = function(xml = NULL, value, description = NULL){
super$initialize(xml = xml, id = private$xmlElement, value = value,
description = description, setValue = FALSE)
}
)
)
ISOClassification$values <- function(labels = FALSE){
return(ISOCodeListValue$values(ISOClassification, labels))
} |
.onLoad <- function (lib, pkg)
{
guiWidgets(.GUI) <- "tcltkGUI"
} |
extract_matrix.RowLinkedMatrix <- function(x, i, j, ...) {
if (length(i) == 0L) {
Z <- matrix(data = integer(), nrow = 0L, ncol = length(j), dimnames = list(NULL, colnames(x)[j]))
} else {
index <- index(x, i = i, sort = FALSE)
nodeList <- unique(index[, 1L])
if (length(nodeList) > 1L) {
Z <- matrix(data = integer(), nrow = length(i), ncol = length(j), dimnames = list(rownames(x)[i], colnames(x)[j]))
for (curNode in nodeList) {
if (is.na(curNode)) {
nodeIndex = is.na(index[, 1L])
Z[nodeIndex, ] <- NA_integer_
} else {
nodeIndex <- index[, 1L] == curNode
nodeIndex[is.na(nodeIndex)] <- FALSE
Z[nodeIndex, ] <- as.matrix(x[[curNode]][index[nodeIndex, 3L], j, drop = FALSE])
}
}
} else {
if (is.na(nodeList)) {
Z <- matrix(data = NA_integer_, nrow = length(i), ncol = length(j), dimnames = list(rep(NA_character_, length(i)), colnames(x)[j]))
} else {
Z <- as.matrix(x[[nodeList]][index[, 3L], j, drop = FALSE])
}
}
}
return(Z)
}
extract_vector.RowLinkedMatrix <- function(x, i, ...) {
if (length(i) == 0L) {
Z <- integer(0L)
} else {
ij <- ktoij(x, i)
rowsPerNode <- sapply(x, nrow)
nodeBoundaries <- c(0L, cumsum(rowsPerNode))
nodeMembership <- .bincode(ij[["i"]], nodeBoundaries)
nodeList <- unique(nodeMembership)
if (length(nodeList) > 1L) {
Z <- vector(mode = "integer", length = length(i))
for (curNode in nodeList) {
if (is.na(curNode)) {
nodeIndex <- is.na(nodeMembership)
Z[nodeIndex] <- NA_integer_
} else {
nodeIndex <- nodeMembership == curNode
nodeIndex[is.na(nodeIndex)] <- FALSE
localIndex <- ((ij[["j"]][nodeIndex] - 1L) * rowsPerNode[curNode] + ij[["i"]][nodeIndex]) - nodeBoundaries[curNode]
Z[nodeIndex] <- x[[curNode]][localIndex]
}
}
} else {
if (is.na(nodeList)) {
Z <- rep(NA_integer_, length(i))
} else {
localIndex <- ((ij[["j"]] - 1L) * rowsPerNode[nodeList] + ij[["i"]]) - nodeBoundaries[nodeList]
Z <- x[[nodeList]][localIndex]
}
}
}
return(Z)
}
replace_matrix.RowLinkedMatrix <- function(x, i, j, ..., value) {
dim(value) <- c(length(i), length(j))
index <- index(x, i = i, sort = FALSE)
nodeList <- unique(index[, 1L])
for (curNode in nodeList) {
nodeIndex <- index[, 1L] == curNode
x[[curNode]][index[nodeIndex, 3L], j] <- value[nodeIndex, ]
}
return(x)
}
replace_vector.RowLinkedMatrix <- function(x, i, ..., value) {
ij <- ktoij(x, i)
rowsPerNode <- sapply(x, nrow)
nodeBoundaries <- c(0L, cumsum(rowsPerNode))
nodeMembership <- .bincode(ij[["i"]], nodeBoundaries)
nodeList <- unique(nodeMembership)
for (curNode in nodeList) {
nodeIndex <- nodeMembership == curNode
localIndex <- ((ij[["j"]][nodeIndex] - 1L) * rowsPerNode[curNode] + ij[["i"]][nodeIndex]) - nodeBoundaries[curNode]
x[[curNode]][localIndex] <- value[nodeIndex]
}
return(x)
}
dim.RowLinkedMatrix <- function(x) {
p <- ncol(x[[1L]])
n <- 0L
for (i in 1L:nNodes(x)) {
n <- n + nrow(x[[i]])
}
return(c(n, p))
}
rownames.RowLinkedMatrix <- function(x) {
nodes <- nodes(x)
names <- rep("", nodes[nrow(nodes), 3L])
for (i in seq_len(nrow(nodes))) {
nodeNames <- rownames(x[[i]])
if (!is.null(nodeNames)) {
names[(nodes[i, 2L]:nodes[i, 3L])] <- nodeNames
}
}
if (all(names == "")) {
names <- NULL
}
return(names)
}
colnames.RowLinkedMatrix <- function(x) {
colnames(x[[1L]])
}
dimnames.RowLinkedMatrix <- function(x) {
list(rownames.RowLinkedMatrix(x), colnames.RowLinkedMatrix(x))
}
`rownames<-.RowLinkedMatrix` <- function(x, value) {
nodes <- nodes(x)
for (i in 1L:nrow(nodes)) {
rownames(x[[i]]) <- value[(nodes[i, 2L]:nodes[i, 3L])]
}
return(x)
}
`colnames<-.RowLinkedMatrix` <- function(x, value) {
for (i in 1L:nNodes(x)) {
colnames(x[[i]]) <- value
}
return(x)
}
`dimnames<-.RowLinkedMatrix` <- function(x, value) {
d <- dim(x)
rownames <- value[[1L]]
colnames <- value[[2L]]
if (!is.list(value) || length(value) != 2L || !(is.null(rownames) || length(rownames) == d[1L]) || !(is.null(colnames) ||
length(colnames) == d[2L])) {
stop("invalid dimnames")
}
x <- `rownames<-.RowLinkedMatrix`(x, rownames)
x <- `colnames<-.RowLinkedMatrix`(x, colnames)
return(x)
}
rbind.RowLinkedMatrix <- function(..., deparse.level = 1L) {
dotdotdot <- list(...)
nodes <- list()
for (i in seq_along(dotdotdot)) {
node <- dotdotdot[[i]]
if (is(node, "LinkedMatrix")) {
nodes <- append(nodes, slot(node, ".Data"))
} else {
nodes <- append(nodes, node)
}
}
do.call(RowLinkedMatrix, nodes)
}
nodes.RowLinkedMatrix <- function(x) {
rowsPerNode <- sapply(x, nrow)
rowUpperBoundaries <- cumsum(rowsPerNode)
rowLowerBoundaries <- rowUpperBoundaries - rowsPerNode + 1
n <- length(rowsPerNode)
nodes <- matrix(data = c(1:n, rowLowerBoundaries, rowUpperBoundaries), nrow = n, ncol = 3L, dimnames = list(NULL, c("node", "row.ini", "row.end")))
return(nodes)
}
index.RowLinkedMatrix <- function(x, i = NULL, sort = TRUE, ...) {
nodes <- nodes(x)
if (!is.null(i)) {
i <- as.integer(i)
if (sort) {
i <- sort(i)
}
} else {
i <- seq_len(nodes[nrow(nodes), 3L])
}
nodeBoundaries <- c(0L, nodes[, 3L])
nodeMembership <- .bincode(i, breaks = nodeBoundaries)
index <- matrix(data = c(nodeMembership, i, i - nodeBoundaries[nodeMembership]), nrow = length(i), ncol = 3L, dimnames = list(NULL, c("node", "row.global", "row.local")))
return(index)
}
as.RowLinkedMatrix <- function(x, ...) {
UseMethod("as.RowLinkedMatrix")
}
as.RowLinkedMatrix.list <- function(x, ...) {
do.call(RowLinkedMatrix, x, ...)
}
RowLinkedMatrix <- setClass("RowLinkedMatrix", contains = "list")
setValidity("RowLinkedMatrix", function(object) {
nodes <- slot(object, ".Data")
if (length(nodes) == 0L) {
return("there needs to be at least one node")
}
if (!all(sapply(nodes, isMatrixLike))) {
return("arguments need to be matrix-like")
}
if (length(unique(sapply(nodes, ncol))) != 1L) {
return("arguments need the same number of columns")
}
names <- lapply(nodes, colnames)
if (length(names) > 1L && !all(duplicated(names) | duplicated(names, fromLast = TRUE))) {
warning("column names of matrix-like objects do not match: colnames() only uses the column names of the first node")
}
return(TRUE)
})
`[.RowLinkedMatrix` <- extract(
extract_vector = extract_vector.RowLinkedMatrix,
extract_matrix = extract_matrix.RowLinkedMatrix,
allowDoubles = TRUE
)
`[<-.RowLinkedMatrix` <- replace(
replace_vector = replace_vector.RowLinkedMatrix,
replace_matrix = replace_matrix.RowLinkedMatrix,
allowDoubles = TRUE
) |
packageStartupMessage("This is gllm 0.34")
emgllm <- function(y,s,X,maxit=1000,tol=0.00001) {
if (typeof(X)=="language") {
X<-model.matrix(X)
}
X<-cbind(X,double(nrow(X)))
em<-emgllmfitter(y,s,X,maxit,tol)
deviance=2 * sum(em$y * log(em$y / em$f), na.rm=TRUE)
observed.values<-em$y
fitted.values<-em$f
full.table<-em$e
list(deviance=deviance,
observed.values=observed.values,
fitted.values=fitted.values,
full.table=full.table)
}
emgllmfitter <- function(y,s,X,maxit,tol)
.C("gllm",
y = as.double(y),
ji = as.integer(s-1),
c = X,
istop = as.integer(maxit),
conv = as.double(tol),
e = double(nrow(X)) + 1,
ni = as.integer(nrow(X)),
nj = as.integer(length(y)),
nk = as.integer(ncol(X)-1),
f = double(length(y)),
PACKAGE="gllm")
scatter<- function(y,s) {
S<-matrix(rep(0,length(y)*length(s)),nrow=length(y))
for(i in 1:length(s)) if (s[i]<=length(y)) S[s[i],i]<-1
t(S)
}
scoregllm<-function(y,s,X,m,tol=1e-5) {
eps<-0.00001
call <- match.call()
formula<-NULL
if (typeof(X)=="language") {
formula<-X
X<-model.matrix(X)
}
X<-t(X)
S<-scatter(y,s)
z<-as.vector(S %*% solve(t(S) %*% S, tol=1e-10) %*% y)
iter<- 0
olddev<- -1
deviance<- 0
b<-qr.solve(t(X),log(m),tol=1e-10)
while(abs(olddev-deviance)>tol) {
iter<-iter+1
olddev<-deviance
if (iter>1) m<- as.vector(exp(t(X) %*% b))
P<- S %*% solve(t(S) %*% diag(m) %*% S, tol=1e-10) %*% t(S) %*% diag(m)
A<- P %*% t(X)
V<- t(A) %*% diag(m) %*% A
V<- qr.solve(V,tol=1e-10)
b<- b - V %*% t(A) %*% (m - z)
f<- as.vector(t(S) %*% m)
use<-(y>eps & f>eps)
deviance<- 2.0*sum(y[use]*log(y[use]/f[use]))
}
observed.values<-y
fitted.values<-f
residuals<- f
residuals[f>0]<-(y[f>0]-f[f>0])/sqrt(f[f>0])
full.table<-m
coefficients<-as.vector(b)
names(coefficients)<-rownames(X)
bl<-(rownames(X)=="")
names(coefficients)[bl]<-paste("beta",1:nrow(X),sep="")[bl]
se<-sqrt(diag(V))
df<-length(y)-qr(X)$rank
res<-list(call=call,formula=formula,
iter=iter,deviance=deviance,df=df,
coefficients=coefficients,se=se,V=V,
observed.values=observed.values,
fitted.values=fitted.values,
residuals=residuals,
full.table=full.table)
class(res) <- "gllm"
res
}
gllm <- function(y,s,X,method="hybrid",em.maxit=1,tol=0.00001) {
if (method=="hybrid" || method=="scoring") {
scoregllm(y,s,X,as.array(emgllm(y,s,X,maxit=em.maxit,tol=tol)$full.table))
}else{
scoregllm(y,s,X,as.array(emgllm(y,s,X,maxit=10000,tol=tol)$full.table))
}
}
summary.gllm <- function(object, ...) {
tab.coef<-data.frame(object$coefficients,
object$se,
exp(object$coefficients),
exp(object$coefficients-1.96*object$se),
exp(object$coefficients+1.96*object$se),
row.names=names(object$coefficients))
colnames(tab.coef)<-c("Estimate","S.E.","exp(Estimate)",
"Lower 95% CL","Upper 95% CL")
tab.fitted<-data.frame(object$observed.values,
object$fitted.values,
object$residuals)
colnames(tab.fitted)<-c("Observed Count","Predicted","Residual")
summary<- list()
summary$call<-object$call
summary$nobs<-length(object$observed.values)
summary$nfull<-length(object$full.table)
summary$mean.cell<-mean(object$observed.values)
summary$deviance<-object$deviance
summary$model.df<-object$df
summary$coefficients<-tab.coef
summary$residuals<-tab.fitted
class(summary) <- "summary.gllm"
summary
}
print.summary.gllm <- function(x, digits=NULL, show.residuals = FALSE, ...) {
if (is.null(digits))
digits <- options()$digits
else options(digits=digits)
cat("\nCall:\n")
cat(paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
cat("\nNo. cells in observed table: ", x$nobs, "\n",sep="")
cat("No. cells in complete table: ", x$nfull, "\n",sep="")
cat(" Mean observed cell size: ", x$mean.cell, "\n",sep="")
cat(" Model Deviance (df): ", formatC(x$deviance,digits=2,format="f"),
" (", x$model.df, ")\n\n",sep="")
print(x$coefficients, digits=digits)
if (show.residuals) {
cat("\n")
print(x$residuals, digits=digits)
}
}
boot.table <- function(y,strata=NULL) {
ynew<-rep(0.5, length(y))
if (is.null(strata)) {
tab.ynew<-table(sample(rep(1:length(y),y),replace=TRUE))
ynew[as.integer(names(tab.ynew))]<-tab.ynew
}else{
s<-as.integer(strata)
for(i in unique(s)) {
idx<-s==i
tab.ynew<-table(sample(rep((1:length(y))[idx],y[idx]),replace=TRUE))
ynew[as.integer(names(tab.ynew))]<-tab.ynew
}
}
ynew
}
boot.gllm <- function(y,s,X,method="hybrid",em.maxit=1,tol=0.00001,
strata=NULL,R=200) {
if (method=="hybrid" || method=="scoring") {
f0<-scoregllm(y,s,X,as.array(emgllm(y,s,X,maxit=em.maxit,tol=tol)$full.table))$full.table
}else{
f0<-scoregllm(y,s,X,as.array(emgllm(y,s,X,maxit=10000,tol=tol)$full.table))$full.table
}
result<-as.matrix(t(f0))
cat("It",0,":",y,"\n")
for(i in 1:R) {
ynew<-boot.table(y,strata=strata)
cat("It",i,":",ynew,"\n")
result<-rbind(result, t(scoregllm(ynew,s,X,as.array(emgllm(ynew,s,X,
maxit=em.maxit,tol=tol)$full.table))$full.table))
}
result
}
anova.gllm <- function(object, ..., test = c("Chisq", "none"))
{
modelname<-unlist(strsplit(deparse(match.call()),"[(),]"))
modelname<-gsub("[() ]","",modelname)
modelname<-gsub("object=","",modelname)
modelname<-modelname[-c(1,grep("=",modelname))]
test <- match.arg(test)
dots <- list(...)
mlist <- list(object, ...)
nt <- length(mlist)
dflis <- sapply(mlist, function(x) x$df)
s <- order(dflis, decreasing=TRUE)
mlist <- mlist[s]
if(any(!sapply(mlist, inherits, "gllm"))) {
stop("not all objects are of class `gllm'")
}
mds <- modelname[s]
dfs <- dflis[s]
lls <- sapply(mlist, function(x) x$deviance)
tss <- ""
if (nt>1) tss <- c("", paste(1:(nt - 1), 2:nt, sep = " vs "))
df <- c(NA, -diff(dfs))
x2 <- c(NA, -diff(lls))
pr <- c(NA, 1 - pchisq(x2[-1], df[-1]))
out <- data.frame(Model = mds, Resid.df = dfs,
Deviance = lls, Pr.Fit = 1-pchisq(lls,dfs),
Test = tss, Df = df, LRtest = x2,
Prob = pr)
names(out) <- c("Model", "Resid. df", "Resid. Dev", "Pr(GOFChi)",
"Test", " Df", "LR stat.", "Pr(Chi)")
if(test=="none") out <- out[, 1:6]
class(out) <- c("Anova", "data.frame")
attr(out, "heading") <-
c("Likelihood ratio tests of Loglinear Models\n")
out
}
ld2 <- function(locus1, locus2=NULL) {
all.possible.genos <- function(genotypes,gtp.sep="/") {
alleles<- sort(unique(unlist(strsplit(genotypes[!is.na(genotypes)], gtp.sep))))
gtp<-cbind(rep(alleles,seq(length(alleles),1,-1)),
rev(alleles)[sequence(seq(length(alleles),1,-1))])
paste(gtp[,1],gtp[,2],sep=gtp.sep)
}
genofactor <- function(genotypes, gtp.sep="/") {
factor(genotypes, levels=all.possible.genos(genotypes))
}
ng.to.nall<-function(ngenos) (sqrt(1+8*ngenos)-1)/2
if (is.null(locus2)) {
if (is.table(locus1) && length(dim(locus1))==2) {
ld.table<-locus1
}else if (is.data.frame(locus1)) {
ld.table<-table(genofactor(locus1[,1]), genofactor(locus1[,2]))
}
}else{
ld.table<-table(genofactor(locus1), genofactor(locus2))
}
siz<-dim(ld.table)
if (length(siz)==2 && siz[1]>1 && all(siz>1)) {
nall1<-ng.to.nall(siz[1])
nall2<-ng.to.nall(siz[2])
m0<-ld2.model(nall1,nall2,"~a1+a2")
m1<-ld2.model(nall1,nall2,"~a1+a2+d")
m2<-ld2.model(nall1,nall2,"~a1+a2+p1")
m3<-ld2.model(nall1,nall2,"~a1+a2+p1+p2")
m4<-ld2.model(nall1,nall2,"~a1+a2+p1+p2+d")
m0<-gllm(c(t(ld.table)),m0$s,m0$X,method="hybrid",em.maxit=1,tol=0.00001)
m1<-gllm(c(t(ld.table)),m1$s,m1$X,method="hybrid",em.maxit=1,tol=0.00001)
m2<-gllm(c(t(ld.table)),m2$s,m2$X,method="hybrid",em.maxit=1,tol=0.00001)
m3<-gllm(c(t(ld.table)),m3$s,m3$X,method="hybrid",em.maxit=1,tol=0.00001)
m4<-gllm(c(t(ld.table)),m4$s,m4$X,method="hybrid",em.maxit=1,tol=0.00001)
res<-list(m0=m0,m1=m1,m2=m2,m3=m3,m4=m4)
class(res)<-"ld2"
res
}else{
cat("Must have two polymorphic loci\n")
}
}
print.ld2 <- function(x,...) {
cat("\nAssuming HWE\n")
print(summary(x$m1))
cat("\n")
print(anova(x$m0,x$m1))
cat("\nModelling HWD\n")
print(summary(x$m4))
cat("\n")
print(anova(x$m0,x$m2,x$m3,x$m4))
}
ld2.model <- function(nall1, nall2, formula="~a1+a2+p1+p2+d") {
mkgeno<-function(nall) {
lab<-t(outer(1:nall, 1:nall, paste,sep="/"))
lab[lower.tri(lab,diag=TRUE)]
}
ld.terms<-function(nall1, nall2, formula=formula) {
nter<-cumsum(c(1,nall1-1,nall2-1, (nall1-1)*(nall1-1),
(nall2-1)*(nall2-1), (nall1-1)*(nall2-1)))
ter<-pmatch(unlist(strsplit(formula,"[~+]")),c("a1","a2","p1","p2","d"))
ter<-ter[!is.na(ter)]
res<-1
for(i in ter) res<-append(res,seq(nter[i]+1, nter[i+1]))
res
}
ng1<-nall1*(nall1+1)/2
ng2<-nall2*(nall2+1)/2
gam<-nall1*nall1*nall2*nall2
gen<-ng1*ng2
mod<-nall1+nall2-1+
(nall1-1)*(nall1-1)+(nall2-1)*(nall2-1)+
(nall1-1)*(nall2-1)
Geno<-matrix(1:gen, nrow=ng1, byrow=TRUE)
rownames(Geno)<-mkgeno(nall1)
colnames(Geno)<-mkgeno(nall2)
S<-array(0, dim=c(nall1,nall1,nall2,nall2))
X<-matrix(0, nrow=gam, ncol=mod)
colnames(X)<-c("Int",paste("a1",2:nall1,sep="."),
paste("a2",2:nall2,sep="."),
paste("p1",outer(2:nall1,2:nall1,paste,sep=""),sep="."),
paste("p2",outer(2:nall2,2:nall2,paste,sep=""),sep="."),
paste("d",outer(2:nall1,2:nall2,paste,sep=""),sep="."))
k<-0
for(i in 1:nall1) for(i2 in 1:i)
for(j in 1:nall2) for(j2 in 1:j) {
k<-k+1
S[i,i2,j,j2]<-S[i,i2,j2,j]<-S[i2,i,j,j2]<-S[i2,i,j2,j]<-k
}
S<-matrix(S, nrow=nall1*nall1, ncol=nall2*nall2)
rownames(S)<-outer(1:nall1,1:nall1,paste,sep="/")
colnames(S)<-outer(1:nall2,1:nall2,paste,sep="/")
k<-0
hap<-rep(" ",gam)
for(i in 1:nall1) for(i2 in 1:nall1)
for(j in 1:nall2) for(j2 in 1:nall2) {
k<-k+1
a1<-rep(0,nall1)
a1[i]<-a1[i]+1
a1[i2]<-a1[i2]+1
p1<-matrix(0, nrow=nall1, ncol=nall1)
p1[i,i2]<-p1[i,i2]+1
a2<-rep(0,nall2)
a2[j]<-a2[j]+1
a2[j2]<-a2[j2]+1
p2<-matrix(0, nrow=nall2, ncol=nall2)
p2[j,j2]<-p2[j,j2]+1
d<-matrix(0, nrow=nall1, ncol=nall2)
d[i, j2]<-d[i, j2]+1
d[i2, j]<-d[i2, j]+1
X[k,]<-c(1,a1[-1],a2[-1],c(p1[-1,-1]), c(p2[-1,-1]), c(d[-1,-1]))
hap[k]<-paste(i,j,";",i2,j2,sep="")
}
rownames(X)<-hap
s<-c(t(S))
names(s)<-hap
list(Geno=Geno, s=s, X=X[,ld.terms(nall1,nall2,formula)])
} |
match.arg.ext = function(arg, choices, base = 1, several.ok = FALSE,
numeric = FALSE, ignore.case = FALSE)
{
if (missing(choices)) {
formal.args <- formals(sys.function(sys.parent()))
choices <- eval(formal.args[[deparse(substitute(arg))]])
}
if (is.character(arg)) {
if (ignore.case) {
choices = tolower(choices)
arg = tolower(arg)
}
res = match.arg(arg=arg,choices=choices,several.ok=several.ok)
if (numeric) res = which(choices %in% res) + base - 1
} else if (is.numeric(arg)) {
if ( (arg<base) | (arg>(length(choices)+base-1)) )
stop("'arg' should be between ",base," and ",length(choices)+base-1)
if (numeric) {
res = arg
} else {
res = choices[arg - base + 1]
}
} else stop("'arg' should be numeric or character")
return(res)
} |
context("setting environmental data")
test_that("Hmsc returns error both XData and X are given", {
expect_error(Hmsc(Y=matrix(1:10),XData=data.frame(x1 = 1:10),X=matrix(1:10)),"only one of XData and X arguments must be specified")
})
test_that("Hmsc returns error when XData is not a data frame or list of data frames", {
expect_error(Hmsc(Y=matrix(1:10),XData=matrix(1:10)), NULL)
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),XData=list(s1 = 1:10, s2 = 1:10)),"each element of X list must be a data.frame")
})
test_that("Hmsc returns error when X is not a matrix", {
expect_error(Hmsc(Y=matrix(1:10),X=data.frame(x1 = 1:10)),"X must be a matrix or a list of matrix objects")
expect_error(Hmsc(Y=matrix(1:10),X=list(s1 = data.frame(x1 = 1:10))),"each element of X list must be a matrix")
})
test_that("Hmsc returns error when X or XData contains NA values", {
expect_error(Hmsc(Y=matrix(1:10),X=list(x1 = matrix(c(1:9,NA)))),"NA values are not allowed in X")
expect_error(Hmsc(Y=matrix(1:10),XData=list(x1 = data.frame(c(1:9,NA)))),"NA values are not allowed in XData")
expect_error(Hmsc(Y=matrix(1:10),XData=data.frame(c(1:9,NA))),"NA values are not allowed in XData")
expect_error(Hmsc(Y=matrix(1:10),X=matrix(c(1:9,NA))),"NA values are not allowed in X")
})
test_that("Hmsc returns error when the size of X or XData is not correct", {
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=list(s1 = matrix(1:10))),"the length of X list argument must be equal to the number of species")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),XData=list(s1=data.frame(x1 = 1:10))),"the length of XData list argument must be equal to the number of species")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),XData=list(s1=data.frame(x1 = 1:10),s2=data.frame(x1=1:9))),"for each element of XData list the number of rows must be equal to the number of sampling units")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),XData=data.frame(x1 = 1:9)),"the number of rows in XData must be equal to the number of sampling units")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=list(s1=matrix(1:18),s2=matrix(1:10))),"for each element of X list the number of rows must be equal to the number of sampling units")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:9)),"the number of rows in X must be equal to the number of sampling units")
})
test_that("Hmsc returns error when X contains more than one intercept column", {
Xmat = matrix(rep(1,20),nrow=10,ncol=2)
colnames(Xmat) = c("Intercept","(Intercept)")
Xdat = data.frame(Xmat)
XdatList = list(s1=Xdat,s2=Xdat)
expect_error(Hmsc(Y=matrix(1:10),X=Xmat), "only one column of X matrix can be named Intercept or (Intercept)",fixed=TRUE)
expect_error(Hmsc(Y=matrix(1:10),XData=Xdat),"only one column of X matrix can be named Intercept or (Intercept)",fixed=TRUE)
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),XData=XdatList),"only one column of X matrix can be named Intercept or (Intercept)",fixed=TRUE)
})
test_that("Hmsc returns error when intercept column does not only contain 1",{
Xmat = matrix(rep(1,20),nrow=10,ncol=2)
Xdat = data.frame(Xmat)
XdatList = list(s1=Xdat,s2=Xdat)
})
context("setting trait data")
test_that("Hmsc returns error when the wrong combination of Tr, TrData and TrFormula is given", {
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), TrData = data.frame(t1 = 1:2), Tr = matrix(1:2)),"only one of TrData and Tr arguments can be specified")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), TrData = data.frame(t1 = 1:2)),"TrFormula argument must be specified if TrData is provided")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), Tr = data.frame(t1 = 1:2)),"Tr must be a matrix")
})
test_that("Hmsc returns error when trait data does not have the right size",{
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), Tr = matrix(1:3)),"the number of rows in Tr should be equal to number of columns in Y")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), TrData = data.frame(t1=1:3),TrFormula = ~t1),"the number of rows in TrData should be equal to number of columns in Y")
})
test_that("Hmsc returns error when there are unknowns in trait data",{
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), Tr = matrix(c(1,NA))),"Tr parameter must not contain any NA values")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), TrData = data.frame(t1=c(1,NA)),TrFormula = ~t1),"TrData parameter must not contain any NA values")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10), TrData =data.frame(t1 = 1:2), TrFormula = ~ t2),"object 't2' not found")
})
test_that("Hmsc returns error when the intercept columns for Tr is not correctly specified",{
Traits = matrix(rep(1,4),nrow=2,ncol=2)
colnames(Traits) = c("Intercept","(Intercept)")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),Tr = Traits),"only one column of Tr matrix can be named Intercept or (Intercept)",fixed=TRUE)
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),TrData = data.frame(Traits),TrFormula = ~ Intercept + (Intercept)),"only one column of Tr matrix can be named Intercept or (Intercept)",fixed=TRUE)
Traits = matrix(rep(0,2),nrow=2,ncol=1)
colnames(Traits) = c("Intercept")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),Tr = Traits),"intercept column in Tr matrix must be a column of ones")
})
test_that("Hmsc returns error when intercept is specified in TrFormula",{
Traits = matrix(rep(1,4),nrow=2,ncol=2)
colnames(Traits) = c("Intercept","x1")
expect_error(Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),TrData = data.frame(Traits),TrFormula = ~ Intercept + x1),"only one column of Tr matrix can be named Intercept or (Intercept)",fixed=TRUE)
Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),TrData = data.frame(Traits),TrFormula = ~ x1)
})
context("setting phylogenetic data")
test_that("Hmsc returns error when both a tree and a correlation matrix are specified",{
expect_error(Hmsc(Y=matrix(1:10),X=matrix(1:10),phyloTree=TD$phy, C=TD$C),
"only one of phyloTree and C arguments can be specified")
})
test_that("Hmsc returns error when ",{
expect_error(Hmsc(Y=matrix(1:10),X=matrix(1:10), C=TD$C),
"the size of square matrix C must be equal to number of species")
})
context("setting latent structure")
test_that("Hmsc returns error when studydesign does not match random levels",{
expect_error(Hmsc(Y=matrix(1:10),X=matrix(1:10),ranLevels = TD$rL1),
"studyDesign is empty, but ranLevels is not")
expect_error(Hmsc(Y=matrix(1:10),X=matrix(1:10),ranLevels = TD$rL1,studyDesign = data.frame(sample = as.factor(1:10))),
"studyDesign must contain named columns corresponding to all levels listed in ranLevelsUsed")
expect_error(Hmsc(Y=matrix(1:10),X=matrix(1:10),ranLevels = list(unit =TD$rL1),studyDesign = data.frame(sample = as.factor(1:10))),
"studyDesign must contain named columns corresponding to all levels listed in ranLevelsUsed")
Hmsc(Y=matrix(1:10),X=matrix(1:10),ranLevels = list(sample =TD$rL1),studyDesign = data.frame(sample = as.factor(1:10)))
})
test_that("Hmsc returns error when studydesign does not match Y",{
expect_error(Hmsc(Y=matrix(1:10),X=matrix(1:10),ranLevels = list(unit =TD$rL1),studyDesign = data.frame(sample = as.factor(1:9))),
"the number of rows in studyDesign must be equal to number of rows in Y")
})
context("scaling")
test_that("Scaling for Y",{
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10))
expect_equivalent(colMeans(m$YScaled),c(11/2,31/2))
expect_equivalent(colMeans(m$Y),c(11/2,31/2))
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),YScale = TRUE)
expect_equivalent(colMeans(m$YScaled),c(0,0))
expect_equivalent(colMeans(m$Y),c(11/2,31/2))
expect_equivalent(round(m$YScalePar),matrix(c(6,3,16,3),ncol=2))
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),YScale = TRUE,distr = c('normal','probit'))
expect_equivalent(colMeans(m$YScaled),c(0,31/2))
expect_equivalent(colMeans(m$Y),c(11/2,31/2))
expect_equivalent(round(m$YScalePar),matrix(c(6,3,0,1),ncol=2))
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),YScale = TRUE,distr = c('poisson','lognormal poisson'))
expect_equivalent(colMeans(m$YScaled),c(11/2,31/2))
expect_equivalent(colMeans(m$Y),c(11/2,31/2))
})
test_that("Scaling for X",{
m = Hmsc(Y=matrix(1:10),X=matrix(1:10))
expect_equivalent(colMeans(m$X),5.5)
expect_equivalent(round(colMeans(m$XScaled)),1)
expect_equivalent(round(m$XScalePar),c(0,7))
m = Hmsc(Y=matrix(1:10),X=matrix(1:10),XScale = FALSE)
expect_equivalent(colMeans(m$X),5.5)
expect_equivalent(colMeans(m$XScaled),5.5)
m = Hmsc(Y=matrix(1:10),XData=data.frame(x1=1:10),XFormula = ~x1)
expect_equivalent(colMeans(m$X),c(1,5.5))
expect_equivalent(colMeans(m$XScaled),c(1,0))
expect_equivalent(round(m$XScalePar),matrix(c(0,1,6,3),ncol=2))
})
test_that("Scaling for traits",{
Traits = matrix(c(1,1,2,23),nrow=2,ncol=2)
colnames(Traits) = c("Intercept","x1")
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),TrData = data.frame(Traits),TrFormula = ~ x1)
expect_equivalent(m$Tr,Traits)
expect_equivalent(round(colMeans(m$TrScaled)),c(1,0))
expect_equivalent(round(m$TrScalePar),matrix(c(0,1,12,15),ncol=2))
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),Tr = Traits)
expect_equivalent(m$Tr,Traits)
expect_equivalent(round(colMeans(m$TrScaled)),c(1,0))
expect_equivalent(round(m$TrScalePar),matrix(c(0,1,12,15),ncol=2))
m = Hmsc(Y=matrix(1:20,nrow=10,ncol=2),X=matrix(1:10),Tr = Traits,TrScale = FALSE)
expect_equivalent(m$TrScaled,Traits)
})
context("Setting data model")
test_that("Family set correctly",{
m = Hmsc(Y=matrix(1:20,nrow=5,ncol=4),X=matrix(1:5),distr=c('probit','poisson','normal','lognormal poisson'))
expect_equivalent(m$distr[,1],c(2,3,1,3))
})
test_that("Variance set correctly",{
m = Hmsc(Y=matrix(1:20,nrow=5,ncol=4),X=matrix(1:5),distr=c('probit','poisson','normal','lognormal poisson'))
expect_equivalent(m$distr[,2],c(0,0,1,1))
})
test_that("Hmsc returns error when unsuitable data model is given",{
expect_error(Hmsc(Y=matrix(1:10,nrow=5,ncol=2),X=matrix(1:5),distr=c('probit','logit')),
"'arg' should be one of \"normal\", \"probit\", \"poisson\", \"lognormal poisson\"")
})
context("setting variable selection")
test_that("Hmsc is set correctly",{
m = Hmsc(Y=TD$Y,
XData=TD$X,
XFormula=~x1+x2,
TrData=TD$Tr,
TrFormula = ~T1 + T2,
phyloTree=TD$phy,
ranLevels=list("sample"=TD$rL2,"plot"=TD$rL1),
studyDesign = TD$studyDesign,
distr=c("probit"))
expect_equal(m$Y,TD$m$Y)
expect_equal(m$YScaled,TD$m$YScaled)
expect_equal(m$XData,TD$m$XData)
expect_equal(m$XScaled,TD$m$XScaled)
expect_equal(m$C,TD$m$C)
expect_equal(m$Pi,TD$m$Pi)
expect_equal(m$studyDesign,TD$m$studyDesign)
expect_equal(m$TrData,TD$m$TrData)
expect_equal(m$ranLevels,TD$m$ranLevels)
expect_equal(m$ranLevelsUsed,TD$m$ranLevelsUsed)
expect_equal(m$dfPi,TD$m$dfPi)
expect_equal(m$phyloTree,TD$m$phyloTree)
expect_equal(m$TrScaled,TD$m$TrScaled)
}) |
source("ESEUR_config.r")
library("pwr")
plot_layout(2, 1)
pal_col=rainbow(3)
ff=read.csv(paste0(ESEUR_dir, "faults/firefox.csv.xz"), as.is=TRUE)
fit_fails=function(fail_count, ff_data, is_quasi)
{
y=cbind(fail_count, 10-fail_count)
b_mod=glm(y ~ (cpu_speed+memory+disk_size)^3, data=ff_data,
family=ifelse(is_quasi, quasibinomial, binomial))
t=stepAIC(b_mod, trace=0)
return(t)
}
power.test=function(base_prob, p_diff, num_runs = 10, req_pow = NULL)
{
t = pwr.2p.test(h = ES.h(base_prob+p_diff, base_prob),
n = num_runs,
sig.level = 0.05,
power = req_pow)
return(t)
}
base_p=c(0.5, 2.5, 5.0)
plot(1, type="n",
xaxs="i", yaxs="i",
xlim=range((1:45)/100), ylim=c(0, 0.9),
xlab="Difference", ylab="Power\n")
for (ip in 1:3)
{
pow=sapply(1:45, function(X)
power.test(base_p[ip]/10, X/100, 10)$power)
lines((1:45)/100, pow, col=pal_col[ip])
pow=sapply(1:45, function(X)
power.test(base_p[ip]/10, X/100, 50)$power)
lines((1:45)/100, pow, col=pal_col[ip])
}
text(0.20, 0.7, "50")
text(0.25, 0.3, "10")
title("Power of experiment", cex.main=1.1)
legend("bottomright", legend=as.character(base_p/10), bty="n",
title="Before", fill=pal_col, cex=1.3)
plot(1, type="n", log="y",
xaxs="i", yaxs="i",
xlim=range((1:45)/100), ylim=c(10, 1000),
xlab="Difference", ylab="Runs\n")
for (ip in 1:3)
{
pow=sapply(1:45, function(X)
power.test(base_p[ip]/10, X/100, NULL, 0.8)$n)
lines((1:45)/100, pow, ,ylim=c(10, 1000), col=pal_col[ip])
}
title("Runs needed", cex.main=1.1)
legend("bottomleft", legend=as.character(base_p/10), bty="n",
title="Before", fill=pal_col, cex=1.3)
|
library(rethinking)
library(animation)
polar2screen <- function( dist, origin, theta ) {
vx <- cos(theta) * dist;
vy <- sin(theta) * dist;
c( origin[1]+vx , origin[2]+vy );
}
screen2polar <- function( origin, dest ) {
vx <- dest[1] - origin[1];
vy <- dest[2] - origin[2];
dist <- sqrt( vx*vx + vy*vy );
theta <- asin( abs(vy) / dist );
if( vx < 0 && vy < 0 ) theta <- pi + theta;
if( vx < 0 && vy > 0 ) theta <- pi - theta;
if( vx > 0 && vy < 0 ) theta <- 2*pi - theta;
if( vx < 0 && vy==0 ) theta <- pi;
if( vx==0 && vy < 0 ) theta <- 3*pi/2;
c( theta, dist );
}
point.polar <- function(dist,theta,origin=c(0,0),draw=TRUE,...) {
pt <- polar2screen(dist,origin,theta)
if ( draw==TRUE ) points( pt[1] , pt[2] , ... )
invisible( pt )
}
line.polar <- function(dist,theta,origin=c(0,0),...) {
pt1 <- polar2screen(dist[1],origin,theta)
pt2 <- polar2screen(dist[2],origin,theta)
lines( c(pt1[1],pt2[1]), c(pt1[2],pt2[2]) , ... )
}
line.short <- function(x,y,short=0.1,...) {
pt1 <- c(x[1],y[1])
pt2 <- c(x[2],y[2])
theta <- screen2polar( pt1 , pt2 )[1]
dist <- screen2polar( pt1 , pt2 )[2]
q1 <- polar2screen( short , pt1 , theta )
q2 <- polar2screen( dist-short , pt1 , theta )
lines( c(q1[1],q2[1]) , c(q1[2],q2[2]) , ... )
}
wedge <- function(dist,start,end,pt,hedge=0.1,alpha,lwd=2,draw=TRUE,hit,...) {
n <- length(pt)
points.save <- matrix(NA,nrow=n,ncol=2)
span <- abs(end-start)
span2 <- span*(1 - 2*hedge)
origin <- start + span*hedge
gap <- span2/n
theta <- origin + gap/2
border <- rep("black",length(pt))
if ( !missing(hit) ) border <- ifelse( hit==1 , 2 , 1 )
if ( !missing(alpha) ) {
pt <- sapply( 1:length(pt) , function(i) col.alpha(pt[i],alpha[i]) )
border <- sapply( 1:length(pt) , function(i) col.alpha(border[i],alpha[i]) )
}
for ( i in 1:n ) {
points.save[i,] <- point.polar( dist , theta , pch=21 , lwd=lwd , bg=pt[i] , col=border[i] , draw=draw, ... )
theta <- theta + gap
}
points.save
}
point_on_line <- function( x , y , p ) {
X <- x[1]*(1-p) + x[2]*p
Y <- y[1]*(1-p) + y[2]*p
c(X,Y)
}
garden <- function( arc , possibilities , data , alpha.fade = 0.25 , col.open=2 , col.closed=1 , hedge=0.1 , hedge1=0 , newplot=TRUE , plot.origin=FALSE , cex=1.5 , lwd=2 , adj.cex , adj.lwd , lwd.dat=1 , ring_dist , progression , prog_dat , xlim=c(-1,1) , ylim=c(-1,1) , thresh=0.2 , ... ) {
poss.cols <- ifelse( possibilities==1 , rangi2 , "white" )
if ( missing(adj.cex) ) adj.cex=rep(1,length(data))
if ( missing(adj.lwd) ) adj.lwd=rep(1,length(data))
if ( newplot==TRUE ) {
par(mgp = c(1.5, 0.5, 0), mar = c(1, 1, 1, 1) + 0.1, tck = -0.02)
plot( NULL , xlim=xlim , ylim=ylim , bty="n" , xaxt="n" , yaxt="n" , xlab="" , ylab="" )
}
if ( plot.origin==TRUE ) point.polar( 0 , 0 , pch=16 )
N <- length(data)
n_poss <- length(possibilities)
goldrat <- 1.618
if ( missing(ring_dist) ) {
ring_dist <- rep(1,N)
if ( N>1 )
for ( i in 2:N ) ring_dist[i] <- ring_dist[i-1]*goldrat
ring_dist <- ring_dist / sum(ring_dist)
}
if ( length(alpha.fade)==1 ) alpha.fade <- rep(alpha.fade,N)
if ( length(col.open)==1 ) col.open <- rep(col.open,N)
if ( length(col.closed)==1 ) col.closed <- rep(col.closed,N)
draw_wedge <- function(r,hit_prior,arc2,hedge=0.1,hedge1=0,lines_to) {
hit <- hit_prior * ifelse( possibilities==data[r] , 1 , 0 )
alpha <- ifelse( hit==1 , 1 , alpha.fade[r] )
the_col <- ifelse( hit==1 , col.open , col.closed )
hedge_use <- ifelse( r==1 , hedge1 , hedge )
do_draw <- TRUE
if ( progression[r] < 1 ) do_draw <- FALSE
rd <- 0
for ( rdi in 1:r ) rd <- rd + ring_dist[rdi]
if ( prog_dat[r] == 1 )
pts <- wedge( rd , arc2[1] , arc2[2] , poss.cols , hedge=hedge_use , alpha=alpha , cex=cex*adj.cex[r] , lwd=lwd*adj.lwd[r] , draw=do_draw , hit=hit )
else
pts <- wedge( rd , arc2[1] , arc2[2] , poss.cols , hedge=hedge_use , alpha=alpha , cex=cex*adj.cex[r] , lwd=lwd*adj.lwd[r] , draw=do_draw )
if ( N > r ) {
span <- abs( arc2[1] - arc2[2] ) / n_poss
for ( j in 1:n_poss ) {
new_arc <- c( arc2[1]+span*(j-1) , arc2[1]+span*j )
pts2 <- draw_wedge(r+1,hit[j],new_arc,hedge,lines_to=pts[j,])
}
}
if ( !missing(lines_to) ) {
for ( k in 1:n_poss ) {
if ( progression[r] > thresh ) {
ptend <- point_on_line( c(lines_to[1],pts[k,1]) , c(lines_to[2],pts[k,2]) , progression[r] )
line.short( c(lines_to[1],ptend[1]) , c(lines_to[2],ptend[2]) , lwd=lwd*adj.lwd[r] , short=0.04 , col=col.closed[1] )
}
if ( prog_dat[r] > thresh && hit[k]==1 ) {
ptend <- point_on_line( c(lines_to[1],pts[k,1]) , c(lines_to[2],pts[k,2]) , prog_dat[r] )
line.short( c(lines_to[1],ptend[1]) , c(lines_to[2],ptend[2]) , lwd=lwd*adj.lwd[r]+lwd.dat , short=0.04 , col=col.open[1] )
}
}
}
return(pts)
}
pts1 <- draw_wedge(1,1,arc=arc,hedge=hedge,lines_to=c(0,0))
invisible(pts1)
}
goldrat <- 1.618
ring_dist <- rep(1,3)
for ( i in 2:3 ) ring_dist[i] <- ring_dist[i-1]*goldrat
ring_dist <- ring_dist / sum(ring_dist)
dat <- c(1,0,1)
dat <- c(-1,-1,-1)
arc <- c( 0 , pi )
garden(
arc = arc,
possibilities = c(0,0,0,1),
data = dat,
hedge = 0.05,
ring_dist=ring_dist,
alpha.fade=1,
progression=c(1,1,0.1)
)
ani.record(reset = TRUE)
poss <- c(0,1,1,1)
nsteps <- 20
prog_seq <- seq( from=0 , to=1 , length=nsteps )
prog <- c(0,0,0)
for ( rr in 1:3 ) {
for ( p in prog_seq ) {
prog[rr] <- p
garden(
arc = arc,
possibilities = poss,
data = c(1,0,0),
hedge = 0.05,
ring_dist=ring_dist,
alpha.fade=1,
progression=prog,
prog_dat=c(0,0,0),
ylim=c(0,1),
thresh=0.3
)
ani.record()
}
}
oopts = ani.options(interval = 0.1)
ani.replay()
prog_seq <- seq( from=0 , to=1 , length=nsteps )
prog <- c(1,1,1)
prog2 <- c(0,0,0)
for ( rr in 1:3 ) {
for ( p in prog_seq ) {
prog2[rr] <- p
garden(
arc = arc,
possibilities = poss,
data = c(1,0,1),
hedge = 0.05,
ring_dist=ring_dist,
alpha.fade=1,
progression=prog,
prog_dat=prog2,
ylim=c(0,1),
lwd.dat=2,
thresh=0.3
)
ani.record()
}
}
oopts = ani.options(interval = 0.1)
ani.replay() |
library(FRAPO)
library(fPortfolio)
library(PerformanceAnalytics)
data(EuroStoxx50)
pr <- timeSeries(EuroStoxx50, charvec = rownames(EuroStoxx50))
NAssets <- ncol(pr)
RDP <- na.omit((pr / lag(pr, k = 1) - 1) * 100)
to <- time(RDP)[208:nrow(RDP)]
from <- rep(start(RDP), length(to))
DDbound <- 0.10
DDalpha <- 0.95
mvspec <- portfolioSpec()
BoxC <- c("minsumW[1:NAssets] = 0.0", "maxsumW[1:NAssets] = 1.0")
wMV <- wCD <- matrix(NA, ncol = ncol(RDP), nrow = length(to))
for(i in 1:length(to)){
series <- window(RDP, start = from[i], end = to[i])
prices <- window(pr, start = from[i], end = to[i])
mv <- minvariancePortfolio(data = series,
spec = mvspec,
constraints = BoxC)
cd <- PCDaR(prices, alpha = DDalpha, bound = DDbound,
softBudget = TRUE)
wMV[i, ] <- c(getWeights(mv))
wCD[i, ] <- Weights(cd)
}
wMV <- rbind(rep(NA, ncol(RDP)), wMV[-nrow(wMV), ])
wMVL1 <- timeSeries(wMV, charvec = to)
colnames(wMVL1) <- colnames(RDP)
wCD <- rbind(rep(NA, ncol(RDP)), wCD[-nrow(wCD), ])
wCDL1 <- timeSeries(wCD, charvec = to)
colnames(wCDL1) <- colnames(RDP)
RDPback <- RDP[to,]
colnames(RDPback) <- colnames(RDP) |
HAuni <- function(Sum,K,H)
{
H/(H + K)*Sum
}
Auni <- function(Sum,K,H)
{
K/(H + K)*Sum
}
H2Abi <- function(Sum, K1, K2, H)
{
(H^2/(H^2+K1*H+K1*K2))*Sum
}
HAbi <- function(Sum, K1, K2, H)
{
(K1*H/(H^2+K1*H+K1*K2))*Sum
}
Abi <- function(Sum, K1, K2, H)
{
(K1*K2/(H^2+K1*H+K1*K2))*Sum
}
H3Atri <- function(Sum, K1, K2, K3, H)
{
(H^3/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
H2Atri <- function(Sum, K1, K2, K3, H)
{
(K1*H^2/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
HAtri <- function(Sum, K1, K2, K3, H)
{
(K1*K2*H/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
Atri <- function(Sum, K1, K2, K3, H)
{
(K1*K2*K3/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
calcTA <- function(aquaenv,
H)
{
with (aquaenv,
{
HCO3 <- HAbi (SumCO2, K_CO2, K_HCO3, H)
CO3 <- Abi (SumCO2, K_CO2, K_HCO3, H)
return(HCO3 + 2*CO3 + calcTAMinor(aquaenv, H))
})
}
calcTAMinor <- function(aquaenv,
H)
{
with (aquaenv,
{
BOH4 <- Auni (SumBOH3, K_BOH3, H)
OH <- K_W / H
HPO4 <- HAtri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H)
PO4 <- Atri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H)
SiOOH3 <- HAbi (SumSiOH4, K_SiOH4, K_SiOOH3, H)
HS <- HAbi (SumH2S, K_H2S, K_HS, H)
S2min <- Abi (SumH2S, K_H2S, K_HS, H)
NH3 <- Auni (SumNH4, K_NH4, H)
HSO4 <- HAbi (SumH2SO4, K_H2SO4, K_HSO4, H)
HF <- HAuni (SumHF, K_HF, H)
H3PO4 <- H3Atri(SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H)
return(BOH4 + OH + HPO4 + 2*PO4 + SiOOH3 + HS + 2*S2min + NH3 - H - HSO4 - HF - H3PO4)
})
}
calcH_TA <- function(aquaenv,
TA)
{
H <- c()
aquaenv[["TA"]] <- TA
for (z in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[z,])
with (aquaenvtemp,
{
Htemp <- Technicals$Hstart; i <- 1
while ((abs(calcTA(aquaenvtemp, Htemp) - aquaenvtemp$TA) > Technicals$Haccur) && (i <= Technicals$maxiter))
{
a <- TA - calcTAMinor(aquaenvtemp, Htemp)
b <- K_CO2*(a-SumCO2)
c <- K_CO2*K_HCO3*(a-2*SumCO2)
Htemp <- (-b + sqrt(b^2 - (4*a*c)))/(2*a); i <- i + 1
if (Htemp<0) {break}
}
if ((Htemp < 0) || (i > Technicals$maxiter))
{
Htemp <- uniroot(function(x){calcTA(aquaenvtemp, x) - aquaenvtemp$TA},
Technicals$unirootinterval, tol=Technicals$uniroottol, maxiter=Technicals$maxiter)$root
}
H <<- c(H, Htemp)
})
}
return(H)
}
calcH_CO2 <- function(aquaenv,
CO2)
{
H <- c()
aquaenv[["CO2"]] <- CO2
for (x in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[x,])
with (aquaenvtemp,
{
a <- CO2 - SumCO2
b <- K_CO2*CO2
c <- K_CO2*K_HCO3*CO2
H <<- c(H, ((-b-sqrt(b^2 - 4*a*c))/(2*a)))
})
}
return(H)
}
calcSumCO2_pH_CO2 <- function(aquaenv,
pH,
CO2)
{
SumCO2 <- c()
aquaenv[["pH"]] <- pH
aquaenv[["CO2"]] <- CO2
for (x in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[x,])
with (aquaenvtemp,
{
H <- 10^{-pH}
denom <- H^2/(H^2 + H*K_CO2 + K_CO2*K_HCO3)
SumCO2 <<- c(SumCO2, (CO2/denom))
})
}
return(SumCO2)
}
calcSumCO2_pH_TA <- function(aquaenv,
pH,
TA)
{
SumCO2 <- c()
aquaenv[["pH"]] <- pH
aquaenv[["TA"]] <- TA
for (x in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[x,])
with (aquaenvtemp,
{
H <- 10^{-pH}
c2 <- (H*K_CO2) /(H^2 + H*K_CO2 + K_CO2*K_HCO3)
c3 <- (K_CO2*K_HCO3)/(H^2 + H*K_CO2 + K_CO2*K_HCO3)
numer <- TA - calcTAMinor(aquaenvtemp, H)
denom <- c2 + 2*c3
SumCO2 <<- c(SumCO2, (numer/denom))
})
}
return(SumCO2)
}
calcSumCO2_TA_CO2 <- function(aquaenv,
TA,
CO2)
{
SumCO2 <- c()
aquaenv[["TA"]] <- TA
aquaenv[["CO2"]] <- CO2
for (i in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[i,])
with (aquaenvtemp,
{
f <- function(x)
{
c1 <- (x^2) /(x^2 + x*K_CO2 + K_CO2*K_HCO3)
c2 <- (x*K_CO2) /(x^2 + x*K_CO2 + K_CO2*K_HCO3)
c3 <- (K_CO2*K_HCO3)/(x^2 + x*K_CO2 + K_CO2*K_HCO3)
return(TA - ((c2+2*c3)*(CO2/c1) + calcTAMinor(aquaenvtemp, x)))
}
H <- uniroot(f, Technicals$unirootinterval, tol=Technicals$uniroottol, maxiter=Technicals$maxiter)$root
attr(aquaenvtemp, "class") <- "aquaenv"
SumCO2 <<- c(SumCO2, calcSumCO2_pH_TA(aquaenvtemp, -log10(H), TA))
})
}
return(SumCO2)
} |
smoothCPPP <-
function(y, B, tau, lambdashort_glatt, lambdashort_orig, DD, NB, glatterms, smoothtype) {
.Call('_expectreg_smoothCPPP', PACKAGE = 'expectreg', y, B, tau, lambdashort_glatt, lambdashort_orig, DD, NB, glatterms, smoothtype)
} |
time_group("Printing graphs to the screen")
time_that("Print large graphs without attributes", replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000)) },
{ print(g) })
time_that("Summarize large graphs without attributes", replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000)) },
{ summary(g) })
time_that("Print large graphs with large graph attributes",
replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000));
g <- set_graph_attr(g, "foo", 1:1000000) },
{ print(g) })
time_that("Summarize large graphs with large graph attributes",
replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000));
g <- set_graph_attr(g, "foo", 1:1000000) },
{ summary(g) })
time_that("Print large graphs with vertex attributes", replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000));
g <- set_vertex_attr(g, 'foo',
value = as.character(seq_len(gorder(g)))) },
{ print(g) })
time_that("Summarize large graphs with vertex attributes", replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000));
g <- set_vertex_attr(g, 'foo',
value = as.character(seq_len(gorder(g)))) },
{ print(g) })
time_that("Print large graphs with edge attributes", replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000));
g <- set_edge_attr(g, 'foo',
value = as.character(seq_len(gsize(g)))) },
{ print(g) })
time_that("Summarize large graphs with edge attributes", replications = 10,
init = { library(igraph); set.seed(42) },
reinit = { g <- make_lattice(c(1000, 1000));
g <- set_edge_attr(g, 'foo',
value = as.character(seq_len(gsize(g)))) },
{ print(g) }) |
pattern_plots<-function(data, meta, low=NA,high=NA, Condition="Condition_1"){
if((is.na(low))||(is.na(high))){stop("You need to supply low an d high parameters for plotting")}
meta<-utils::read.csv(meta, header=TRUE)
meta<-meta[,c("Sample_ID",Condition)]
colnames(meta)<-c("Sample_ID","Condition")
data_temp<-data
rownames(data_temp)<-data$"Symbol"
data_temp<-data_temp[meta$"Sample_ID"]
data_temp$"Mean"<-apply(data_temp,1,mean)
data_temp<-data_temp[data_temp$"Mean">=low,]
data_temp<-data_temp[data_temp$"Mean"<=high,]
symbol_vals<-rownames(data_temp)
data<-data[which(data$"Symbol"%in%symbol_vals),]
data_transform<-reshape2::melt(data,"Symbol")
data_transform<-merge(data_transform,meta,by.x="variable",by.y="Sample_ID")
temp_df_mean <-stats::aggregate(.~ Condition+Symbol, data_transform, mean, na.rm = TRUE)
df<-data_transform
df_mean <- dplyr::group_by(df, Condition)
df_mean <-dplyr::ungroup(dplyr::summarize(df_mean, average = mean(value)))
Condition<-df[,"Condition"]
value<-df$"value"
Condition_mean<-as.data.frame(df_mean)[,"Condition"]
average<-df_mean$"average"
p<- ggplot2::ggplot(df, ggplot2::aes(Condition,value, fill=Condition)) +ggplot2::geom_violin(trim=FALSE, alpha=0.5)+ggplot2::geom_point(data = df_mean, mapping = ggplot2::aes(x = Condition_mean, y = average),color="red") +ggplot2::geom_line(data = df_mean, mapping = aes(x = Condition_mean, y = average,group=1))+viridis::scale_fill_viridis(discrete = TRUE)
methods::show(p)
qual_col_pals <- RColorBrewer::brewer.pal.info[which(RColorBrewer::brewer.pal.info$"category"%in%c('qual')),]
col_vector <- unlist(mapply(RColorBrewer::brewer.pal, qual_col_pals$"maxcolors", rownames(qual_col_pals)))
colors <- col_vector[1:nlevels(as.factor(data$"Symbol"))]
plot_ly(data = temp_df_mean, x = ~Condition, y = ~value, color = ~Symbol, colors = colors, type="bar")
} |
panel_st <- function(data, agg = data$config$st$aggregation$active,
agg_met = data$config$st$aggregation$method) {
if (agg) {
if (agg_met == "static") {
panel <- panel_st_agg_static(data)
} else if (agg_met == "dynamic") {
panel <- panel_st_agg_dynamic(data)
} else if (agg_met == "nodes") {
panel <- panel_st_agg_node(data)
}
} else {
panel <- panel_st_raw(data = data, runtime = FALSE)
}
return(panel)
}
panel_st_runtime <- function(data,
agg = data$config$starpu$aggregation$active) {
if (agg) {
panel <- panel_st_agg_static(data, runtime = TRUE, step = data$config$starpu$aggregation$step)
} else {
panel <- panel_st_raw(data = data, runtime = TRUE)
}
return(panel)
}
panel_st_raw <- function(data = NULL, ST.Outliers = data$config$st$outliers, base_size = data$config$base_size,
expand_x = data$config$expand, expand_y = data$config$st$expand, selected_nodes = data$config$selected_nodes,
labels = data$config$st$labels, alpha = data$config$st$alpha, idleness = data$config$st$idleness,
taskdeps = data$config$st$tasks$active, tasklist = data$config$st$tasks$list, levels = data$config$st$tasks$levels,
makespan = data$config$st$makespan, abe = data$config$st$abe$active, pmtoolbounds = data$config$pmtool$bounds$active,
cpb = data$config$st$cpb, cpb_mpi = data$config$st$cpb_mpi$active, legend = data$config$st$legend,
x_start = data$config$limits$start,
x_end = data$config$limits$end, runtime = FALSE) {
if (is.null(data)) stop("data provided to state_chart is NULL")
if (is.null(expand_x) || !is.numeric(expand_x)) {
expand_x <- 0.05
}
if (is.null(x_start) || (!is.na(x_start) && !is.numeric(x_start))) {
x_start <- NA
}
if (is.null(x_end) || (!is.na(x_end) && !is.numeric(x_end))) {
x_end <- NA
}
if (is.null(legend) || !is.logical(legend)) {
legend <- TRUE
}
gow <- ggplot() +
default_theme(base_size, expand_x)
App <- data$Application
if (!is.null(selected_nodes)) {
data$Y %>%
separate(.data$Parent, into = c("Node"), remove = FALSE, extra = "drop", fill = "right") %>%
filter(.data$Node %in% selected_nodes) %>%
arrange(.data$Position) %>%
mutate(New = cumsum(lag(.data$Height, default = 0))) %>%
select(.data$Parent, .data$New) -> new_y
if (runtime) {
data$Starpu <- data$Starpu %>%
left_join(new_y, by = c("ResourceId" = "Parent")) %>%
mutate(Position = if_else(is.na(.data$New), -3, .data$New)) %>%
select(-.data$New)
} else {
data$Application <- data$Application %>%
left_join(new_y, by = c("ResourceId" = "Parent")) %>%
mutate(Position = if_else(is.na(.data$New), -3, .data$New)) %>%
mutate(Height = if_else(is.na(.data$New), 0, .data$Height)) %>%
select(-.data$New)
App <- data$Application %>%
filter(.data$Position >= 0)
}
}
if (runtime) {
gow <- gow + geom_states(data$Starpu,
ST.Outliers, runtime, data$Colors,
labels = labels,
expand = expand_y,
rect_outline = data$config$st$rect_outline,
alpha_value = alpha, Y = data$Y
)
} else {
gow <- gow + geom_states(App,
ST.Outliers, runtime, data$Colors,
labels = labels,
expand = expand_y,
rect_outline = data$config$st$rect_outline,
alpha_value = alpha, Y = data$Y
)
}
if (!runtime) {
if (idleness) gow <- gow + geom_idleness(data)
if (taskdeps) {
if(!is.null(data$Last)){
tasksel <- last(data, tasklist)
}else{
tasksel <- gaps_backward_deps(
data = data,
tasks = tasklist,
levels = levels
)
}
if (nrow(tasksel) > 0 & !is.null(selected_nodes)) {
tasksel <- tasksel %>%
left_join(new_y, by = c("ResourceId" = "Parent")) %>%
mutate(Position = if_else(is.na(.data$New), -3, .data$New)) %>%
select(-.data$New)
}
gow <- gow + geom_path_highlight(tasksel)
}
if (cpb || cpb_mpi) gow <- gow + geom_cpb(data)
if (abe) gow <- gow + geom_abe(data)
if (pmtoolbounds) gow <- gow + geom_pmtool_bounds(data)
if (makespan) gow <- gow + geom_makespan(App, bsize = base_size)
}
if (!legend) {
gow <- gow + theme(legend.position = "none")
}
gow <- gow +
coord_cartesian(xlim = c(x_start, x_end), ylim = c(0, NA))
return(gow)
}
geom_states <- function(dfw = NULL, Show.Outliers = FALSE, StarPU = FALSE, Colors = NULL,
labels = "1",
expand = 0.05,
rect_outline = FALSE,
alpha_value = 0.5,
Y = NULL) {
if (is.null(dfw)) stop("data is NULL when given to geom_states")
if (is.null(Colors)) stop("data is NULL when given to geom_states")
ret <- list()
if (StarPU) {
ret[[length(ret) + 1]] <- scale_fill_manual(values = starpu_colors())
} else {
ret[[length(ret) + 1]] <- scale_fill_manual(values = extract_colors(dfw, Colors))
}
yconfm <- yconf(dfw, labels, Y)
ret[[length(ret) + 1]] <- scale_y_continuous(
breaks = yconfm$Position + (yconfm$Height / 3), labels = unique(as.character(yconfm$ResourceId)),
expand = c(expand, 0)
)
ret[[length(ret) + 1]] <- ylab(ifelse(StarPU, "StarPU Workers", "Application Workers"))
ret[[length(ret) + 1]] <-
geom_rect(
data = dfw, aes(
fill = .data$Value,
xmin = .data$Start,
xmax = .data$End,
ymin = .data$Position,
ymax = .data$Position + .data$Height - 0.2
),
color = ifelse(rect_outline, "black", NA),
alpha = ifelse(Show.Outliers && !StarPU, alpha_value, 1.0)
)
if (Show.Outliers && !StarPU) {
ret[[length(ret) + 1]] <-
geom_rect(
data = (dfw %>% filter(.data$Outlier == TRUE)),
aes(
fill = .data$Value,
xmin = .data$Start,
xmax = .data$End,
ymin = .data$Position,
ymax = .data$Position + .data$Height - 0.2
),
color = ifelse(rect_outline, "black", NA),
alpha = 1
)
}
return(ret)
}
geom_path_highlight <- function(paths = NULL) {
if (is.null(paths)) return(list())
if ((paths %>% nrow()) == 0) {
return(list())
}
ret <- list()
ret[[length(ret) + 1]] <- geom_rect(
data = paths,
size = 1,
aes(
color = .data$Path,
xmin = .data$Start,
xmax = .data$End,
ymin = .data$Position,
ymax = .data$Position + .data$Height - 0.2
), alpha = 0
)
paths %>%
select(.data$JobId, .data$Start, .data$End, .data$Position, .data$Height) %>%
unique() -> x1
paths %>%
select(.data$Path, .data$JobId, .data$Dependent) %>%
left_join(x1, by = c("JobId" = "JobId")) %>%
left_join(x1, by = c("Dependent" = "JobId")) %>%
na.omit() -> pathlines
ret[[length(ret) + 1]] <- geom_segment(
data = pathlines,
aes(
x = .data$Start.x,
xend = .data$End.y,
y = .data$Position.x + (.data$Height.x / 2),
yend = .data$Position.y + (.data$Height.y / 2),
color = .data$Path
)
)
return(ret)
}
panel_st_agg_node <- function(data,
x_start = data$config$limits$start,
x_end = data$config$limits$end,
step = data$config$st$aggregation$step,
legend = data$config$st$legend) {
if (is.null(step) || !is.numeric(step)) {
if (is.null(data$config$global_agg_step)) {
agg_step <- 100
} else {
agg_step <- data$config$global_agg_step
}
} else {
agg_step <- step
}
if (is.null(x_start) || (!is.na(x_start) && !is.numeric(x_start))) {
x_start <- NA
}
if (is.null(x_end) || (!is.na(x_end) && !is.numeric(x_end))) {
x_end <- NA
}
if (is.null(legend) || !is.logical(legend)) {
legend <- TRUE
}
step <- 100
df <- time_aggregation_prep(data$Application)
df <- time_aggregation_do(df %>%
group_by(.data$Node, .data$ResourceId, .data$ResourceType, .data$Task), step)
df.spatial <- node_spatial_aggregation(df)
space.within <- 0.01
space.between <- 0.0
space <- space.between
df.spatial %>%
mutate(Node = as.integer(as.character(.data$Node))) %>%
select(.data$Node, .data$ResourceType) %>%
unique() %>%
mutate(ResourceType.Height = 1) %>%
arrange(-.data$Node, desc(.data$ResourceType)) %>%
mutate(ResourceType.Position = cumsum(lag(.data$ResourceType.Height, default = 0) + space) - space) %>%
as.data.frame() -> df.node_position
df.spatial %>%
mutate(Start = .data$Slice, End = .data$Start + .data$Duration) %>%
mutate(Node = as.integer(as.character(.data$Node))) %>%
left_join(df.node_position, by = c("Node", "ResourceType")) %>%
group_by(.data$Node, .data$ResourceType, .data$Slice) %>%
arrange(-.data$Node) %>%
mutate(Position = .data$ResourceType.Position + cumsum(.data$Activity) - .data$Activity) %>%
mutate(Height = 1) %>%
ungroup() -> df.spatial_prep
hl_per_node_ABE(data$Application) %>%
mutate(Node = as.integer(as.character(.data$Node))) %>%
select(-.data$MinPosition, -.data$MaxPosition) %>%
left_join(df.node_position %>% select(.data$Node, .data$ResourceType.Position, .data$ResourceType.Height) %>% unique(), by = c("Node")) %>%
select(.data$Node, .data$Result, .data$ResourceType.Position, .data$ResourceType.Height) %>%
arrange(-.data$Node) %>%
group_by(.data$Node, .data$Result) %>%
summarize(
Node.Position = min(.data$ResourceType.Position),
Node.Height = sum(.data$ResourceType.Height)
) %>%
ungroup() %>%
mutate(MinPosition = .data$Node.Position) %>%
mutate(MaxPosition = .data$Node.Position + .data$Node.Height + space.between) -> df.pernodeABE
df.node_position %>%
group_by(.data$Node, .data$ResourceType) %>%
summarize(Node.Position = min(.data$ResourceType.Position) + sum(.data$ResourceType.Height) - 0.5) %>%
mutate(Label = paste(.data$ResourceType, .data$Node)) -> yconf
new_state_plot <- df.spatial_prep %>%
ggplot() +
default_theme(data$config$base_size, data$config$expand) +
xlab("Time [ms]") +
scale_fill_manual(values = extract_colors(df.spatial_prep %>% rename(Value = .data$Task), data$Colors)) +
scale_y_continuous(
breaks = yconf$Node.Position,
labels = yconf$Label, expand = c(data$config$expand, 0)
) +
ylab("Node Occupation") +
geom_rect(aes(
fill = .data$Task,
xmin = .data$Start,
xmax = .data$End,
ymin = .data$Position,
ymax = .data$Position + .data$Activity
), alpha = .5)
if (data$config$st$makespan) new_state_plot <- new_state_plot + geom_makespan(df.spatial_prep, bsize = data$config$base_size)
if (data$config$st$abe$active) {
new_state_plot <- new_state_plot +
geom_abe_internal(df.pernodeABE,
base_size = data$config$base_size,
abesize = data$config$st$abe$size,
bar_color = data$config$st$abe$bar_color,
text = data$config$st$abe$text,
label = data$config$st$abe$label
)
}
if (data$config$st$cpb || data$config$st$cpb_mpi$active) {
cpbs <- hl_global_cpb(data)
}
if (data$config$st$cpb) {
new_state_plot <- new_state_plot + geom_cpb_internal(df.spatial_prep, cpbs$CPB, "CPB:", bsize = data$config$base_size)
}
if (data$config$st$cpb_mpi$active) {
if (is.na(data$config$st$cpb_mpi$tile_size)) {
starvz_warn("CPB_MPI is active and st$cpb_mpi$tile_size is NULL")
}
if (is.na(data$config$st$cpb_mpi$bandwidth)) {
starvz_warn("CPB_MPI is active and st$cpb_mpi$bandwidth is NULL")
}
tile_size <- data$config$st$cpb_mpi$tile_size
bandwidth <- data$config$st$cpb_mpi$bandwidth
cpbmpit <- cpbs$CPB + cpbs$NMPI * (tile_size * tile_size * 8) / bandwidth / 1000000
new_state_plot <- new_state_plot + geom_cpb_internal(df.spatial_prep, cpbs$CPBMPI, "CPB-MPI:", bsize = data$config$base_size)
if (data$config$st$cpb_mpi$theoretical) {
new_state_plot <- new_state_plot + geom_cpb_internal(df.spatial_prep, cpbmpit, "CPB-MPI*:", bsize = data$config$base_size)
}
}
new_state_plot <- new_state_plot +
coord_cartesian(xlim = c(x_start, x_end), ylim = c(0, NA)) +
guides(fill = guide_legend(nrow = 2))
if (!legend) {
new_state_plot <- new_state_plot + theme(legend.position = "none")
}
return(new_state_plot)
} |
unselectCurrentCluster<-function
(
df,
dbg=FALSE
) {
if (dbg) cat('unselectCurrentCluster called\n')
if (dbg) printVar(df$currentCluster)
if (!is.null(df$clusters) && length(df$clusters)>=df$currentCluster
&& !is.null(df$clusters[[df$currentCluster]]$indices)) {
df<-pushSelectionHistory(df,dbg)
currentClusterIdxInH<-max(df$clusters[[df$currentCluster]]$indices)
currentClusterLeafs<-computeMemberIndices(df$h,currentClusterIdxInH)
df$leafColorIdxs[currentClusterLeafs]<-0
df$unselectedBranches$indices<-
c(df$unselectedBranches$indices,df$clusters[[df$currentCluster]]$indices)
df$unselectedBranches$branches<-
rbind(df$unselectedBranches$branches,df$clusters[[df$currentCluster]]$branches)
df$clusters[[df$currentCluster]]$indices<-NULL
df$clusters[[df$currentCluster]]$branches<-NULL
selectionChanged<-TRUE
} else {
selectionChanged<-FALSE
}
return(list(df=df,selectionChanged=selectionChanged))
} |
head(APMultipleChoice)
answer <- c(85, 90, 79, 78, 68)
chisq.test(answer) |
STF = function(sp, time, endTime = delta(time)) {
new("STF", ST(sp, time, endTime))
}
STFDF = function(sp, time, data, endTime = delta(time)) {
new("STFDF", STF(sp, time, endTime), data = data)
}
myCoordinates = function(x) {
stopifnot(is(x, "Spatial"))
if (is(x, "SpatialLines"))
do.call(rbind, lapply(coordinates(x), function(x) x[[1]][1,]))
else
coordinates(x)
}
setMethod("coordinates", "STF", function(obj) {
mc = myCoordinates(obj@sp)
m = matrix(apply(mc, 2, rep, nrow(obj@time)), ncol = ncol(mc))
dimnames(m)[[2]] = coordnames(obj@sp)
m
})
index.STF = function(x, ...) {
rep(index(x@time), each = length(x@sp))
}
index.STFDF = index.STF
as.data.frame.STF = function(x, row.names = NULL, ...) {
if (is.null(row.names(x@sp)))
row.names(x@sp) = 1:nrow(x@sp)
timedata = apply(x@time, 2, rep, each = length(x@sp))
ret = data.frame(as.data.frame(coordinates(x)),
sp.ID = rep(factor(row.names(x@sp), levels = row.names(x@sp)),
nrow(x@time)),
time = index(x),
endTime = rep(x@endTime, each= length(x@sp)),
timedata,
row.names = row.names, ...)
if ("data" %in% slotNames(x@sp)) {
x = apply(x@sp@data, 2, rep, nrow(x@time))
row.names(x) = NULL
data.frame(ret, x)
} else
ret
}
setAs("STF", "data.frame", function(from) as.data.frame.STF(from))
as.data.frame.STFDF = function(x, row.names = NULL, ...) {
f = as.data.frame(as(x, "STF"))
data.frame(f, x@data, row.names = row.names, ...)
}
setAs("STFDF", "data.frame", function(from) as.data.frame.STFDF(from))
unstack.STFDF = function(x, form, which = 1,...) {
if(missing(form))
form = as.formula(paste(names(x@data)[which], "sp.ID", sep = "~"))
ret = unstack(as(x, "data.frame"), form, ...)
rownames(ret) = make.unique(as.character(index(x@time)))
ret
}
as.STFDF.xts = function(from) {
nc = seq_along(from@data)
ret = do.call(cbind, lapply(nc,
function(i) {
ix = index(from@time)
if (is(ix, "Date"))
xts(unstack(from[,,i, drop = FALSE]), ix)
else
xts(unstack(from[,,i, drop = FALSE]), ix, tzone = tzone(from@time))
}
)
)
if (length(nc) > 1)
names(ret) = as.vector(t(outer(names(from@data), row.names(from@sp), paste, sep = ".")))
else
names(ret) = row.names(from@sp)
ret
}
setAs("STFDF", "xts", as.STFDF.xts)
as.zoo.STFDF = function(x,...) as.zoo(as(x, "xts"))
setAs("STFDF", "zoo", function(from) as.zoo.STFDF(from))
as.array.STFDF = function(x, ...) {
a = array(NA, dim(x))
for (i in 1:dim(x)[3])
a[,,i] = t(as(x[,, i, drop = FALSE], "xts"))
dimnames(a) = list(NULL, make.names(index(x@time)), names(x@data))
a
}
subs.STF_and_STFDF <- function(x, i, j, ... , drop = is(x, "STFDF")) {
nr = dim(x)[1]
nc = dim(x)[2]
n.args = nargs()
dots = list(...)
missing.i = missing(i)
missing.j = missing(j)
if (length(dots) > 0) {
missing.k = FALSE
k = dots[[1]]
} else
missing.k = TRUE
if (missing.i && missing.j && missing.k)
return(x)
if (!missing.k && is(x, "STFDF")) {
x@data = x@data[ , k, drop = FALSE]
if (missing.j && n.args == 2)
return(x)
}
if (!missing.i && is(i, "STF")) {
j = which(!is.na(timeMatch(x,i)))
i = which(!is.na(over(x@sp, geometry(i@sp))))
missing.j = FALSE
}
matrix.i <- FALSE
if (!is.character(row.names(x@sp)))
row.names(x@sp) <- as.character(row.names(x@sp))
if (missing.i)
s = 1:length(x@sp)
else {
if (is.matrix(i)) {
stopifnot(ncol(i)==2)
s <- unique(i[,1])
missing.j <- FALSE
matrix.i <- TRUE
} else {
if (is(i, "Spatial")) {
s = which(!is.na(over(x@sp, geometry(i))))
} else if (is.logical(i)) {
i = rep(i, length.out = length(x@sp))
s = which(i)
} else if (is.character(i)) {
s = match(i, row.names(x@sp), nomatch = FALSE)
} else
s = i
x@sp = x@sp[s,]
}
}
if (missing.j)
t = 1:nrow(x@time)
else {
if (matrix.i)
t <- unique(i[,2])
else {
if (is.logical(j))
j = which(j)
nct = ncol(x@time)
x@time = cbind(x@time, 1:nrow(x@time))
x@time = x@time[j]
t = as.vector(x@time[, nct+1])
x@time = x@time[,-(nct+1)]
x@endTime = x@endTime[t]
}
}
if (matrix.i) {
ind <- i[order(i[,2]),]
ind[,1] <- match(ind[,1], s)
ind[,2] <- match(ind[,2], t)
reOrder <- numeric(nrow(ind))
for (ts in unique(ind[,2])) {
selRow <- which(ind[,2] == ts)
reOrder[selRow] <- selRow[order(ind[selRow,1])]
}
ind[,1] <- ind[reOrder,1]
if (is(x, "STFDF")) {
sel <- (i[,2]-1)*nr+i[,1]
x <- STSDF(x@sp[s,], x@time[t,], x@data[sel,,drop=FALSE], ind, x@endTime[t])
} else
x <- STS(x@sp[s,], x@time[t,], ind, x@endTime[t])
} else if (is(x, "STFDF")) {
df = x@data
x@data = data.frame(lapply(x@data, function(v) as.vector(matrix(v, nr, nc)[s,t])))
for (i in which(sapply(df, is.factor)))
x@data[,i] = factor(x@data[,i], levels = levels(df[,i]))
}
if (drop) {
if (length(s) == 1 && all(s > 0)) {
if (length(t) == 1)
x = x@data[1,]
else {
ix = index(x@time)
xs = cbind(x@data, as.data.frame(x@time))
if (is(ix, "Date"))
x = xts(xs, ix)
else
x = xts(xs, ix, tzone = tzone(x@time))
}
} else {
if (length(t) == 1) {
if(is(x, "STFDF"))
x = addAttrToGeom(x@sp, x@data, match.ID = FALSE)
else
x = x@sp
}
}
}
x
}
setMethod("[", "STFDF", subs.STF_and_STFDF)
setMethod("[", "STF", subs.STF_and_STFDF)
na.omit.STFDF <- function(object, drop=TRUE, ...){
data <- na.omit(object@data)
omit <- attr(data, "na.action")
n <- length(object@sp)
s <- unique((omit-1) %% n + 1)
t <- unique((omit-1) %/% n + 1)
if (drop && (length(s)==n || length(t)==nrow(object@time)))
return(NA)
else
return(object[(1:n)[!(1:n) %in% s],
(1:nrow(object@time))[!1:nrow(object@time) %in% t],
drop=drop])
}
setMethod("addAttrToGeom", signature(x = "STF", y = "data.frame"),
function(x, y, match.ID, ...)
new("STFDF", x, data = y)
)
length.STF = function(x) { prod(dim(x)[1:2]) }
length.STFDF = function(x) { prod(dim(x)[1:2]) }
setMethod("geometry", "STFDF", function(obj) as(obj, "STF"))
nbMult = function(nb, st, addT = TRUE, addST = FALSE) {
stopifnot(is(st, "STF"))
stopifnot(is(nb, "nb"))
stopifnot(length(nb) == length(st@sp))
n = dim(st)[2]
if (n <= 1)
return(nb)
L = length(nb)
ret = list()
FN = function(x,i,j,L) {
ret = as.integer(x + i * L)
if (addT) {
if (addST)
now = c(ret, j + i * L)
else
now = j + i * L
if (i > 0)
ret = c(ret, now - L)
if (i < (n-1))
ret = c(ret, now + L)
}
sort(ret)
}
for (i in 0:(n-1)) {
app = lapply(1:L, function(j) FN(nb[[j]], i, j, L))
ret = append(ret, app)
}
attributes(ret) = attributes(nb)
attr(ret, "region.id") = as.character(1:length(ret))
ret
} |
converged <- function(fit, step="init step", stop=FALSE){
if (fit$convergence==1) {
ret <- FALSE
if (stop) stop(paste("iteration limit 'maxit' have been reached in", step, sep=" "))
}
else if (fit$convergence==10) {
ret <- FALSE
if (stop) stop(paste("Degenerancy of Nelder_Mead simplex", step, sep=" "))
} else {
ret <- TRUE
}
ret
} |
context("checkEnvironment")
test_that("checkEnvironment", {
myobj = new.env()
expect_succ_all(Environment, myobj)
myobj = list()
expect_fail_all(Environment, myobj)
ee = new.env(parent = emptyenv())
ee$yyy = 1
ee$zzz = 1
expect_false(testEnvironment(NULL))
expect_false(testEnvironment(list()))
expect_true(testEnvironment(ee))
expect_false(testEnvironment(ee, contains = "xxx"))
expect_true(testEnvironment(ee, contains = "yyy"))
expect_true(testEnvironment(ee, contains = c("yyy", "zzz")))
expect_error(assertEnvironment(list()), "environment")
expect_error(assertEnvironment(ee, "xxx"), "with name")
expect_error(assertEnvironment(letters), "character")
}) |
context("Test of tdcc()")
test_that("Result is correct", {
temp <- rbind(1:20,
c(1,3,2,4,16,10,19,12,18,17,
20,5,14,7,8,11,6,15,9,13))
res <- tdcc(temp, pearson = TRUE)["pearson"]
expect_equal(res, 0.730271, tolerance = 1e-7, check.attributes = FALSE)
}) |
forest.default <- function(x, vi, sei, ci.lb, ci.ub,
annotate=TRUE, showweights=FALSE, header=FALSE,
xlim, alim, olim, ylim, at, steps=5, level=95, refline=0, digits=2L, width,
xlab, slab, ilab, ilab.xpos, ilab.pos, order, subset,
transf, atransf, targs, rows,
efac=1, pch, psize, plim=c(0.5,1.5), col,
lty, fonts, cex, cex.lab, cex.axis, ...) {
mstyle <- .get.mstyle("crayon" %in% .packages())
na.act <- getOption("na.action")
if (!is.element(na.act, c("na.omit", "na.exclude", "na.fail", "na.pass")))
stop(mstyle$stop("Unknown 'na.action' specified under options()."))
if (missing(transf))
transf <- FALSE
if (missing(atransf))
atransf <- FALSE
transf.char <- deparse(transf)
atransf.char <- deparse(atransf)
if (is.function(transf) && is.function(atransf))
stop(mstyle$stop("Use either 'transf' or 'atransf' to specify a transformation (not both)."))
yi <- x
if (missing(targs))
targs <- NULL
if (missing(at))
at <- NULL
if (missing(ilab))
ilab <- NULL
if (missing(ilab.xpos))
ilab.xpos <- NULL
if (missing(ilab.pos))
ilab.pos <- NULL
if (missing(subset))
subset <- NULL
if (missing(order))
order <- NULL
if (missing(pch))
pch <- 15
if (missing(psize))
psize <- NULL
if (missing(col))
col <- NULL
if (missing(cex))
cex <- NULL
if (missing(cex.lab))
cex.lab <- NULL
if (missing(cex.axis))
cex.axis <- NULL
level <- .level(level)
if (length(digits) == 1L)
digits <- c(digits,digits)
ddd <- list(...)
if (missing(lty)) {
lty <- c("solid", "solid")
} else {
if (length(lty) == 1L)
lty <- c(lty, "solid")
}
if (length(efac) == 1L)
efac <- rep(efac, 2L)
if (is.null(ddd$annosym)) {
annosym <- c(" [", ", ", "]", "-")
} else {
annosym <- ddd$annosym
if (length(annosym) == 3L)
annosym <- c(annosym, "-")
if (length(annosym) != 4L)
stop(mstyle$stop("Argument 'annosym' must be a vector of length 3 (or 4)."))
}
if (is.null(attr(yi, "measure"))) {
measure <- "GEN"
} else {
measure <- attr(yi, "measure")
}
estlab <- .setlab(measure, transf.char, atransf.char, gentype=3, short=TRUE)
if (is.expression(estlab)) {
header.right <- str2lang(paste0("bold(", estlab, " * '", annosym[1], "' * '", 100*(1-level), "% CI'", " * '", annosym[3], "')"))
} else {
header.right <- paste0(estlab, annosym[1], 100*(1-level), "% CI", annosym[3])
}
if (is.logical(header)) {
if (header) {
header.left <- "Study"
} else {
header.left <- NULL
header.right <- NULL
}
} else {
if (!is.character(header))
stop(mstyle$stop("Argument 'header' must either be a logical or character vector."))
if (length(header) == 1L) {
header.left <- header
} else {
header.left <- header[1]
header.right <- header[2]
}
}
if (!annotate)
header.right <- NULL
if (is.null(ddd$decreasing)) {
decreasing <- FALSE
} else {
decreasing <- ddd$decreasing
}
if (!is.null(ddd$clim))
olim <- ddd$clim
if (is.null(ddd$rowadj)) {
rowadj <- rep(0,3)
} else {
rowadj <- ddd$rowadj
if (length(rowadj) == 1L)
rowadj <- c(rowadj,rowadj,0)
if (length(rowadj) == 2L)
rowadj <- c(rowadj,0)
}
if (is.null(ddd$top)) {
top <- 3
} else {
top <- ddd$top
}
lplot <- function(..., textpos, decreasing, clim, rowadj, annosym, top) plot(...)
labline <- function(..., textpos, decreasing, clim, rowadj, annosym, top) abline(...)
lsegments <- function(..., textpos, decreasing, clim, rowadj, annosym, top) segments(...)
laxis <- function(..., textpos, decreasing, clim, rowadj, annosym, top) axis(...)
lmtext <- function(..., textpos, decreasing, clim, rowadj, annosym, top) mtext(...)
lpolygon <- function(..., textpos, decreasing, clim, rowadj, annosym, top) polygon(...)
ltext <- function(..., textpos, decreasing, clim, rowadj, annosym, top) text(...)
lpoints <- function(..., textpos, decreasing, clim, rowadj, annosym, top) points(...)
if (!missing(vi) && is.function(vi))
stop(mstyle$stop("Cannot find variable specified for 'vi' argument."), call.=FALSE)
if (hasArg(ci.lb) && hasArg(ci.ub)) {
if (length(ci.lb) != length(ci.ub))
stop(mstyle$stop("Length of 'ci.lb' and 'ci.ub' is not the same."))
if (missing(vi) && missing(sei)) {
vi <- ((ci.ub - ci.lb) / (2*qnorm(level/2, lower.tail=FALSE)))^2
} else {
if (missing(vi))
vi <- sei^2
}
if (length(ci.lb) != length(vi))
stop(mstyle$stop("Length of 'vi' (or 'sei') does not match length of ('ci.lb', 'ci.ub') pairs."))
} else {
if (missing(vi)) {
if (missing(sei)) {
stop(mstyle$stop("Must specify either 'vi', 'sei', or ('ci.lb', 'ci.ub') pairs."))
} else {
vi <- sei^2
}
}
if (length(yi) != length(vi))
stop(mstyle$stop("Length of 'vi' (or 'sei') does not match length of 'yi'."))
ci.lb <- yi - qnorm(level/2, lower.tail=FALSE) * sqrt(vi)
ci.ub <- yi + qnorm(level/2, lower.tail=FALSE) * sqrt(vi)
}
k <- length(yi)
if (length(vi) != k)
stop(mstyle$stop("Length of 'yi' does not match the length of 'vi', 'sei', or the ('ci.lb', 'ci.ub') pairs."))
if (missing(slab)) {
if (!is.null(attr(yi, "slab")) && length(attr(yi, "slab")) == k) {
slab <- attr(yi, "slab")
} else {
slab <- paste("Study", seq_len(k))
}
} else {
if (length(slab) == 1L && is.na(slab))
slab <- rep("", k)
}
if (length(slab) != k)
stop(mstyle$stop(paste0("Length of the 'slab' argument (", length(slab), ") does not correspond to the number of outcomes (", k, ").")))
if (!is.null(ilab)) {
if (is.null(dim(ilab)))
ilab <- cbind(ilab)
if (nrow(ilab) != k)
stop(mstyle$stop(paste0("Length of the 'ilab' argument (", nrow(ilab), ") does not correspond to the number of outcomes (", k, ").")))
}
if (length(pch) == 1L)
pch <- rep(pch, k)
if (length(pch) != k)
stop(mstyle$stop(paste0("Length of the 'pch' argument (", length(pch), ") does not correspond to the number of outcomes (", k, ").")))
if (!is.null(psize)) {
if (length(psize) == 1L)
psize <- rep(psize, k)
if (length(psize) != k)
stop(mstyle$stop(paste0("Length of the 'psize' argument (", length(psize), ") does not correspond to the number of outcomes (", k, ").")))
}
if (!is.null(col)) {
if (length(col) == 1L)
col <- rep(col, k)
if (length(col) != k)
stop(mstyle$stop(paste0("Length of the 'col' argument (", length(col), ") does not correspond to the number of outcomes (", k, ").")))
} else {
col <- rep("black", k)
}
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k)
if (length(subset) != k)
stop(mstyle$stop(paste0("Length of the 'subset' argument (", length(subset), ") does not correspond to the number of outcomes (", k, ").")))
}
if (!is.null(order)) {
if (length(order) == 1L) {
order <- match.arg(order, c("obs", "yi", "prec", "vi"))
if (order == "obs" || order == "yi")
sort.vec <- order(yi)
if (order == "prec" || order == "vi")
sort.vec <- order(vi, yi)
} else {
if (length(order) != k)
stop(mstyle$stop(paste0("Length of the 'order' argument (", length(order), ") does not correspond to the number of outcomes (", k, ").")))
if (grepl("^order\\(", deparse1(substitute(order)))) {
sort.vec <- order
} else {
sort.vec <- order(order, decreasing=decreasing)
}
}
yi <- yi[sort.vec]
vi <- vi[sort.vec]
ci.lb <- ci.lb[sort.vec]
ci.ub <- ci.ub[sort.vec]
slab <- slab[sort.vec]
ilab <- ilab[sort.vec,,drop=FALSE]
pch <- pch[sort.vec]
psize <- psize[sort.vec]
col <- col[sort.vec]
subset <- subset[sort.vec]
}
if (!is.null(subset)) {
yi <- yi[subset]
vi <- vi[subset]
ci.lb <- ci.lb[subset]
ci.ub <- ci.ub[subset]
slab <- slab[subset]
ilab <- ilab[subset,,drop=FALSE]
pch <- pch[subset]
psize <- psize[subset]
col <- col[subset]
}
k <- length(yi)
if (missing(rows)) {
rows <- k:1
} else {
if (length(rows) == 1L)
rows <- rows:(rows-k+1)
}
if (length(rows) != k)
stop(mstyle$stop(paste0("Length of the 'rows' argument (", length(rows), ") does not correspond to the number of outcomes (", k, ")", ifelse(is.null(subset), ".", " after subsetting."))))
yi <- yi[k:1]
vi <- vi[k:1]
ci.lb <- ci.lb[k:1]
ci.ub <- ci.ub[k:1]
slab <- slab[k:1]
ilab <- ilab[k:1,,drop=FALSE]
pch <- pch[k:1]
psize <- psize[k:1]
col <- col[k:1]
rows <- rows[k:1]
yivi.na <- is.na(yi) | is.na(vi)
if (any(yivi.na)) {
not.na <- !yivi.na
if (na.act == "na.omit") {
yi <- yi[not.na]
vi <- vi[not.na]
ci.lb <- ci.lb[not.na]
ci.ub <- ci.ub[not.na]
slab <- slab[not.na]
ilab <- ilab[not.na,,drop=FALSE]
pch <- pch[not.na]
psize <- psize[not.na]
col <- col[not.na]
rows.new <- rows
rows.na <- rows[!not.na]
for (j in seq_len(length(rows.na))) {
rows.new[rows >= rows.na[j]] <- rows.new[rows >= rows.na[j]] - 1
}
rows <- rows.new[not.na]
}
if (na.act == "na.fail")
stop(mstyle$stop("Missing values in results."))
}
k <- length(yi)
if (is.function(transf)) {
if (is.null(targs)) {
yi <- sapply(yi, transf)
ci.lb <- sapply(ci.lb, transf)
ci.ub <- sapply(ci.ub, transf)
} else {
yi <- sapply(yi, transf, targs)
ci.lb <- sapply(ci.lb, transf, targs)
ci.ub <- sapply(ci.ub, transf, targs)
}
}
tmp <- .psort(ci.lb, ci.ub)
ci.lb <- tmp[,1]
ci.ub <- tmp[,2]
if (!missing(olim)) {
if (length(olim) != 2L)
stop(mstyle$stop("Argument 'olim' must be of length 2."))
olim <- sort(olim)
yi[yi < olim[1]] <- olim[1]
yi[yi > olim[2]] <- olim[2]
ci.lb[ci.lb < olim[1]] <- olim[1]
ci.ub[ci.ub > olim[2]] <- olim[2]
}
if (showweights) {
weights <- 1/vi
weights <- 100 * weights / sum(weights, na.rm=TRUE)
}
if (is.null(psize)) {
if (any(vi <= 0, na.rm=TRUE)) {
psize <- rep(1, k)
} else {
if (length(plim) < 2L)
stop(mstyle$stop("Argument 'plim' must be of length 2 or 3."))
wi <- 1/sqrt(vi)
if (!is.na(plim[1]) && !is.na(plim[2])) {
rng <- max(wi, na.rm=TRUE) - min(wi, na.rm=TRUE)
if (rng <= .Machine$double.eps^0.5) {
psize <- rep(1, k)
} else {
psize <- (wi - min(wi, na.rm=TRUE)) / rng
psize <- (psize * (plim[2] - plim[1])) + plim[1]
}
}
if (is.na(plim[1]) && !is.na(plim[2])) {
psize <- wi / max(wi, na.rm=TRUE) * plim[2]
if (length(plim) == 3L)
psize[psize <= plim[3]] <- plim[3]
}
if (!is.na(plim[1]) && is.na(plim[2])) {
psize <- wi / min(wi, na.rm=TRUE) * plim[1]
if (length(plim) == 3L)
psize[psize >= plim[3]] <- plim[3]
}
if (all(is.na(psize)))
psize <- rep(1, k)
}
}
rng <- max(ci.ub, na.rm=TRUE) - min(ci.lb, na.rm=TRUE)
if (annotate) {
if (showweights) {
plot.multp.l <- 2.00
plot.multp.r <- 2.00
} else {
plot.multp.l <- 1.20
plot.multp.r <- 1.20
}
} else {
plot.multp.l <- 1.20
plot.multp.r <- 0.40
}
if (missing(xlim)) {
xlim <- c(min(ci.lb, na.rm=TRUE) - rng * plot.multp.l, max(ci.ub, na.rm=TRUE) + rng * plot.multp.r)
xlim <- round(xlim, digits[[2]])
}
alim.spec <- TRUE
if (missing(alim)) {
if (is.null(at)) {
alim <- range(pretty(x=c(min(ci.lb, na.rm=TRUE), max(ci.ub, na.rm=TRUE)), n=steps-1))
alim.spec <- FALSE
} else {
alim <- range(at)
}
}
alim <- sort(alim)
xlim <- sort(xlim)
if (xlim[1] > min(yi, na.rm=TRUE)) { xlim[1] <- min(yi, na.rm=TRUE) }
if (xlim[2] < max(yi, na.rm=TRUE)) { xlim[2] <- max(yi, na.rm=TRUE) }
if (alim[1] < xlim[1]) { xlim[1] <- alim[1] }
if (alim[2] > xlim[2]) { xlim[2] <- alim[2] }
if (is.null(ddd$textpos)) {
textpos <- xlim
} else {
textpos <- ddd$textpos
}
if (length(textpos) != 2L)
stop(mstyle$stop("Argument 'textpos' must be of length 2."))
if (is.na(textpos[1]))
textpos[1] <- xlim[1]
if (is.na(textpos[2]))
textpos[2] <- xlim[2]
if (missing(ylim)) {
ylim <- c(0.5, max(rows, na.rm=TRUE)+top)
} else {
ylim <- sort(ylim)
}
if (is.null(at)) {
if (alim.spec) {
at <- seq(from=alim[1], to=alim[2], length.out=steps)
} else {
at <- pretty(x=c(min(ci.lb, na.rm=TRUE), max(ci.ub, na.rm=TRUE)), n=steps-1)
}
} else {
at[at < alim[1]] <- alim[1]
at[at > alim[2]] <- alim[2]
at <- unique(at)
}
at.lab <- at
if (is.function(atransf)) {
if (is.null(targs)) {
at.lab <- formatC(sapply(at.lab, atransf), digits=digits[[2]], format="f", drop0trailing=is.integer(digits[[2]]))
} else {
at.lab <- formatC(sapply(at.lab, atransf, targs), digits=digits[[2]], format="f", drop0trailing=is.integer(digits[[2]]))
}
} else {
at.lab <- formatC(at.lab, digits=digits[[2]], format="f", drop0trailing=is.integer(digits[[2]]))
}
if (missing(fonts)) {
fonts <- rep(par("family"), 3L)
} else {
if (length(fonts) == 1L)
fonts <- rep(fonts, 3L)
if (length(fonts) == 2L)
fonts <- c(fonts, fonts[1])
}
if (is.null(names(fonts)))
fonts <- setNames(c(1L,1L,1L), nm=fonts)
par(family=names(fonts)[1], font=fonts[1])
par.mar <- par("mar")
par.mar.adj <- par.mar - c(0,3,1,1)
par.mar.adj[par.mar.adj < 0] <- 0
par(mar = par.mar.adj)
on.exit(par(mar = par.mar), add=TRUE)
lplot(NA, NA, xlim=xlim, ylim=ylim, xlab="", ylab="", yaxt="n", xaxt="n", xaxs="i", bty="n", col="black", ...)
labline(h=ylim[2]-(top-1), lty=lty[2], col="black", ...)
par.usr <- par("usr")
if (is.numeric(refline))
lsegments(refline, par.usr[3], refline, ylim[2]-(top-1), lty="dotted", col="black", ...)
height <- par.usr[4] - par.usr[3]
if (is.null(cex)) {
lheight <- strheight("O")
cex.adj <- ifelse(k * lheight > height * 0.8, height/(1.25 * k * lheight), 1)
}
if (is.null(cex)) {
cex <- par("cex") * cex.adj
} else {
if (is.null(cex.lab))
cex.lab <- cex
if (is.null(cex.axis))
cex.axis <- cex
}
if (is.null(cex.lab))
cex.lab <- par("cex") * cex.adj
if (is.null(cex.axis))
cex.axis <- par("cex") * cex.adj
laxis(side=1, at=at, labels=at.lab, cex.axis=cex.axis, col="black", ...)
if (missing(xlab))
xlab <- .setlab(measure, transf.char, atransf.char, gentype=1)
lmtext(xlab, side=1, at=min(at) + (max(at)-min(at))/2, line=par("mgp")[1]-0.5, cex=cex.lab, col="black", ...)
for (i in seq_len(k)) {
if (is.na(yi[i]) || is.na(ci.lb[i]) || is.na(ci.ub[i]))
next
if (ci.lb[i] >= alim[2]) {
lpolygon(x=c(alim[2], alim[2]-(1.4/100)*cex*(xlim[2]-xlim[1]), alim[2]-(1.4/100)*cex*(xlim[2]-xlim[1]), alim[2]), y=c(rows[i], rows[i]+(height/150)*cex*efac[2], rows[i]-(height/150)*cex*efac[2], rows[i]), col=col[i], border=col[i], ...)
next
}
if (ci.ub[i] <= alim[1]) {
lpolygon(x=c(alim[1], alim[1]+(1.4/100)*cex*(xlim[2]-xlim[1]), alim[1]+(1.4/100)*cex*(xlim[2]-xlim[1]), alim[1]), y=c(rows[i], rows[i]+(height/150)*cex*efac[2], rows[i]-(height/150)*cex*efac[2], rows[i]), col=col[i], border=col[i], ...)
next
}
lsegments(max(ci.lb[i], alim[1]), rows[i], min(ci.ub[i], alim[2]), rows[i], lty=lty[1], col=col[i], ...)
if (ci.lb[i] >= alim[1]) {
lsegments(ci.lb[i], rows[i]-(height/150)*cex*efac[1], ci.lb[i], rows[i]+(height/150)*cex*efac[1], col=col[i], ...)
} else {
lpolygon(x=c(alim[1], alim[1]+(1.4/100)*cex*(xlim[2]-xlim[1]), alim[1]+(1.4/100)*cex*(xlim[2]-xlim[1]), alim[1]), y=c(rows[i], rows[i]+(height/150)*cex*efac[2], rows[i]-(height/150)*cex*efac[2], rows[i]), col=col[i], border=col[i], ...)
}
if (ci.ub[i] <= alim[2]) {
lsegments(ci.ub[i], rows[i]-(height/150)*cex*efac[1], ci.ub[i], rows[i]+(height/150)*cex*efac[1], col=col[i], ...)
} else {
lpolygon(x=c(alim[2], alim[2]-(1.4/100)*cex*(xlim[2]-xlim[1]), alim[2]-(1.4/100)*cex*(xlim[2]-xlim[1]), alim[2]), y=c(rows[i], rows[i]+(height/150)*cex*efac[2], rows[i]-(height/150)*cex*efac[2], rows[i]), col=col[i], border=col[i], ...)
}
}
ltext(textpos[1], rows+rowadj[1], slab, pos=4, cex=cex, col=col, ...)
if (!is.null(ilab)) {
if (is.null(ilab.xpos))
stop(mstyle$stop("Must specify 'ilab.xpos' argument when adding information with 'ilab'."))
if (length(ilab.xpos) != ncol(ilab))
stop(mstyle$stop(paste0("Number of 'ilab' columns (", ncol(ilab), ") does not match length of 'ilab.xpos' argument (", length(ilab.xpos), ").")))
if (!is.null(ilab.pos) && length(ilab.pos) == 1L)
ilab.pos <- rep(ilab.pos, ncol(ilab))
par(family=names(fonts)[3], font=fonts[3])
for (l in seq_len(ncol(ilab))) {
ltext(ilab.xpos[l], rows+rowadj[3], ilab[,l], pos=ilab.pos[l], cex=cex, ...)
}
par(family=names(fonts)[1], font=fonts[1])
}
if (annotate) {
if (is.function(atransf)) {
if (is.null(targs)) {
annotext <- cbind(sapply(yi, atransf), sapply(ci.lb, atransf), sapply(ci.ub, atransf))
} else {
annotext <- cbind(sapply(yi, atransf, targs), sapply(ci.lb, atransf, targs), sapply(ci.ub, atransf, targs))
}
tmp <- .psort(annotext[,2:3])
annotext[,2:3] <- tmp
} else {
annotext <- cbind(yi, ci.lb, ci.ub)
}
if (showweights)
annotext <- cbind(weights, annotext)
annotext <- .fcf(annotext, digits[[1]])
annotext <- sub("-", annosym[4], annotext, fixed=TRUE)
if (missing(width)) {
width <- apply(annotext, 2, function(x) max(nchar(x)))
} else {
if (length(width) == 1L)
width <- rep(width, ncol(annotext))
if (length(width) != ncol(annotext))
stop(mstyle$stop(paste0("Length of 'width' argument (", length(width), ") does not match the number of annotation columns (", ncol(annotext), ").")))
}
for (j in seq_len(ncol(annotext))) {
annotext[,j] <- formatC(annotext[,j], width=width[j])
}
if (showweights) {
annotext <- cbind(annotext[,1], "% ", annotext[,2], annosym[1], annotext[,3], annosym[2], annotext[,4], annosym[3])
} else {
annotext <- cbind(annotext[,1], annosym[1], annotext[,2], annosym[2], annotext[,3], annosym[3])
}
annotext <- apply(annotext, 1, paste, collapse="")
annotext[grepl("NA", annotext, fixed=TRUE)] <- ""
par(family=names(fonts)[2], font=fonts[2])
ltext(textpos[2], rows+rowadj[2], labels=annotext, pos=2, cex=cex, col=col, ...)
par(family=names(fonts)[1], font=fonts[1])
} else {
width <- NULL
}
for (i in seq_len(k)) {
if (is.na(yi[i]))
next
if (yi[i] >= alim[1] && yi[i] <= alim[2])
lpoints(x=yi[i], y=rows[i], pch=pch[i], cex=cex*psize[i], col=col[i], ...)
}
ltext(textpos[1], ylim[2]-(top-1)+1, header.left, pos=4, font=2, cex=cex, ...)
ltext(textpos[2], ylim[2]-(top-1)+1, header.right, pos=2, font=2, cex=cex, ...)
res <- list(xlim=par("usr")[1:2], alim=alim, at=at, ylim=ylim, rows=rows, cex=cex, cex.lab=cex.lab, cex.axis=cex.axis, ilab.xpos=ilab.xpos, ilab.pos=ilab.pos, textpos=textpos)
sav <- c(res, list(level=level, annotate=annotate, digits=digits[1], width=width, transf=transf, atransf=atransf, targs=targs, fonts=fonts[1:2], annosym=annosym))
try(assign("forest", sav, envir=.metafor), silent=TRUE)
invisible(res)
} |
merge_states <- function(states, weight.matrix) {
if (any(duplicated(states))) {
stop("You must provide different states.")
}
weight.matrix[, states[1]] <- rowSums(weight.matrix[, states])
weight.matrix <- weight.matrix[, -states[-1]]
invisible(weight.matrix)
} |
diameter <- function(g, dist=NULL){
if(class(g)[1]!="graphNEL"){
stop("'g' has to be a 'graphNEL' object")
}
stopifnot(.validateGraph(g))
if(is.null(dist)){
dist <- distanceMatrix(g)
}
return(max(dist))
} |
"errors.cb" <-
function(x) { ncb.od(x)$errors.cb } |
context("Test ebreg function.")
dcomplex <- function(x, n, p, a, b, log=TRUE) {
o <- -x * (log(b) + a * log(p)) + log(x <= n)
if(!log) o <- exp(o)
return(o)
}
test_that('the right things are NULL when pred is FALSE', {
n=100
p=200
r=0.5
sig2 <- 1
signal=1
beta <- rep(1, 5)
s0 <- length(beta)
d <- 1
log.f <- function(x) dcomplex(x, n, p, 0.05, 1)
g <- function(i, j) r**(abs(i - j))
R <- outer(1:p, 1:p, g)
e <- eigen(R)
sqR <- e$vectors %*% diag(sqrt(e$values)) %*% t(e$vectors)
X <- matrix(rnorm(n * p), nrow=n, ncol=p) %*% sqR
X.new <- matrix(rnorm(p), nrow=1, ncol=p) %*% sqR
y <- as.numeric(X[, 1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(n)
y.new <- as.numeric(X.new[,1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(1)
o1 <- ebreg(y, X, X.new, FALSE, alpha=.99, gam=.005, NULL, FALSE, igpar=c(0.01, 4), log.f, M=5000, sample.beta=TRUE)
expect_true( is.null(o1$ynew))
expect_true( is.null(o1$ynew.mean))
expect_true( is.null(o1$PI))
})
test_that('the right things are NULL when sample.beta is FALSE', {
n=100
p=200
r=0.5
signal=1
sig2 <- 1
beta <- rep(1, 5)
s0 <- length(beta)
d <- 1
log.f <- function(x) dcomplex(x, n, p, 0.05, 1)
g <- function(i, j) r**(abs(i - j))
R <- outer(1:p, 1:p, g)
e <- eigen(R)
sqR <- e$vectors %*% diag(sqrt(e$values)) %*% t(e$vectors)
X <- matrix(rnorm(n * p), nrow=n, ncol=p) %*% sqR
X.new <- matrix(rnorm(p), nrow=1, ncol=p) %*% sqR
y <- as.numeric(X[, 1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(n)
y.new <- as.numeric(X.new[,1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(1)
o1 <- ebreg(y, X, X.new, FALSE, alpha=.99, gam=.005, NULL, FALSE, igpar=c(0.01, 4), log.f, M=5000, pred=TRUE)
expect_true( is.null(o1$beta))
expect_true( is.null(o1$beta.mean))
expect_true( is.null(o1$CI))
})
test_that('the right things are NULL when prior is TRUE', {
n=100
p=200
r=0.5
sig2 <- 1
signal=1
beta <- rep(1, 5)
s0 <- length(beta)
d <- 1
log.f <- function(x) dcomplex(x, n, p, 0.05, 1)
g <- function(i, j) r**(abs(i - j))
R <- outer(1:p, 1:p, g)
e <- eigen(R)
sqR <- e$vectors %*% diag(sqrt(e$values)) %*% t(e$vectors)
X <- matrix(rnorm(n * p), nrow=n, ncol=p) %*% sqR
X.new <- matrix(rnorm(p), nrow=1, ncol=p) %*% sqR
y <- as.numeric(X[, 1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(n)
y.new <- as.numeric(X.new[,1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(1)
o1 <- ebreg(y, X, X.new, FALSE, alpha=.99, gam=.005, NULL, TRUE, igpar=c(0.01, 4), log.f, M=5000, pred=TRUE)
expect_true( is.null(o1$sig2))
})
test_that('returned values have the right size', {
n=100
p=200
r=0.5
M=5000
signal=1
sig2 <- 1
beta <- rep(1, 5)
s0 <- length(beta)
d <- 1
log.f <- function(x) dcomplex(x, n, p, 0.05, 1)
g <- function(i, j) r**(abs(i - j))
R <- outer(1:p, 1:p, g)
e <- eigen(R)
sqR <- e$vectors %*% diag(sqrt(e$values)) %*% t(e$vectors)
X <- matrix(rnorm(n * p), nrow=n, ncol=p) %*% sqR
X.new <- matrix(rnorm(p), nrow=1, ncol=p) %*% sqR
y <- as.numeric(X[, 1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(n)
y.new <- as.numeric(X.new[,1:s0] %*% beta[1:s0]) + sqrt(sig2) * rnorm(1)
o1 <- ebreg(y, X, X.new, FALSE, alpha=.99, gam=.005, NULL, TRUE, igpar=c(0.01, 4), log.f, M=M, pred=TRUE, sample.beta=TRUE)
expect_true(ncol(o1$beta)==p)
expect_true(nrow(o1$beta)==M)
expect_true(length(o1$beta.mean)==p)
}) |
samonCrossSummaryIM <- function(trt1,trt2, CIlevel=0.95) {
Nalpha <- trt1$Nalpha
alphaList <- trt1$alphaList
NSamples <- trt1$NSamples
n10 <- trt1$n0
n20 <- trt2$n0
TM1 <- trt1$TM[, c("alpha","IFEst","MIIFVar")]
TM2 <- trt2$TM[, c("alpha","IFEst","MIIFVar")]
TS1 <- trt1$TS[, c("alpha","Sample","IFEst","MIIFVar","mIFEst")]
TS2 <- trt2$TS[, c("alpha","Sample","IFEst","MIIFVar","mIFEst")]
colnames(TM1) <- c("alpha1","IFEst1","IFVar1")
colnames(TM2) <- c("alpha2","IFEst2","IFVar2")
colnames(TS1) <- c("alpha1","Sample","IFEst1","IFVar1","MIFEst1")
colnames(TS2) <- c("alpha2","Sample","IFEst2","IFVar2","MIFEst2")
for ( i1 in 1:Nalpha ) {
for ( i2 in 1:Nalpha ) {
alpha1 <- alphaList[i1]
alpha2 <- alphaList[i2]
TMA1 <- TM1[TM1[,"alpha1"] == alpha1,, drop=FALSE ]
TMA2 <- TM2[TM2[,"alpha2"] == alpha2,, drop=FALSE ]
TSA1 <- TS1[TS1[,"alpha1"] == alpha1,, drop=FALSE ]
TSA2 <- TS2[TS2[,"alpha2"] == alpha2,, drop=FALSE ]
TM <- cbind(TMA1,TMA2)
TM[,"Difference"] <- TM[,"IFEst2" ] - TM[,"IFEst1" ]
TM[,"DIFSE"] <- sqrt(TM[,"IFVar2"] + TM[,"IFVar1"])
TS <- merge(TSA1,TSA2,by=c("Sample"))
TS[,"Difference"] <- TS[,"IFEst2" ] - TS[,"IFEst1" ]
TS[,"DIFSE"] <- sqrt(TS[,"IFVar2"] + TS[,"IFVar1"])
TS[,"TIF"] <- (TS[,"Difference"] - TS[,"MIFEst2"] + TS[,"MIFEst1"]) / TS[,"DIFSE"]
TS <- data.frame(TS)
cicut <- CIlevel
cicut1 <- (1 - CIlevel)/2
cicut2 <- 1 - cicut1
myq <- function(x) {
x1 <- as.vector(quantile(x, c(cicut1,cicut2)))
x2 <- as.vector(quantile(abs(x), c(cicut)))
return(c(x1,x2))
}
ag3 <- matrix(myq( TS[,c("TIF") ]), nrow=1)
colnames(ag3) <- c("tIFLow", "tIFHigh", "tIFSym")
TM <- merge(TM,ag3)
zcut <- qnorm( cicut2 )
lb1 <- TM[,"Difference"] - zcut * TM[,"DIFSE"]
ub1 <- TM[,"Difference"] + zcut * TM[,"DIFSE"]
lb5 <- TM[,"Difference"] - TM[,"tIFHigh"] * TM[,"DIFSE"]
ub5 <- TM[,"Difference"] - TM[,"tIFLow" ] * TM[,"DIFSE"]
lb7 <- TM[,"Difference"] - TM[,"tIFSym"] * TM[,"DIFSE"]
ub7 <- TM[,"Difference"] + TM[,"tIFSym"] * TM[,"DIFSE"]
Difference <- TM[,"Difference"]
CI <- cbind( alpha1, alpha2,Difference,lb1, ub1, lb5, ub5, lb7, ub7)
if ( i1 == 1 & i2 == 1) {
CIout <- CI
TMout <- TM
}
else {
CIout <- rbind(CIout,CI)
TMout <- rbind(TMout,TM)
}
}
}
Ret <- list( TM = TMout, CI = CIout, Nalpha = Nalpha, alphaList = alphaList, CIlevel=CIlevel )
return(Ret)
} |
NULL
maxlambdaMGLM <- function(object) {
object@maxlambda
}
setMethod("maxlambda", "MGLMsparsereg", function(object) maxlambdaMGLM(object))
NULL
dofMGLM <- function(object) {
object@Dof
}
setMethod("dof", "MGLMsparsereg", function(object) dofMGLM(object)) |
if (!isGeneric('makeTP')) {
setGeneric('makeTP', function(x, ...)
standardGeneric('makeTP'))
}
makeTP <- function(projectDir=tempdir(),
locationName="treePos",
missionTrackList=NULL,
launchPos=c(8.772055,50.814689),
demFn=NULL,
flightAltitude=100,
climbDist=7.5,
aboveTreeAlt=15,
circleRadius = 1.0,
takeOffAlt = 50.0,
presetFlightTask="remote",
maxSpeed=25.0,
followSurfaceRes=5,
altFilter=0.5,
windCondition=1,
launchAltitude=-9999,
uavType="pixhawk",
cameraType = "MAPIR2",
copy = FALSE,
runDir="") {
task <- NULL
demFn <- path.expand(demFn)
locationName <- paste0(locationName,"_missions")
surveyArea <- missionTrackList
projstru <- setProjStructure (projectDir,
locationName,
flightAltitude,
uavType,
cameraType,
surveyArea,
demFn,
copy,
"P")
dateString <- projstru[3]
taskName <- projstru[2]
csvFn <- projstru[1]
projectDir<-projstru[4]
runDir<-makeGlobalVar(name = "runDir",value = file.path(projectDir,"fp-data/run/"))
logger <- log4r::create.logger(logfile = paste0(file.path(projectDir, "fp-data/log/"),strsplit(basename(taskName), "\\.")[[1]][1],'.log'))
log4r::level(logger) <- "INFO"
log4r::levellog(logger,'INFO',"--------------------- START RUNfile.path(runDir, ---------------------------")
log4r::levellog(logger, 'INFO', paste("Working folder: ", file.path(projectDir)))
flightList <- readTreeTrack(missionTrackList)
test <- try(readLaunchPos(launchPos))
if (class(test)!="try-error"){
launchPos <- test
flightArea <- flightList+launchPos
}
else{
log4r::levellog(logger, 'FATAL', "
stop("
}
p <- list()
p$launchLat <- launchPos@coords[2]
p$launchLon <- launchPos@coords[1]
p$locationName <- locationName
p$missionTrackList <- missionTrackList
p$demFn <- demFn
p$flightAltitude <- flightAltitude
p$presetFlightTask <- presetFlightTask
p$maxSpeed <- maxSpeed
p$followSurfaceRes <- followSurfaceRes
p$windCondition <- windCondition
p$uavType <- uavType
p$curvesize <- 0
p$rotationdir <- 0
p$gimbalmode <- 0
p$gimbalpitchangle <- -90
p$launchAltitude <- launchAltitude
p$aboveTreeAlt <- aboveTreeAlt
p$altFilter <- altFilter
p$projectDir <- projectDir
p$climbDist <- climbDist
p$task <- fp_getPresetTask("treetop")
fullTreeList <- makeFlightPathT3(flightList,
p,
uavType,
task,
demFn,
logger,
projectDir,
locationName,
circleRadius,
flightArea,
takeOffAlt,
runDir)
log4r::levellog(logger, 'INFO', paste("taskName : ", taskName))
log4r::levellog(logger, 'INFO', paste("DEM filename : ", demFn))
log4r::levellog(logger, 'INFO', paste("launchAltitude : ", launchAltitude))
log4r::levellog(logger, 'INFO', paste("followSurface : ", followSurfaceRes))
log4r::levellog(logger, 'INFO', paste("altfilter : ", altFilter))
log4r::levellog(logger, 'INFO', paste("flightAltitude : ", flightAltitude))
log4r::levellog(logger, 'INFO', paste("flightAltitude : ", aboveTreeAlt))
log4r::levellog(logger, 'INFO', paste("flightAltitude : ", circleRadius))
log4r::levellog(logger, 'INFO', paste("flightAltitude : ", takeOffAlt))
log4r::levellog(logger, 'INFO', paste("presetFlightTask: ", presetFlightTask))
if (uavType == "djiP3"){
log4r::levellog(logger, 'INFO', paste("curvesize : ", p$curvesize))
log4r::levellog(logger, 'INFO', paste("rotationdir : ", p$rotationdir))
log4r::levellog(logger, 'INFO', paste("gimbalmode : ", p$gimbalmode))
log4r::levellog(logger, 'INFO',paste("gimbalpitchangle: ", p$gimbalpitchangle))
}
log4r::levellog(logger,'INFO',paste("max flight speed : ",round(maxSpeed, digits = 1)," (km/h) "))
log4r::levellog(logger,'INFO',"--------------------- END RUN -----------------------------")
note <- " Fly save and have Fun..."
dumpFile(paste0(file.path(projectDir, "fp-data/log/"),strsplit(basename(taskName), "\\.")[[1]][1],'.log'))
cat("\n NOTE: You will find all parameters in the logfile:\n",paste0(file.path(projectDir, "fp-data/log/"),strsplit(basename(taskName), "\\.")[[1]][1],'.log'),"","\n ",
"\n Fly save and have Fun...")
} |
MCSimulation<-function(P, i, nsteps){
n <- nrow(P)-1
statehist <- c(i, rep(0, nsteps))
for (step in 2:(nsteps+1)){
statehist[step] <- sample(0:n,1,prob=P[1+statehist[step-1],])
}
return(statehist)
} |
gen_skinny_cube <- function(dimension) {
kind_gen = 5
m_gen = 0
Vpoly_gen = FALSE
Mat = poly_gen(kind_gen, Vpoly_gen, FALSE, dimension, m_gen)
b = Mat[, 1]
Mat = Mat[, -c(1), drop = FALSE]
P = Hpolytope(A = -Mat, b = b, volume = 2^(dimension -1)*200)
return(P)
} |
display_name <- function(x) {
stopifnot(inherits(x, "coverage"))
if (length(x) == 0) {
return()
}
filenames <- vcapply(x, function(x) get_source_filename(x$srcref, full.names = TRUE))
to_relative_path(filenames, attr(x, "root"))
}
to_relative_path <- function(path, base) {
if (is.null(base)) {
return(path)
}
rex::re_substitutes(path, rex::rex(base, "/"), "")
}
filter_non_package_files <- function(x) {
filenames <- vcapply(x, function(x) get_source_filename(x$srcref, full.names = TRUE))
x[rex::re_matches(filenames, rex::rex(attr(x, "package")$path, "/"), "")]
} |
NAO <- function(ano_exp = NULL, ano_obs = NULL, lon, lat, ftime_average = 2:4, obsproj = TRUE) {
if (!is.null(ano_exp)) {
if (!is.numeric(ano_exp) || !is.array(ano_exp)) {
stop("Parameter 'ano_exp' must be a numeric array.")
}
if (length(dim(ano_exp)) != 6) {
stop("'ano_exp' must have dimensions c(n. experimental data sets, n. members, n. start dates, n. forecast time steps, n. latitudes, n. longitudes).")
}
}
if (!is.null(ano_obs)) {
if (!is.numeric(ano_obs) || !is.array(ano_obs)) {
stop("Parameter 'ano_obs' must be a numeric array.")
}
if (length(dim(ano_obs)) != 6) {
stop("'ano_obs' must have dimensions c(n. observational data sets, n. obs. members, n. start dates, n. forecast time steps, n. latitudes, n. longitudes).")
}
}
if (!is.null(ano_obs) && !is.null(ano_exp)) {
if (!identical(dim(ano_exp)[3:6], dim(ano_obs)[3:6])) {
stop("'ano_obs' and 'ano_exp' must have the same number of start dates, forecast time steps, latitudes and longitudes.")
}
}
if (!is.numeric(lon) || !is.numeric(lat)) {
stop("'lon' and 'lat' must be numeric vectors.")
}
if (is.null(attr(lon, 'first_lon')) || is.null(attr(lon, 'last_lon')) ||
is.null(attr(lon, 'array_across_gw')) || is.null(attr(lon, 'data_across_gw'))) {
.warning("At least one of the attributes 'first_lon', 'last_lon', 'data_across_gw' or 'array_across_gw' of the parameter 'lon' is not defined (see documentation on output 'lon' of ?Load). The spatial domain of the provided data may be unnoticedly wrong.")
}
if (is.null(attr(lat, 'last_lat'))) {
attr(lat, 'last_lat') <- tail(lat, 1)
}
if (is.null(attr(lat, 'first_lat'))) {
attr(lat, 'first_lat') <- head(lat, 1)
}
stop_bad_domain <- "The typical domain used to compute the NAO is 20N-80N, 80W-40E.\n"
stop_needed <- FALSE
if (attr(lat, 'last_lat') < 70 || attr(lat, 'last_lat') > 90 ||
attr(lat, 'first_lat') > 30 || attr(lat, 'first_lat') < 10) {
stop_needed <- TRUE
}
if (!is.null(attr(lon, 'data_across_gw'))) {
if (!attr(lon, 'data_across_gw')) {
stop_needed <- TRUE
}
}
if (!is.null(attr(lon, 'first_lon')) && !is.null(attr(lon, 'last_lon'))) {
if (!(attr(lon, 'last_lon') < attr(lon, 'first_lon'))) {
stop_needed <- TRUE
} else if (attr(lon, 'last_lon') > 50 || attr(lon, 'last_lon') < 30 ||
attr(lon, 'first_lon') > 290 || attr(lon, 'first_lon') < 270) {
stop_needed <- TRUE
}
}
if (stop_needed) {
stop(stop_bad_domain)
}
if (!is.null(ano_exp)) {
dims <- dim(ano_exp)
} else if (!is.null(ano_obs)) {
dims <- dim(ano_obs)
} else {
stop("Either one of 'ano_exp' or 'ano_obs' must be provided.")
}
nlon <- dims[6]
nlat <- dims[5]
nftimes <- dims[4]
nyr <- dims[3]
nmemb <- dims[2]
nexp <- dims[1]
if (length(lon) != nlon) {
stop("Inconsistent number of longitudes and input field dimensions.")
}
if (length(lat) != nlat) {
stop("Inconsistent number of latitudes and input field dimensions.")
}
if (nyr < 2) {
stop("At least data for 2 start dates must be provided.")
}
if (!is.numeric(ftime_average)) {
stop("'ftime_average' must be a numeric vector.")
}
if (any(ftime_average > nftimes)) {
stop("'ftime_averages' contains indexes to non-existing forecast time steps.")
}
if (!is.logical(obsproj)) {
stop("'obsproj' must be either TRUE or FALSE.")
}
if (obsproj) {
if (is.null(ano_obs)) {
stop("Parameter 'obsproj' set to TRUE but no 'ano_obs' provided.")
}
if (is.null(ano_exp)) {
.warning("parameter 'obsproj' set to TRUE but no 'ano_exp' provided.")
}
}
fcsys <- 1
NAOF.ver <- NULL
NAOO.ver <- NULL
OEOF <- NULL
if (!is.null(ano_exp)) {
ano_exp <- ano_exp[fcsys, , , ftime_average, , , drop = FALSE]
f1 <- Mean1Dim(ano_exp, posdim = 4, narm = TRUE)
dim(f1) <- c(1, nmemb, nyr, 1, nlat, nlon)
NAOF.ver <- array(NA, c(nmemb, nyr))
}
if (!is.null(ano_obs)) {
ano_obs <- ano_obs[1, 1, , ftime_average, , , drop = FALSE]
o1 <- Mean1Dim(ano_obs, posdim = 4, narm = TRUE)
dim(o1) <- c(1, 1, nyr, 1, nlat, nlon)
NAOO.ver <- array(NA, c(1, nyr))
}
for (iy in 1:nyr) {
if (!is.null(ano_obs)) {
o2 <- o1[1, 1, -iy, 1, , ]
dim(o2) <- c(nyr - 1, nlat, nlon)
OEOF <- EOF(o2, lon, lat, neofs = 1)
sign <- 1
if (0 < mean(OEOF$EOFs[1, which.min(abs(lat - 65)), ], na.rm = T)) {
sign <- -1
}
OEOF$EOFs <- OEOF$EOFs * sign
OEOF$PCs <- OEOF$PCs * sign
PCO <- ProjectField(o1, OEOF, mode = 1)
NAOO.ver[1, iy] <- PCO[1, 1, iy, 1]
}
if (!is.null(ano_exp)) {
if (!obsproj) {
f2 <- f1[1, , -iy, 1, , ]
dim(f2) <- c(nmemb * (nyr - 1), nlat, nlon)
FEOF <- EOF(f2, lon, lat, neofs = 1)
sign <- 1
if (0 < FEOF$EOFs[1, which.min(abs(lat - 65)), ]) {
sign <- -1
}
FEOF$EOFs <- FEOF$EOFs * sign
FEOF$PCs <- FEOF$PCs * sign
PCF <- ProjectField(f1, FEOF, mode = 1)
for (imemb in 1:nmemb) {
NAOF.ver[imemb, iy] <- PCF[1, imemb, iy, 1]
}
} else {
PCF <- ProjectField(f1, OEOF, mode = 1)
NAOF.ver[, iy] <- PCF[1, , iy, 1]
}
}
}
return(list(NAO_exp = NAOF.ver, NAO_obs = NAOO.ver, EOFs_obs = OEOF))
} |
context("Applying transformations")
test_that("Existing transformations can be applied and combined", {
options(RNiftyReg.threads=2L)
t2 <- readNifti(system.file("extdata","epi_t2.nii.gz",package="RNiftyReg"))
t1 <- readNifti(system.file("extdata","flash_t1.nii.gz",package="RNiftyReg"))
mni <- readNifti(system.file("extdata","mni_brain.nii.gz",package="RNiftyReg"))
t2_to_t1 <- readAffine(system.file("extdata","affine.txt",package="RNiftyReg"), t2, t1)
t1_to_mni <- readNifti(system.file("extdata","control.nii.gz",package="RNiftyReg"), t1, mni)
deformation <- deformationField(t2_to_t1, jacobian=TRUE)
expect_equal(round(worldToVoxel(as.array(deformation)[34,49,64,1,], t2)), c(40,40,20))
expect_equal(as.array(jacobian(deformation))[34,49,64], prod(diag(t2_to_t1)), tolerance=0.05)
expect_equal(applyTransform(t2_to_t1,c(40,40,20),nearest=TRUE), c(34,49,64))
expect_equal(class(applyTransform(t2_to_t1,t2,internal=TRUE))[1], "internalImage")
saveTransform(t2_to_t1, "t2_to_t1.rds")
reloadedTransform <- loadTransform("t2_to_t1.rds")
expect_equal(applyTransform(reloadedTransform,c(40,40,20),nearest=TRUE), c(34,49,64))
expect_equivalent(applyTransform(t2_to_t1,t2), applyTransform(reloadedTransform,t2))
unlink("t2_to_t1.rds")
skip_on_os("solaris")
point <- applyTransform(t2_to_t1, c(40,40,20), nearest=FALSE)
expect_equal(applyTransform(t1_to_mni,point,nearest=TRUE), c(33,49,24))
expect_equal(round(applyTransform(t1_to_mni,point,nearest=FALSE)), c(33,49,24))
expect_equal(applyTransform(t1_to_mni,t1,interpolation=0)[33,49,25], t1[34,49,64])
t2_to_mni <- composeTransforms(t2_to_t1, t1_to_mni)
expect_equal(applyTransform(t2_to_mni,c(40,40,20),nearest=TRUE), c(33,49,24))
t2_to_t1_half <- halfTransform(t2_to_t1)
expect_equivalent(composeTransforms(t2_to_t1_half,t2_to_t1_half), t2_to_t1)
t1_to_mni_half <- halfTransform(t1_to_mni)
mniIdentity <- buildAffine(source=mni)
t1_to_mni_reconstructed <- composeTransforms(t1_to_mni_half, t1_to_mni_half, mniIdentity)
expect_equal(applyTransform(t1_to_mni_reconstructed,point,nearest=TRUE), c(33,49,24))
}) |
data <- dat.bourassa1996
data <- escalc(measure = "OR", ai = lh.le, bi = lh.re, ci = rh.le, di= rh.re,
data = data, add = 1/2, to = "all")
data$mage[is.na(data$mage)] <- median(data$mage, na.rm = TRUE)
data[c(5:8)] <- lapply(data[c(5:8)], factor)
data$yi <- as.numeric(data$yi)
set.seed(33)
mf.cluster.b1996 <- MetaForest(formula = yi~ selection + investigator + hand_assess + eye_assess + mage +sex, data = data, study = "sample", whichweights = "unif", num.trees = 300)
test_that("clustermf has the correct number of trees", {expect_equal(300, mf.cluster.b1996$forest$num.trees)})
test_that("Metaforest calls clustermf", {expect_true(inherits(mf.cluster.b1996, "cluster_mf"))}) |
context("envir")
test_that("set env", {
path <- test_prepare_orderly_example("minimal")
cfg <- c("database:",
" source:",
" driver: RSQLite::SQLite",
" args:",
" dbname: source.sqlite",
" user: $MY_USER")
writeLines(cfg, file.path(path, "orderly_config.yml"))
config <- orderly_config_$new(path)
expect_error(orderly_db_args(config$database$source, config, "loc"),
"Environment variable 'MY_USER' is not set")
writeLines(c("MY_USER: foo"), path_orderly_envir_yml(path))
x <- orderly_db_args(config$database$source, config)
expect_equal(x$args$user, "foo")
writeLines(c("MY_USER: bar"), path_orderly_envir_yml(path))
x <- orderly_db_args(config$database$source, config)
expect_equal(x$args$user, "bar")
})
test_that("read env", {
path <- tempfile()
dir.create(path)
filename <- path_orderly_envir_yml(path)
writeLines(c("foo: 1", "foo: 2"), filename)
expect_error(orderly_envir_read(path))
writeLines(c("- foo: 1", "- foo: 2"), filename)
expect_error(orderly_envir_read(path),
"must be named")
writeLines(c("foo: 1", "bar: [2, 3]"), filename)
expect_error(
orderly_envir_read(path),
"Expected all elements of orderly_envir.yml to be scalar (check 'bar')",
fixed = TRUE)
})
test_that("non-character data is OK", {
path <- tempfile()
dir.create(path)
filename <- path_orderly_envir_yml(path)
writeLines(c("foo: 1", "bar: 2"), filename)
dat <- orderly_envir_read(path)
expect_equal(dat, c(foo = "1", bar = "2"))
})
test_that("remove null values", {
path <- tempfile()
dir.create(path)
filename <- path_orderly_envir_yml(path)
writeLines(c("foo: ~", "bar: 2"), filename)
dat <- orderly_envir_read(path)
expect_equal(dat, c(bar = "2"))
}) |
EDRDistance <- function(x, y, epsilon, sigma) {
if (class(try(EDRInitialCheck(x, y, epsilon, sigma))) == "try-error") {
return(NA)
} else {
tamx <- length(x)
tamy <- length(y)
subcost<-as.numeric(as.vector(t(proxy::dist(x, y, method="euclidean")
> epsilon)))
cost.matrix <- c(1:((tamx + 1) * (tamy + 1))) * 0 + (sum(subcost) *
length(subcost))
if (missing(sigma)) {
resultList <- .C("edrnw", as.integer(tamx), as.integer(tamy),
as.double(cost.matrix), as.double(subcost))
cost.matrix <- resultList[[3]]
} else {
resultList <- .C("edr", as.integer(tamx), as.integer(tamy),
as.integer(sigma), as.double(cost.matrix),
as.double(subcost))
cost.matrix <- resultList[[4]]
}
d <- cost.matrix[length(cost.matrix)]
return(d)
}
}
EDRInitialCheck <- function(x, y, epsilon, sigma) {
if (! is.numeric(x) | ! is.numeric(y)) {
stop('The series must be numeric', call.=FALSE)
}
if (! is.vector(x) | ! is.vector(y)) {
stop('The series must be univariate vectors', call.=FALSE)
}
if (length(x) < 1 | length(y) < 1) {
stop('The series must have at least one point', call.=FALSE)
}
if (! is.numeric(epsilon)) {
stop('The threshold must be numeric', call.=FALSE)
}
if (epsilon < 0) {
stop('The threshold must be positive', call.=FALSE)
}
if (any(is.na(x)) | any(is.na(y))) {
stop('There are missing values in the series', call.=FALSE)
}
if (! missing(sigma)) {
if ((sigma) <= 0) {
stop('The window size must be positive', call.=FALSE)
}
if (sigma < abs(length(x) - length(y))) {
stop('The window size can not be lower than the difference between the
series lengths', call.=FALSE)
}
}
} |
rgoogleads <- new.env(parent = emptyenv())
rgoogleads$last_request_id <- NULL
rgoogleads$customer_id <- NULL
invisible(rgoogleads)
gads_last_request_ids <- function() {
return(rgoogleads$last_request_id)
}
gads_customer_id_to_env <- function(customer_id) {
customer_id <- str_replace_all(customer_id, "-", "") %>%
str_replace('(\\d{3})(\\d{3})(\\d{4})', '\\1-\\2-\\3')
rgoogleads$customer_id <- customer_id
}
gads_customer_id_from_env <- function() {
return(rgoogleads$customer_id)
} |
"significantSNP" |
shinydashboard::tabItem(
tabName = "gauge",
fluidRow(
column(
width = 12,
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("gauge1"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
verbatimTextOutput("code_gauge1"))
)
)
)
)
)
) |
context("Testing the freqlist output")
TAB <- table(mdat[, c("Group", "Sex", "Phase")])
TAB.subset <- table(mdat[!(mdat$Group == "Low" & mdat$Sex == "Male"), c("Group", "Sex", "Phase")])
TAB.na <- table(mdat[, c("trt", "ethan")], useNA = 'a')
old.labs <- c(cumFreq = "cumFreq", freqPercent = "freqPercent", cumPercent = "cumPercent")
test_that("A basic freqlist call", {
expect_identical(
capture.kable(summary(freqlist(TAB), labelTranslations = old.labs)),
c("|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|High |Female |I | 4| 4| 4.44| 4.44|",
"| | |II | 8| 12| 8.89| 13.33|",
"| | |III | 3| 15| 3.33| 16.67|",
"| |Male |I | 7| 22| 7.78| 24.44|",
"| | |II | 2| 24| 2.22| 26.67|",
"| | |III | 6| 30| 6.67| 33.33|",
"|Low |Female |I | 7| 37| 7.78| 41.11|",
"| | |II | 8| 45| 8.89| 50.00|",
"| | |III | 2| 47| 2.22| 52.22|",
"| |Male |I | 5| 52| 5.56| 57.78|",
"| | |II | 4| 56| 4.44| 62.22|",
"| | |III | 4| 60| 4.44| 66.67|",
"|Med |Female |II | 11| 71| 12.22| 78.89|",
"| | |III | 3| 74| 3.33| 82.22|",
"| |Male |II | 8| 82| 8.89| 91.11|",
"| | |III | 8| 90| 8.89| 100.00|"
)
)
})
test_that("strata option in freqlist call", {
expect_identical(
capture.kable(summary(freqlist(TAB, strata = "Group"), single = FALSE, labelTranslations = old.labs)),
c("|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|High |Female |I | 4| 4| 13.33| 13.33|",
"| | |II | 8| 12| 26.67| 40.00|",
"| | |III | 3| 15| 10.00| 50.00|",
"| |Male |I | 7| 22| 23.33| 73.33|",
"| | |II | 2| 24| 6.67| 80.00|",
"| | |III | 6| 30| 20.00| 100.00|",
"" ,
"" ,
"|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|Low |Female |I | 7| 7| 23.33| 23.33|",
"| | |II | 8| 15| 26.67| 50.00|",
"| | |III | 2| 17| 6.67| 56.67|",
"| |Male |I | 5| 22| 16.67| 73.33|",
"| | |II | 4| 26| 13.33| 86.67|",
"| | |III | 4| 30| 13.33| 100.00|",
"" ,
"" ,
"|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|Med |Female |II | 11| 11| 36.67| 36.67|",
"| | |III | 3| 14| 10.00| 46.67|",
"| |Male |II | 8| 22| 26.67| 73.33|",
"| | |III | 8| 30| 26.67| 100.00|"
)
)
expect_error(freqlist(TAB, strata = "group"), "strata variable not found")
})
test_that("sparse option in freqlist call", {
expect_identical(
capture.kable(summary(freqlist(TAB, sparse = TRUE), labelTranslations = old.labs)),
c("|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|High |Female |I | 4| 4| 4.44| 4.44|",
"| | |II | 8| 12| 8.89| 13.33|",
"| | |III | 3| 15| 3.33| 16.67|",
"| |Male |I | 7| 22| 7.78| 24.44|",
"| | |II | 2| 24| 2.22| 26.67|",
"| | |III | 6| 30| 6.67| 33.33|",
"|Low |Female |I | 7| 37| 7.78| 41.11|",
"| | |II | 8| 45| 8.89| 50.00|",
"| | |III | 2| 47| 2.22| 52.22|",
"| |Male |I | 5| 52| 5.56| 57.78|",
"| | |II | 4| 56| 4.44| 62.22|",
"| | |III | 4| 60| 4.44| 66.67|",
"|Med |Female |I | 0| 60| 0.00| 66.67|",
"| | |II | 11| 71| 12.22| 78.89|",
"| | |III | 3| 74| 3.33| 82.22|",
"| |Male |I | 0| 74| 0.00| 82.22|",
"| | |II | 8| 82| 8.89| 91.11|",
"| | |III | 8| 90| 8.89| 100.00|"
)
)
})
test_that("NA options in freqlist call", {
expect_identical(
capture.kable(summary(freqlist(TAB.na, na.options = "include"))),
c("|trt |ethan | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:---|:-------|----:|---------------:|-------:|------------------:|",
"|A |Ethan | 17| 17| 18.89| 18.89|",
"| |Heinzen | 16| 33| 17.78| 36.67|",
"| |NA | 3| 36| 3.33| 40.00|",
"|B |Ethan | 25| 61| 27.78| 67.78|",
"| |Heinzen | 29| 90| 32.22| 100.00|"
)
)
expect_identical(
capture.kable(summary(freqlist(TAB.na, na.options = "showexclude"))),
c("|trt |ethan | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:---|:-------|----:|---------------:|-------:|------------------:|",
"|A |Ethan | 17| 17| 19.54| 19.54|",
"| |Heinzen | 16| 33| 18.39| 37.93|",
"| |NA | 3| NA| NA| NA|",
"|B |Ethan | 25| 58| 28.74| 66.67|",
"| |Heinzen | 29| 87| 33.33| 100.00|"
)
)
expect_identical(
capture.kable(summary(freqlist(TAB.na, na.options = "remove"))),
c("|trt |ethan | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:---|:-------|----:|---------------:|-------:|------------------:|",
"|A |Ethan | 17| 17| 19.54| 19.54|",
"| |Heinzen | 16| 33| 18.39| 37.93|",
"|B |Ethan | 25| 58| 28.74| 66.67|",
"| |Heinzen | 29| 87| 33.33| 100.00|"
)
)
})
test_that("Changing the labels on non-grouped freqlists", {
ref <- c(
"|Treatment |Ethan Rocks | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:---------|:-----------|----:|---------------:|-------:|------------------:|",
"|A |Ethan | 17| 17| 18.89| 18.89|",
"| |Heinzen | 16| 33| 17.78| 36.67|",
"| |NA | 3| 36| 3.33| 40.00|",
"|B |Ethan | 25| 61| 27.78| 67.78|",
"| |Heinzen | 29| 90| 32.22| 100.00|"
)
expect_identical(
capture.kable(summary(freqlist(TAB.na, na.options = "include"), labelTranslations = c(trt = "Treatment", ethan = "Ethan Rocks"))),
ref
)
expect_identical(
capture.kable(summary(freqlist(TAB.na, na.options = "include", labelTranslations = list(trt = "Treatment", ethan = "Ethan Rocks")))),
ref
)
expect_identical(
capture.kable(summary(freqlist(TAB.na, na.options = "include", labelTranslations = c(trt = "Treatment", ethan ="Ethan Rocks")))),
ref
)
expect_error(freqlist(TAB.na, labelTranslations = c("Treatment", "Ethan Rocks")), "Unnamed label")
expect_error(freqlist(TAB.na, labelTranslations = c(hi = "Treatment", ethan = "Ethan Rocks")), NA)
tmp <- freqlist(TAB.na, na.options = "include")
labels(tmp) <- c(trt = "Treatment", ethan = "Ethan Rocks")
expect_identical(
capture.kable(summary(tmp)),
ref
)
labels(tmp) <- NULL
expect_identical(
capture.kable(summary(tmp)),
c("|trt |ethan | Freq| cumFreq| freqPercent| cumPercent|",
"|:---|:-------|----:|-------:|-----------:|----------:|",
"|A |Ethan | 17| 17| 18.89| 18.89|",
"| |Heinzen | 16| 33| 17.78| 36.67|",
"| |NA | 3| 36| 3.33| 40.00|",
"|B |Ethan | 25| 61| 27.78| 67.78|",
"| |Heinzen | 29| 90| 32.22| 100.00|"
)
)
labels(tmp) <- c(ethan = "Ethan Rocks", trt = "Treatment", dummy = "Dummy")
expect_identical(
capture.kable(summary(tmp)),
c(
"|Treatment |Ethan Rocks | Freq| cumFreq| freqPercent| cumPercent|",
"|:---------|:-----------|----:|-------:|-----------:|----------:|",
"|A |Ethan | 17| 17| 18.89| 18.89|",
"| |Heinzen | 16| 33| 17.78| 36.67|",
"| |NA | 3| 36| 3.33| 40.00|",
"|B |Ethan | 25| 61| 27.78| 67.78|",
"| |Heinzen | 29| 90| 32.22| 100.00|"
)
)
})
test_that("Changing the labels on grouped freqlists", {
expect_identical(
capture.kable(summary(freqlist(TAB.na, options = "include", strata = "ethan",
labelTranslations = c(trt = "Treatment", ethan = "Ethan", old.labs)))),
c("|Ethan |Treatment | Freq| cumFreq| freqPercent| cumPercent|" ,
"|:-----|:---------|----:|-------:|-----------:|----------:|" ,
"|Ethan |A | 17| 17| 40.48| 40.48|" ,
"| |B | 25| 42| 59.52| 100.00|" ,
"" ,
"" ,
"|Ethan |Treatment | Freq| cumFreq| freqPercent| cumPercent|",
"|:-------|:---------|----:|-------:|-----------:|----------:|",
"|Heinzen |A | 16| 16| 35.56| 35.56|",
"| |B | 29| 45| 64.44| 100.00|",
"" ,
"" ,
"|Ethan |Treatment | Freq| cumFreq| freqPercent| cumPercent|" ,
"|:-----|:---------|----:|-------:|-----------:|----------:|" ,
"|NA |A | 3| 3| 100.00| 100.00|"
)
)
})
test_that("dupLabels works", {
expect_identical(
capture.kable(summary(freqlist(TAB, labelTranslations = old.labs), dupLabels = TRUE)),
c("|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|High |Female |I | 4| 4| 4.44| 4.44|",
"|High |Female |II | 8| 12| 8.89| 13.33|",
"|High |Female |III | 3| 15| 3.33| 16.67|",
"|High |Male |I | 7| 22| 7.78| 24.44|",
"|High |Male |II | 2| 24| 2.22| 26.67|",
"|High |Male |III | 6| 30| 6.67| 33.33|",
"|Low |Female |I | 7| 37| 7.78| 41.11|",
"|Low |Female |II | 8| 45| 8.89| 50.00|",
"|Low |Female |III | 2| 47| 2.22| 52.22|",
"|Low |Male |I | 5| 52| 5.56| 57.78|",
"|Low |Male |II | 4| 56| 4.44| 62.22|",
"|Low |Male |III | 4| 60| 4.44| 66.67|",
"|Med |Female |II | 11| 71| 12.22| 78.89|",
"|Med |Female |III | 3| 74| 3.33| 82.22|",
"|Med |Male |II | 8| 82| 8.89| 91.11|",
"|Med |Male |III | 8| 90| 8.89| 100.00|"
)
)
expect_identical(
capture.kable(summary(freqlist(TAB, strata = "Group", labelTranslations = old.labs), single = FALSE, dupLabels = TRUE)),
c("|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|High |Female |I | 4| 4| 13.33| 13.33|",
"|High |Female |II | 8| 12| 26.67| 40.00|",
"|High |Female |III | 3| 15| 10.00| 50.00|",
"|High |Male |I | 7| 22| 23.33| 73.33|",
"|High |Male |II | 2| 24| 6.67| 80.00|",
"|High |Male |III | 6| 30| 20.00| 100.00|",
"" ,
"" ,
"|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|Low |Female |I | 7| 7| 23.33| 23.33|",
"|Low |Female |II | 8| 15| 26.67| 50.00|",
"|Low |Female |III | 2| 17| 6.67| 56.67|",
"|Low |Male |I | 5| 22| 16.67| 73.33|",
"|Low |Male |II | 4| 26| 13.33| 86.67|",
"|Low |Male |III | 4| 30| 13.33| 100.00|",
"" ,
"" ,
"|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|Med |Female |II | 11| 11| 36.67| 36.67|",
"|Med |Female |III | 3| 14| 10.00| 46.67|",
"|Med |Male |II | 8| 22| 26.67| 73.33|",
"|Med |Male |III | 8| 30| 26.67| 100.00|"
)
)
})
test_that("Adding a title", {
expect_identical(
capture.kable(summary(freqlist(TAB.na, options = "include", labelTranslations = c(trt = "Treatment", ethan = "Ethan", old.labs)),
dupLabels = TRUE, title = "Ethan Rocks")),
c("Table: Ethan Rocks" ,
"" ,
"|Treatment |Ethan | Freq| cumFreq| freqPercent| cumPercent|",
"|:---------|:-------|----:|-------:|-----------:|----------:|",
"|A |Ethan | 17| 17| 18.89| 18.89|",
"|A |Heinzen | 16| 33| 17.78| 36.67|",
"|A |NA | 3| 36| 3.33| 40.00|",
"|B |Ethan | 25| 61| 27.78| 67.78|",
"|B |Heinzen | 29| 90| 32.22| 100.00|"
)
)
expect_identical(
capture.kable(summary(freqlist(TAB.na, options = "include", strata = "ethan",
labelTranslations = c(trt = "Treatment", ethan = "Ethan", old.labs)),
dupLabels = TRUE, title = "Ethan Rocks")),
c("Table: Ethan Rocks" ,
"" ,
"|Ethan |Treatment | Freq| cumFreq| freqPercent| cumPercent|" ,
"|:-----|:---------|----:|-------:|-----------:|----------:|" ,
"|Ethan |A | 17| 17| 40.48| 40.48|" ,
"|Ethan |B | 25| 42| 59.52| 100.00|" ,
"" ,
"" ,
"|Ethan |Treatment | Freq| cumFreq| freqPercent| cumPercent|",
"|:-------|:---------|----:|-------:|-----------:|----------:|",
"|Heinzen |A | 16| 16| 35.56| 35.56|",
"|Heinzen |B | 29| 45| 64.44| 100.00|",
"" ,
"" ,
"|Ethan |Treatment | Freq| cumFreq| freqPercent| cumPercent|" ,
"|:-----|:---------|----:|-------:|-----------:|----------:|" ,
"|NA |A | 3| 3| 100.00| 100.00|"
)
)
})
test_that("Formula method works", {
expect_identical(
capture.kable(summary(freqlist(TAB.na, options = "include"), labelTranslations = c(trt = "Trt", ethan = "Ethan"))),
capture.kable(summary(freqlist(~ trt + addNA(ethan), data = mdat), labelTranslations = c("addNA(ethan)" = "Ethan", trt = "Trt")))
)
if(getRversion() >= "3.4.0")
{
expect_identical(
capture.kable(summary(freqlist(~ trt + ethan, data = mdat, addNA = TRUE), labelTranslations = c(trt = "Trt", ethan = "Ethan"))),
capture.kable(summary(freqlist(~ trt + addNA(ethan), data = mdat), labelTranslations = c("addNA(ethan)" = "Ethan", trt = "Trt")))
)
} else skip("R version isn't right to use 'addNA=TRUE'")
})
test_that("digits specification", {
expect_identical(
capture.kable(summary(freqlist(~ trt + addNA(ethan), data = mdat), digits.pct = 1, digits.count = 1)),
capture.kable(summary(freqlist(~ trt + addNA(ethan), data = mdat, digits.pct = 1, digits.count = 1)))
)
expect_identical(
capture.kable(summary(freqlist(~ trt + addNA(ethan), data = mdat), digits.pct = 1, digits.count = 1)),
c(
"|Treatment Arm |addNA(ethan) | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:-------------|:------------|----:|---------------:|-------:|------------------:|",
"|A |Ethan | 17.0| 17.0| 18.9| 18.9|",
"| |Heinzen | 16.0| 33.0| 17.8| 36.7|",
"| |NA | 3.0| 36.0| 3.3| 40.0|",
"|B |Ethan | 25.0| 61.0| 27.8| 67.8|",
"| |Heinzen | 29.0| 90.0| 32.2| 100.0|"
)
)
})
test_that("11/18/16: Emily Lundt's subsetted table and duplicate label problem", {
expect_identical(
capture.kable(summary(freqlist(TAB.subset), labelTranslations = old.labs)),
c("|Group |Sex |Phase | Freq| cumFreq| freqPercent| cumPercent|",
"|:-----|:------|:-----|----:|-------:|-----------:|----------:|",
"|High |Female |I | 4| 4| 5.19| 5.19|",
"| | |II | 8| 12| 10.39| 15.58|",
"| | |III | 3| 15| 3.90| 19.48|",
"| |Male |I | 7| 22| 9.09| 28.57|",
"| | |II | 2| 24| 2.60| 31.17|",
"| | |III | 6| 30| 7.79| 38.96|",
"|Low |Female |I | 7| 37| 9.09| 48.05|",
"| | |II | 8| 45| 10.39| 58.44|",
"| | |III | 2| 47| 2.60| 61.04|",
"|Med |Female |II | 11| 58| 14.29| 75.32|",
"| | |III | 3| 61| 3.90| 79.22|",
"| |Male |II | 8| 69| 10.39| 89.61|",
"| | |III | 8| 77| 10.39| 100.00|"
)
)
})
test_that("04/17/18: using 'method' in freqlist (
dat <- data.frame(method = c(1, 1, 2, 2, 3, 3, 4, 4))
expect_identical(
capture.kable(summary(freqlist(~method, data = dat))),
c("|method | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:------|----:|---------------:|-------:|------------------:|",
"|1 | 2| 2| 25.00| 25.00|",
"|2 | 2| 4| 25.00| 50.00|",
"|3 | 2| 6| 25.00| 75.00|",
"|4 | 2| 8| 25.00| 100.00|"
)
)
})
test_that("02/26/19: don't drop labels with subset= argument (
expect_identical(
capture.kable(summary(freqlist(~ age, data = mockstudy, subset = age > 80))),
c("|Age in Years | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:------------|----:|---------------:|-------:|------------------:|",
"|81 | 12| 12| 41.38| 41.38|",
"|82 | 6| 18| 20.69| 62.07|",
"|83 | 6| 24| 20.69| 82.76|",
"|84 | 1| 25| 3.45| 86.21|",
"|85 | 2| 27| 6.90| 93.10|",
"|88 | 2| 29| 6.90| 100.00|"
)
)
})
test_that("03/20/2019: freqlist still works with all zero counts (
tab0 <- table(factor(c(), levels = c("m", "f")))
expect_error(print(summary(freqlist(tab0))), "There wasn't anything")
expect_identical(
capture.kable(summary(freqlist(tab0), sparse = TRUE)),
c("|Var1 | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:----|----:|---------------:|-------:|------------------:|",
"|m | 0| 0| NA| NA|",
"|f | 0| 0| NA| NA|"
)
)
})
test_that("03/21/2019: freqlist doesn't lose labels when subsetting (
expect_identical(
capture.kable(summary(freqlist(~ sex + ps + arm, data = mockstudy, strata = "arm",
subset = arm == "F: FOLFOX" & !is.na(ps))[c(1:2, 4)])),
c("|Treatment Arm |sex | Freq|",
"|:-------------|:------|----:|",
"|F: FOLFOX |Male | 168|",
"| | | 148|",
"| | | 16|",
"| |Female | 110|",
"| | | 95|",
"| | | 13|"
)
)
})
test_that("02/28/2020: freqlist.formula works without needing addNA AND na.option (
expect_identical(
capture.kable(summary(freqlist(~ sex + ps, data = mockstudy))),
c("|sex |ps | Freq| Cumulative Freq| Percent| Cumulative Percent|",
"|:------|:--|----:|---------------:|-------:|------------------:|",
"|Male |0 | 391| 391| 26.08| 26.08|",
"| |1 | 329| 720| 21.95| 48.03|",
"| |2 | 34| 754| 2.27| 50.30|",
"| |NA | 162| 916| 10.81| 61.11|",
"|Female |0 | 244| 1160| 16.28| 77.38|",
"| |1 | 202| 1362| 13.48| 90.86|",
"| |2 | 33| 1395| 2.20| 93.06|",
"| |NA | 104| 1499| 6.94| 100.00|"
)
)
expect_identical(
capture.kable(summary(freqlist(~ sex + ps, data = mockstudy, addNA = FALSE))),
capture.kable(summary(freqlist(~ sex + ps, data = mockstudy, na.options = "remove")))
)
}) |
sample_posterior_R <- function(R, n = 1000, window = 1L) {
if (!inherits(R, "estimate_R")) {
stop("R must be generated from the estimate_r function.")
}
mu <- R$R$`Mean(R)`[window]
sigma <- R$R$`Std(R)`[window]
cv <- sigma / mu
shape <- 1 / (cv ^ 2)
scale <- mu * cv ^ 2
rgamma(n, shape = shape, scale = scale)
} |
is.gce_zone_operation <- function(x){
inherits(x, "gce_zone_operation")
}
as.zone_operation <- function(x){
structure(x, class = c("gce_zone_operation", class(x)))
}
is.gce_global_operation <- function(x){
inherits(x, "gce_global_operation")
}
as.region_operation <- function(x){
structure(x, class = c("gce_region_operation", class(x)))
}
is.gce_region_operation <- function(x){
inherits(x, "gce_region_operation")
}
as.global_operation <- function(x){
structure(x, class = c("gce_global_operation", class(x)))
}
gce_delete_op <- function(operation) {
if(inherits(operation,
c("gce_global_operation", "gce_zone_operation","gce_region_operation"))){
UseMethod("gce_delete_op", operation)
} else {
myMessage("No operation class found. Got: ", class(operation), level = 1)
return(operation)
}
}
gce_delete_op.gce_zone_operation <- function(operation) {
if(is.gce_zone_operation(operation)){
url <- operation$selfLink
} else {
stop("Not a gce_zone_operation")
}
f <- gar_api_generator(url, "DELETE", data_parse_function = function(x) x)
suppressWarnings(out <- f())
myMessage("Operation cancelled", level = 3)
as.zone_operation(out)
}
gce_delete_op.gce_global_operation <- function(operation) {
if(is.gce_global_operation(operation)){
url <- operation$selfLink
} else {
stop("Not a gce_global_operation")
}
f <- gar_api_generator(url, "DELETE", data_parse_function = function(x) x)
suppressWarnings(out <- f())
myMessage("Operation cancelled", level = 3)
as.zone_operation(out)
}
gce_get_op <- function(operation = .Last.value){
if(inherits(operation, c("gce_global_operation", "gce_zone_operation","gce_region_operation"))){
UseMethod("gce_get_op", operation)
} else {
myMessage("No operation class found. Got: ", class(operation), level = 1)
return(operation)
}
}
gce_get_op.gce_zone_operation <- function(operation) {
if(is.gce_zone_operation(operation)){
url <- operation$selfLink
} else {
stop("Not a gce_zone_operation")
}
f <- gar_api_generator(url, "GET", data_parse_function = function(x) x)
out <- f()
as.zone_operation(out)
}
gce_get_op.gce_global_operation <- function(operation) {
if(is.gce_global_operation(operation)){
url <- operation$selfLink
} else {
stop("Not class gce_global_operation")
}
f <- gar_api_generator(url, "GET", data_parse_function = function(x) x)
out <- f()
as.global_operation(out)
}
gce_list_zone_op <- function(filter = NULL,
maxResults = NULL,
pageToken = NULL,
project = gce_get_global_project(),
zone = gce_get_global_zone()) {
url <- sprintf("https://www.googleapis.com/compute/v1/projects/%s/zones/%s/operations",
project, zone)
pars <- list(filter = filter,
maxResults = maxResults,
pageToken = pageToken)
pars <- rmNullObs(pars)
f <- gar_api_generator(url,
"GET",
pars_args = pars,
data_parse_function = function(x) x)
f()
}
gce_wait <- function(operation, wait = 3, verbose = TRUE, timeout_tries = 50){
if(inherits(operation, "character")){
stop("Use the job object instead of job$name")
}
if(operation$kind != "compute
myMessage("Not an operation, returning object")
return(operation)
}
DO_IT <- TRUE
tries <- 0
myMessage("Starting operation...", level = 2)
while(DO_IT){
check <- gce_get_op(operation)
if(check$status == "DONE"){
DO_IT <- FALSE
} else if(check$status == "RUNNING"){
if(verbose) myMessage("Operation running...", level = 3)
} else {
if(verbose) myMessage("Checking operation...", check$status, level = 3)
}
Sys.sleep(wait)
tries <- tries + 1
if(tries > timeout_tries){
myMessage("Timeout reached in operation")
check$error$errors <- "Timeout reached in operation"
DO_IT <- FALSE
}
}
if(verbose && !is.null(check$endTime))
myMessage("Operation complete in ",
format(timestamp_to_r(check$endTime) - timestamp_to_r(check$insertTime)), level = 3)
if(!is.null(check$error)){
errors <- check$error$errors
e.m <- paste(vapply(errors, print, character(1)), collapse = " : ", sep = " \n")
warning("
warning("
}
check
} |
library(ggplot2)
xGrid = c(0+.Machine$double.eps,seq(0,1, length.out=81)[-c(1,81)],1-.Machine$double.eps)
theta0 <- expand.grid(mu=seq(0,2,length.out=9), sigma=10^seq(-0.5,0.5,length.out=5))
n <- nrow(theta0)
.calcDensityGrid <- function(
theta0
,xGrid = seq(0,1, length.out=81)[-c(1,81)]
){
dx <- apply( theta0, 1, function(theta0i){
dx <- dlogitnorm(xGrid, mu=theta0i[1], sigma=theta0i[2])
})
dimnames(dx) <- list(iX=NULL,iTheta=NULL)
ds <- melt(dx)
ds[1:10,]
ds$mu <- rep(as.factor(round(theta0[,1],2)), each=length(xGrid))
ds$sigma <- rep(as.factor(round(theta0[,2],2)), each=length(xGrid))
ds$x <- rep(xGrid, nrow(theta0))
ds
}
.calcCdfGrid <- function(
theta0
,xGrid = seq(0,1, length.out=81)[-c(1,81)]
){
dx <- apply( theta0, 1, function(theta0i){
dx <- plogitnorm(xGrid, mu=theta0i[1], sigma=theta0i[2])
})
dimnames(dx) <- list(iX=NULL,iTheta=NULL)
ds <- melt(dx)
ds[1:10,]
ds$mu <- rep(as.factor(round(theta0[,1],2)), each=length(xGrid))
ds$sigma <- rep(as.factor(round(theta0[,2],2)), each=length(xGrid))
ds$x <- rep(xGrid, nrow(theta0))
ds
}
windows(width=7,height=4.5)
ds <- .calcDensityGrid(theta0,xGrid=xGrid)
qplot(xGrid,value,data=ds, geom="line", color=sigma, ylab="density")+ facet_wrap(~mu,scales="free")+opts(axis.title.x = theme_blank())
windows(width=4,height=4)
ds <- .calcDensityGrid(theta0,xGrid=xGrid)
qplot(xGrid,value,data=ds[ds$mu %in% c(0,1),], geom="line", color=sigma, ylab="density")+ facet_grid(mu~.,scales="free")+opts(axis.title.x = theme_blank())
ds <- .calcCdfGrid(theta0,xGrid=xGrid)
qplot(xGrid,value,data=ds[ds$mu %in% c(0,1),], geom="line", color=sigma, ylab="cumulative density")+ facet_grid(mu~.,scales="free")+opts(axis.title.x = theme_blank())
mle=0.8
mu <- seq(0,logit(mle),length.out=10)[-10]
tmp <- twSigmaLogitnorm(mle,mu)
sigma2 <- (logit(mle)-mu)/(2*mle-1)
theta0 <- cbind(mu,sigma=as.numeric(sqrt(sigma2)))
ds <- .calcDensityGrid(theta0,xGrid=xGrid)
qplot(xGrid,value,data=ds, geom="line", color=mu )
qlogitnorm(p=0.975,mu=theta0[,1],sigma=theta0[,2])
qlogitnorm(p=0.99,mu=theta0[,1],sigma=theta0[,2])
mle=0.8
plot( .ofLogitnormMLE(mu,mle=mle,quant=0.95,perc=0.999) ~ mu)
theta <- twCoefLogitnormMLE( mle=mle,quant=0.95,perc=0.99)
plot( dlogitnorm(xGrid,mu=theta[1],sigma=theta[2])~xGrid, type="l")
c( (logit(mle)-theta[1])/(2*mle-1), theta[2]^2 )
abline(v=c(mle,0.99),col="gray")
mle=0.5
theta <- twCoefLogitnormMLE( mle=mle,quant=0.99,perc=0.999)
q2 <- qlogitnorm(0.999,mu=theta[1],sigma=theta[2])
plot( dlogitnorm(xGrid,mu=theta[1],sigma=theta[2])~xGrid, type="l")
abline(v=c(mle,q2),col="gray")
mle=0.1
theta <- twCoefLogitnormMLE( mle=mle,quant=0.5,perc=0.99)
quant2 <- qlogitnorm(0.99,mu=theta[1],sigma=theta[2])
plot( dlogitnorm(xGrid,mu=theta[1],sigma=theta[2])~xGrid, type="l")
abline(v=c(mle,quant2),col="gray")
mle=0.9
theta <- twCoefLogitnormMLE( mle=mle,quant=0.98,perc=0.99)
quant2 <- qlogitnorm(0.99,mu=theta[1],sigma=theta[2])
plot( dlogitnorm(xGrid,mu=theta[1],sigma=theta[2])~xGrid, type="l")
abline(v=c(mle,quant2),col="gray")
mle=0.9
mu=seq(0,if(mle<0.5) mle else 1-mle,length.out=10)[-10]
mu=seq(0,0.25,length.out=10)[-10]
tmp <- twSigmaLogitnorm(mle,mu)
sigma2 <- (logit(mle)-mu)/(2*mle-1)
theta0 <- cbind(mu,sigma=as.numeric(sqrt(sigma2)))
ds <- .calcDensityGrid(theta0,xGrid=xGrid)
qplot(xGrid,value,data=ds, geom="line", color=mu, ylim=c(0.9,1.2) ) |
context("Dataframe Structure")
test_that("curve_mean", {
GroupA <- runif(100, min = 0, max = 100)
GroupB <- runif(100, min = 0, max = 100)
RandomData <- data.frame(GroupA, GroupB)
bob <- curve_mean(GroupA, GroupB, RandomData, method = "default")
variable1 <- rnorm(100)
variable2 <- rnorm(100)
variable3 <- rnorm(100)
variable4 <- rnorm(100)
variable5 <- rnorm(100)
variable6 <- rnorm(100)
variable7 <- rnorm(100)
sampledf <- data.frame(variable1, variable2, variable3, variable4, variable5, variable6, variable7)
columnnames <- c("lower.limit", "upper.limit", "intrvl.width", "intrvl.level", "cdf", "pvalue", "svalue")
colnames(sampledf) <- columnnames
expect_equivalent(str(bob[[1]]), str(sampledf))
})
test_that("curve_gen", {
GroupA <- rnorm(50)
GroupB <- rnorm(50)
RandomData <- data.frame(GroupA, GroupB)
rob <- glm(GroupA ~ GroupB, data = RandomData)
bob <- curve_gen(rob, "GroupB", method = "glm")
variable1 <- rnorm(100)
variable2 <- rnorm(100)
variable3 <- rnorm(100)
variable4 <- rnorm(100)
variable5 <- rnorm(100)
variable6 <- rnorm(100)
variable7 <- rnorm(100)
sampledf <- data.frame(variable1, variable2, variable3, variable4, variable5, variable6, variable7)
columnnames <- c("lower.limit", "upper.limit", "intrvl.width", "intrvl.level", "cdf", "pvalue", "svalue")
colnames(sampledf) <- columnnames
expect_equivalent(str(bob[[1]]), str(sampledf))
})
test_that("curve_meta", {
library(metafor)
GroupAData <- runif(20, min = 0, max = 100)
GroupAMean <- round(mean(GroupAData), digits = 2)
GroupASD <- round(sd(GroupAData), digits = 2)
GroupBData <- runif(20, min = 0, max = 100)
GroupBMean <- round(mean(GroupBData), digits = 2)
GroupBSD <- round(sd(GroupBData), digits = 2)
GroupCData <- runif(20, min = 0, max = 100)
GroupCMean <- round(mean(GroupCData), digits = 2)
GroupCSD <- round(sd(GroupCData), digits = 2)
GroupDData <- runif(20, min = 0, max = 100)
GroupDMean <- round(mean(GroupDData), digits = 2)
GroupDSD <- round(sd(GroupDData), digits = 2)
StudyName <- c("Study1", "Study2")
MeanTreatment <- c(GroupAMean, GroupCMean)
MeanControl <- c(GroupBMean, GroupDMean)
SDTreatment <- c(GroupASD, GroupCSD)
SDControl <- c(GroupBSD, GroupDSD)
NTreatment <- c(20, 20)
NControl <- c(20, 20)
metadf <- data.frame(StudyName, MeanTreatment, MeanControl, SDTreatment, SDControl, NTreatment, NControl)
library(metafor)
dat <- escalc(
measure = "SMD", m1i = MeanTreatment, sd1i = SDTreatment, n1i = NTreatment,
m2i = MeanControl, sd2i = SDControl, n2i = NControl, data = metadf
)
res <- rma(yi, vi, data = dat, slab = paste(StudyName, sep = ", "), method = "FE", digits = 2)
metaf <- curve_meta(res)
variable1 <- rnorm(100)
variable2 <- rnorm(100)
variable3 <- rnorm(100)
variable4 <- rnorm(100)
variable5 <- rnorm(100)
variable6 <- rnorm(100)
variable7 <- rnorm(100)
sampledf <- data.frame(variable1, variable2, variable3, variable4, variable5, variable6, variable7)
columnnames <- c("lower.limit", "upper.limit", "intrvl.width", "intrvl.level", "cdf", "pvalue", "svalue")
colnames(sampledf) <- columnnames
expect_equivalent(str(metaf[[1]]), str(sampledf))
}) |
block.ts <- function(data, l=2) {
if(l == 1) {
return(invisible(data))
}
if(is.vector(data)) {
N <- floor(length(data)/l)*l
return( apply(array(data, dim=c(l, N/l)), 2, mean))
}
if(length(dim(data))!=2) {
stop("block.ts currently only implemented for vectors of 2-dim arrays\n")
}
N <- floor(length(data[,1])/l)*l
ncf <- array(0, dim=c(N/l,length(data[1,])))
j <- 1
for ( i in seq(1,N,l)) {
ncf[j,] <- apply(data[i:(i+l-1),], 2, mean)
j <- j+1
}
return(invisible(ncf))
} |
node <- function(object) {
UseMethod("node")
}
way <- function(object) {
UseMethod("way")
}
relation <- function(object) {
UseMethod("relation")
}
elem_by_id <- function(id, subclass) {
structure(c(id = id), element = subclass, class = c(subclass, "element"))
}
node.default <- function(object) {
elem_by_id(object, "node")
}
way.default <- function(object) {
elem_by_id(object, "way")
}
relation.default <- function(object) {
elem_by_id(object, "relation")
}
attrs <- function(condition) {
structure(list(condition = substitute(condition)), what = "attrs",
class = "condition")
}
tags <- function(condition) {
structure(list(condition = substitute(condition)), what = "tags",
class = "condition")
}
refs <- function(condition) {
structure(list(condition = substitute(condition)), what = "refs",
class = "condition")
}
node.condition <- function(object) {
structure(object, element = "node")
}
way.condition <- function(object) {
structure(object, element = "way")
}
relation.condition <- function(object) {
structure(object, element = "relation")
} |
mean(Sepal.Length ~ Species, data = iris)
median(Sepal.Length ~ Species, data = iris)
df_stats(Sepal.Length ~ Species, data = iris, mean, median) |
MannKendallLTP <- function(data) {
nx <- as.integer(length(data))
nx_double_sum <- as.integer((nx*(nx-1))/2)
out1<-.C("score",nx,data,tr = as.integer(array(0,dim = c(1,3))),PACKAGE =
"HKprocess")
S <- (out1$tr)[1]
V0Sminus <- (out1$tr)[2]
denom_ties <- (out1$tr)[3]
rm(out1)
V0S <- (nx * (nx - 1) * (2*nx + 5))/18 - V0Sminus/18
u <- ifelse(S > 0,(S - 1)/sqrt(V0S),ifelse(S==0,0,(S + 1)/sqrt(V0S)))
pvalue_mann_kendall <- 2 * pnorm(-abs(u))
rm(u)
denominator <- sqrt(nx_double_sum - 0.5 * denom_ties)* sqrt(nx_double_sum)
tau <- S/denominator
out2<-.C("score0",nx,data,tr = array(0,dim = c(1,nx_double_sum)),PACKAGE =
"HKprocess")
s0 <- median(out2$tr)
rm(out2)
y <- data - s0 * (1:nx)
ranky <- rank(y,ties.method = c("average"))
z <- qnorm(ranky/(nx + 1))
Hest <- mleHK(z)[3]
mHsign <- 0.5 - 2.87 * (nx^(-0.9067))
sHsign <- 0.77654 * (nx^(-0.5)) - 0.0062
pvalue_H <- 2 * pnorm(-abs((Hest - mHsign)/sHsign))
a0 <- (1.0024 * nx - 2.5681)/(nx + 18.6693)
a1 <- (-2.2510 * nx + 157.2075)/(nx + 9.2245)
a2 <- (15.3402 * nx - 188.6140)/(nx + 5.8917)
a3 <- (-31.4258 * nx + 549.8599)/(nx - 1.1040)
a4 <- (20.7988 * nx - 419.0402)/(nx - 1.9248)
B <- a0 + a1 * Hest + a2 * Hest^2 + a3 * Hest^3 + a4 * Hest^4
out3<-.C("VstarSfunction",nx,Hest,tr = array(0,dim = c(1,1)),PACKAGE =
"HKprocess")
V_star_S <- (c((out3$tr)[1]))
rm(out3)
VS <- B * V_star_S
u <- ifelse(S > 0,(S - 1)/sqrt(VS),ifelse(S==0,0,(S + 1)/sqrt(VS)))
pvalue_mann_kendall_ltp <- 2 * pnorm(-abs(u))
rm(u)
Mann_Kendall <- setNames(c(tau,S,V0S,s0,denominator,pvalue_mann_kendall),
c("Kendall_s_tau_statistic","Score","V0Score","Sen_slope","denominator",
"2_sided_pvalue"))
H_significance <- setNames(c(Hest,pvalue_H),c("Hest","2_sided_pvalue"))
Mann_Kendall_LTP <- setNames(c(VS,pvalue_mann_kendall_ltp),c("VScore",
"2_sided_pvalue"))
results_names <- c("Mann_Kendall","Significance_of_H","Mann_Kendall_LTP")
results <- list(Mann_Kendall,H_significance,Mann_Kendall_LTP)
names(results) <- results_names
return(results)
} |
context("tuning")
test_that("tuning_run throws graceful errors with wrong sample argument", {
with_tests_dir({
expect_error(
tuning_run("write_run_data.R",
confirm = FALSE,
flags = list(
learning_rate = c(0.01, 0.02),
max_steps = c(2500, 500)
),
sample = 1.1,
echo = FALSE
)
)
})
with_tests_dir({
expect_error(
tuning_run("write_run_data.R",
confirm = FALSE,
flags = list(
learning_rate = c(0.01, 0.02),
max_steps = c(2500, 500)
),
sample = 0,
echo = FALSE
)
)
})
runs <- with_tests_dir({
tuning_run("write_run_data.R",
confirm = FALSE,
flags = list(
learning_rate = c(0.01, 0.02),
max_steps = c(2500, 500)
),
sample = 1e-6,
echo = FALSE
)
})
expect_equal(nrow(runs), 1)
})
test_that("tuning_run can execute multiple runs", {
runs <- with_tests_dir({
tuning_run("write_run_data.R",
confirm = FALSE,
flags = list(
learning_rate = c(0.01, 0.02),
max_steps = c(2500, 500)
),
sample = 1,
echo = FALSE
)
})
expect_equal(nrow(runs), 4)
})
test_that("tuning_run can correctly handle different types of inputs for flags", {
grid <- expand.grid(
learning_rate = c(0.01, 0.02),
max_steps = c(2500, 500, 99)
)
runs <- with_tests_dir(tuning_run("write_run_data.R",
confirm = FALSE, flags = grid
))
expect_equal(nrow(runs), 6)
expect_error(
with_tests_dir(tuning_run("write_run_data.R", confirm = FALSE),
"flags must be specified as a named list"
))
expect_error(
tuning_run("write_run_data.R",
confirm = FALSE,
flags = list(c(0.01, 0.02), c(2500, 500))
),
"as a named list"
)
})
runs_dirs <- with_tests_dir(normalizePath(list.dirs("runs", recursive = FALSE)))
unlink(runs_dirs, recursive = TRUE) |
ipta <- function(x = x, y = y, Monthly = Monthly){
df <- cbind.data.frame(x, y, Monthly)
d <- rbind.data.frame(df, df[1, ])
distance = sqrt(diff(d$x)^2 + diff(d$y)^2)
slope = diff(d$y) / diff(d$x)
plot(d$x, d$y, pch = 19, type = "b", main = "Innovative Polygon Trend Analysis",
xlab = "First half", ylab = "Second half", xlim = c(min(d$x),max(d$x)),
ylim = c(min(d$y),max(d$y)))
text(x = d$x, y = d$y, labels = df$Monthly,
cex=0.8, pos=3,col="black")
abline(a = 0, b = 1, col = "black", lwd = 2)
return(list("Distance" = distance, "Slope" = slope))
} |
context("Results for derived statistics")
elements <- 1:10
total <- length(elements)
detectedH1 <- c(1:4, 8,9)
trueH1 <- 1:5
test_that("derived statistics are correct", {
expect_equal(ebc_TPR(detectedH1, trueH1), 4 / 5)
expect_equal(ebc_TNR(detectedH1, trueH1, elements), 3 / 5)
expect_equal(ebc_TNR(detectedH1, trueH1, m = total), 3 / 5)
expect_equal(ebc_PPV(detectedH1, trueH1), 2 / 3)
expect_equal(ebc_NPV(detectedH1, trueH1, elements), 3 / 4)
expect_equal(ebc_NPV(detectedH1, trueH1, m = total), 3 / 4)
expect_equal(ebc_FNR(detectedH1, trueH1), 1 / 5)
expect_equal(ebc_FPR(detectedH1, trueH1, elements), 2 / 5)
expect_equal(ebc_FPR(detectedH1, trueH1, m = total), 2 / 5)
expect_equal(ebc_FDR(detectedH1, trueH1), 1 / 3)
expect_equal(ebc_FOR(detectedH1, trueH1, elements), 1 / 4)
expect_equal(ebc_FOR(detectedH1, trueH1, m = total), 1 / 4)
expect_equal(ebc_ACC(detectedH1, trueH1, elements), 7 / 10)
expect_equal(ebc_ACC(detectedH1, trueH1, m = total), 7 / 10)
expect_equal(ebc_BACC(detectedH1, trueH1, elements), 7 / 10)
expect_equal(ebc_BACC(detectedH1, trueH1, m = total), 7 / 10)
expect_equal(ebc_F1(detectedH1, trueH1), 8 / 11)
expect_equal(ebc_PLR(detectedH1, trueH1, elements), 2)
expect_equal(ebc_PLR(detectedH1, trueH1, m = total), 2)
expect_equal(ebc_NLR(detectedH1, trueH1, elements), 1 / 3)
expect_equal(ebc_NLR(detectedH1, trueH1, m = total), 1 / 3)
expect_equal(ebc_DOR(detectedH1, trueH1, elements), 6)
expect_equal(ebc_DOR(detectedH1, trueH1, m = total), 6)
})
detectedH1 <- sample(letters, 14)
trueH1 <- sample(letters, 15)
test_that("relations between statistics are correct", {
expect_equal(ebc_TPR(detectedH1, trueH1),
1 - ebc_FNR(detectedH1, trueH1))
expect_equal(ebc_TNR(detectedH1, trueH1, letters),
1 - ebc_FPR(detectedH1, trueH1, letters))
expect_equal(ebc_PPV(detectedH1, trueH1),
1 - ebc_FDR(detectedH1, trueH1))
expect_equal(ebc_NPV(detectedH1, trueH1, letters),
1 - ebc_FOR(detectedH1, trueH1, letters))
expect_equal(ebc_F1(detectedH1, trueH1),
2 / ((1 / ebc_TPR(detectedH1, trueH1)) +
1 / ebc_PPV(detectedH1, trueH1)))
expect_equal(ebc_DOR(detectedH1, trueH1, letters),
ebc_PLR(detectedH1, trueH1, letters) /
ebc_NLR(detectedH1, trueH1, letters))
}) |
library(hansard)
context("research_briefings")
test_that("research_briefings return expected format", {
skip_on_cran()
skip_on_travis()
rtl <- hansard_research_topics_list()
expect_is(rtl, "list")
rsl <- hansard_research_subtopics_list()
expect_is(rsl, "list")
rtyl <- hansard_research_types_list()
expect_is(rtyl, "list")
rbdf <- hansard_research_briefings(
subtopic = "Falkland Islands",
verbose = TRUE
)
expect_length(rbdf, 14)
expect_true(tibble::is_tibble(rbdf))
rbtsb <- hansard_research_briefings(
topic = "Defence",
subtopic = "Falkland Islands",
verbose = TRUE
)
expect_true(tibble::is_tibble(rbtsb))
expect_true(rbdf[[1]][[1]] == rbtsb[[1]][[1]])
}) |
m2Set <-
function (v=c(0)) {
nv<-list();k<-0;
for (i in 1:length( v ) ) for (j in 1:length(v[[i]][[1]]))
if (!is.element( list(c(v[[i]][[1]][[j]])), nv) )
{ k<-k+1; nv[[k]]<-v[[i]][[1]][[j]]; }
return(nv);
} |
monmlp.reshape <-
function(x, y, weights, hidden1, hidden2)
{
N11 <- ncol(x)+1
N12 <- hidden1
N1 <- N11*N12
W1 <- weights[1:N1]
W1 <- matrix(W1, N11, N12)
if (hidden2==0){
N21 <- hidden1+1
N22 <- ncol(y)
N2 <- N1 + N21*N22
W2 <- weights[(N1+1):N2]
W2 <- matrix(W2, N21, N22)
W.list <- list(W1=W1, W2=W2)
} else{
N21 <- hidden1+1
N22 <- hidden2
N2 <- N1 + N21*N22
W2 <- weights[(N1+1):N2]
W2 <- matrix(W2, N21, N22)
N31 <- hidden2+1
N32 <- ncol(y)
N3 <- N2 + N31*N32
W3 <- weights[(N2+1):N3]
W3 <- matrix(W3, N31, N32)
W.list <- list(W1=W1, W2=W2, W3=W3)
}
W.list
} |
random.active.test <- function( x.b, x.g, k=length(x.b), segments=NULL,
max.iter=2000, eps=0.001 )
{
if ( missing( x.b ) )
stop( "argument 'x.b' is missing" )
if ( !is.vector( x.b ) )
stop( "argument 'x.b' is not a vector" )
if ( !is.numeric( x.b ) )
stop( "argument 'x.b' is not a numeric vector" )
n <- length( x.b )
if ( n == 1 )
stop( "Argument 'x.b' must be of length greater than 1" )
if ( missing( x.g ) )
stop( "argument 'x.g' is missing" )
if ( x.g <= 0 )
stop( "argument x.g is not positive" )
if ( !is.null( segments ) ) {
activeInvestments <- collapse.segments( segments )
numberInvestments <- length( activeInvestments )
if ( numberInvestments > n || max( activeInvestments ) > n )
stop( "argument 'segments' has investments that are not allowed" )
thisResult <- random.active.test( x.b[activeInvestments], x.g,
k=numberInvestments, segments=NULL,max.iter, eps )
weights <- thisResult$x
iter <- thisResult$iter
passiveInvestments <- segment.complement( n, activeInvestments )
x.a <- rep( 0, n )
x.p <- rep( 0, n )
x.a[activeInvestments] <- weights
x.p[passiveInvestments] <- x.b[passiveInvestments]
x <- x.a + x.p
result <- list( x=x, iter=iter )
return( result )
}
if ( k < n ) {
if ( k < 2 )
stop( "argument 'k' is less than two" )
allInvestments <- 1:n
activeInvestments <- sample( allInvestments, k, replace=FALSE )
thisResult <- random.active.test( x.b[activeInvestments], x.g, k,
segments=NULL, max.iter, eps )
weights <- thisResult$x
iter <- thisResult$iter
passiveInvestments <- segment.complement( n, activeInvestments )
x.a <- rep( 0, n )
x.p <- rep( 0, n )
x.a[activeInvestments] <- weights
x.p[passiveInvestments] <- x.b[passiveInvestments]
x <- x.a + x.p
result <- list( x=x, iter=iter )
return( result )
}
if ( k > n )
stop( "argument 'k' is greater than the number of benchmark investments" )
x.t.b <- sum( x.b )
x.t.long <- x.g * x.t.b / 2
x.t.short <- x.t.long
thisResult <- random.longshort.test( n, k, segments, x.t.long,
x.t.short, max.iter, eps )
x.ls <- thisResult$x
iter <- thisResult$iter
x <- x.b + x.ls
result <- list( x=x, iter=iter )
return( result )
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.