code
stringlengths 1
13.8M
|
---|
ate <- function(event,
treatment,
censor = NULL,
data,
data.index = NULL,
formula,
estimator = NULL,
strata = NULL,
contrasts = NULL,
allContrasts = NULL,
times,
cause = NA,
landmark,
se = TRUE,
iid = (B == 0) && (se || band),
known.nuisance = FALSE,
band = FALSE,
B = 0,
seed,
handler = "foreach",
mc.cores = 1,
cl = NULL,
verbose = TRUE,
...){
dots <- list(...)
call <- match.call()
if(is.data.table(data)){
data <- data.table::copy(data)
}else{
data <- data.table::as.data.table(data)
}
init <- ate_initArgs(object.event = event,
object.treatment = treatment,
object.censor = censor,
formula = formula,
landmark = landmark,
mydata = data,
data.index = data.index,
estimator = estimator,
times = times,
cause = cause,
handler = handler,
product.limit = dots$product.limit,
store.iid = dots$store.iid)
object.event <- init$object.event
object.treatment <- init$object.treatment
object.censor <- init$object.censor
data.index <- init$data.index
times <- init$times
handler <- init$handler
formula <- init$formula
landmark <- init$landmark
treatment <- init$treatment
cause <- init$cause
estimator <- init$estimator
fct.pointEstimate <- init$fct.pointEstimate
n.obs <- init$n.obs
n.censor <- init$n.censor
eventVar.time <- init$eventVar.time
eventVar.status <- init$eventVar.status
level.censoring <- init$level.censoring
level.states <- init$level.states
censorVar.time <- init$censorVar.time
censorVar.status <- init$censorVar.status
dots$product.limit <- init$product.limit
store.iid <- init$store.iid
return.iid.nuisance <- (se || band || iid) && (B==0) && (known.nuisance == FALSE)
if("method.iid" %in% names(dots)){
method.iid <- dots$method.iid
dots$method.iid <- NULL
}else{
method.iid <- 1
}
check <- ate_checkArgs(call = call,
object.event = object.event,
object.censor = object.censor,
object.treatment = object.treatment,
mydata = data,
formula = formula,
treatment = treatment,
strata = strata,
contrasts = contrasts,
allContrasts = allContrasts,
times = times,
cause = cause,
landmark = landmark,
se = se,
iid = iid,
data.index = data.index,
return.iid.nuisance = return.iid.nuisance,
band = band,
B = B,
seed = seed,
handler = handler,
mc.cores = mc.cores,
cl = cl,
verbose = verbose,
n.censor = n.censor,
level.censoring = level.censoring,
level.states = level.states,
estimator = estimator,
eventVar.time = eventVar.time,
eventVar.status = eventVar.status,
censorVar.time = censorVar.time,
censorVar.status = censorVar.status,
n.obs = n.obs
)
testE.Cox <- inherits(object.event,"coxph") || inherits(object.event,"cph") || inherits(object.event,"phreg")
testE.CSC <- inherits(object.event,"CauseSpecificCox")
testE.glm <- inherits(object.event,"glm")
if(!is.null(strata)){
if(!is.factor(data[[strata]])){
data[[strata]] <- factor(data[[strata]])
}
if(is.null(contrasts)){
contrasts <- levels(data[[strata]])
}
levels <- levels(data[[strata]])
}else{
if(!is.factor(data[[treatment]])){
data[[treatment]] <- factor(data[[treatment]])
}
if(is.null(contrasts)){
contrasts <- levels(data[[treatment]])
}
levels <- levels(data[[treatment]])
}
if(is.null(allContrasts)){
allContrasts <- utils::combn(contrasts, m = 2)
}else if(any(contrasts %in% allContrasts == FALSE)){
contrasts <- contrasts[contrasts %in% allContrasts]
}
out <- list(meanRisk = NULL,
diffRisk = NULL,
ratioRisk = NULL,
iid = NULL,
boot = NULL,
estimator = estimator,
eval.times = times,
n = n.obs,
variables = c(time = eventVar.time, event = eventVar.status,
treatment = if(is.null(treatment)){NA}else{treatment},
strata = if(is.null(strata)){NA}else{strata}),
theCause = cause,
contrasts = contrasts,
allContrasts = allContrasts,
computation.time = list("point" = NA, "iid" = NA, "bootstrap" = NA),
inference = data.frame("se" = se, "iid" = iid, "band" = band, "bootstrap" = B>0, "ci" = FALSE, "p.value" = FALSE,
"conf.level" = NA, "alternative" = NA,
"bootci.method" = NA, "n.bootstrap" = if(B>0){B}else{NA},
"method.band" = NA, "n.sim" = NA)
)
attr(out$theCause,"cause") <- level.states
attr(out$theCause,"level.censoring") <- level.censoring
if(!is.na(eventVar.time)){
attr(out$variables,"range.time") <- range(data[[eventVar.time]])
if(!is.null(strata)){
var.group <- strata
}else{
var.group <- treatment
}
if(attr(estimator,"TD")){
attr(out$eval.times,"n.at.risk") <- dcast(cbind(times = paste0(times,"+",landmark),
data[data[[var.group]] %in% contrasts,
list(pc = sapply(times+landmark, function(t){sum(.SD[[eventVar.time]]>=t)})), by = var.group]),
value.var = "pc", formula = as.formula(paste0(var.group,"~times")))
}else{
attr(out$eval.times,"n.at.risk") <- dcast(cbind(times = times,
data[data[[var.group]] %in% contrasts,
list(pc = sapply(times, function(t){sum(.SD[[eventVar.time]]>=t)})), by = var.group]),
value.var = "pc", formula = as.formula(paste0(var.group,"~times")))
}
}
attr(out$eval.times,"n.censored") <- n.censor
class(out) <- c("ate")
if(verbose>1/2){
print(out)
cat("\n Processing\n")
}
if(return.iid.nuisance){
if(verbose>1/2){
cat(" - Prepare influence function:")
}
if(attr(estimator,"GFORMULA") && (testE.Cox || testE.CSC) && identical(is.iidCox(object.event),FALSE)){
if(verbose>1/2){cat(" outcome")}
object.event <- iidCox(object.event, tau.max = max(times), store.iid = store.iid, return.object = TRUE)
}
if(attr(estimator,"IPCW")){
if(identical(is.iidCox(object.censor),FALSE)){
if(verbose>1/2){cat(" censoring")}
object.censor <- iidCox(object.censor, store.iid = store.iid, tau.max = max(times))
}
}
if(verbose>1/2){cat(" done \n")}
}
if(verbose>1/2){
cat(" - Point estimation:")
}
args.pointEstimate <- c(list(object.event = object.event,
object.censor = object.censor,
object.treatment = object.treatment,
mydata=data,
treatment=treatment,
strata=strata,
contrasts=contrasts,
allContrasts=allContrasts,
levels=levels,
times=times,
cause=cause,
landmark=landmark,
n.censor = n.censor,
level.censoring = level.censoring,
estimator = estimator,
eventVar.time = eventVar.time,
eventVar.status = eventVar.status,
censorVar.time = censorVar.time,
censorVar.status = censorVar.status,
return.iid.nuisance = return.iid.nuisance,
data.index = data.index,
method.iid = method.iid),
dots)
if (attr(estimator,"TD")){
args.pointEstimate <- c(args.pointEstimate,list(formula=formula))
}
tps1 <- Sys.time()
pointEstimate <- do.call(fct.pointEstimate, args.pointEstimate)
tps2 <- Sys.time()
out$meanRisk <- pointEstimate$meanRisk
out$diffRisk <- pointEstimate$diffRisk
out$ratioRisk <- pointEstimate$ratioRisk
out$computation.time[["point"]] <- tps2-tps1
if(verbose>1/2){cat(" done \n")}
if(se || band || iid){
if (attr(estimator,"TD")){
key1 <- c("treatment","landmark")
key2 <- c("treatment.A","treatment.B","landmark")
}
else{
key1 <- c("treatment","time")
key2 <- c("treatment.A","treatment.B","time")
}
if(B>0){
if (verbose>1/2){
cat(" - Non-parametric bootstrap using ",B," samples and ",mc.cores," core",if(mc.cores>1){"s"},"\n", sep ="")
cat(" (expected time: ",round(as.numeric(out$computation.time$point)*B/mc.cores,2)," seconds)\n", sep = "")
}
name.estimate <- c(paste("mean",out$meanRisk$estimator,out$meanRisk$time,out$meanRisk$landmark,out$meanRisk$treatment,sep="."),
paste("difference",out$diffRisk$estimator,out$diffRisk$time,out$diffRisk$landmark,out$diffRisk$A,out$diffRisk$B,sep="."),
paste("ratio",out$ratioRisk$estimator,out$ratioRisk$time,out$ratioRisk$landmark,out$ratioRisk$A,out$ratioRisk$B,sep="."))
estimate <- setNames(c(out$meanRisk$estimate,out$diffRisk$estimate,out$ratioRisk$estimate), name.estimate)
resBoot <- calcBootATE(args = args.pointEstimate,
n.obs = n.obs["data"],
fct.pointEstimate = fct.pointEstimate,
name.estimate = name.estimate,
handler = handler,
B = B,
seed = seed,
mc.cores = mc.cores,
cl = cl,
verbose = verbose)
out$boot <- list(t0 = estimate,
t = resBoot$boot,
R = B,
data = data,
seed = resBoot$bootseeds,
statistic = NULL,
sim = "ordinary",
call = quote(boot(data = XX, statistic = XX, R = XX)),
stype = "i",
strata = rep(1,n.obs["data"]),
weights = rep(1/n.obs["data"],n.obs["data"]),
pred.i = NULL,
L = NULL,
ran.gen = NULL,
mle = NULL
)
class(out$boot) <- "boot"
tps3 <- Sys.time()
out$computation.time[["bootstrap"]] <- tps3-tps2
if (verbose>1/2){
cat("\n")
}
} else {
if (verbose>1/2){
cat(" - Decomposition iid: ")
}
if(return.iid.nuisance && (attr(estimator,"IPTW") == TRUE)){
args.pointEstimate[names(pointEstimate$store)] <- pointEstimate$store
if(identical(method.iid,2)){
out$iid <- do.call(iidATE2, args.pointEstimate)
}else{
out$iid <- do.call(iidATE, args.pointEstimate)
}
}else{
out$iid <- list(GFORMULA = pointEstimate$store$iid.GFORMULA,
IPTW = pointEstimate$store$iid.IPTW,
AIPTW = pointEstimate$store$iid.AIPTW)
}
tps3 <- Sys.time()
out$computation.time[["iid"]] <- tps3-tps2
if (verbose>1/2){
cat("done\n")
}
}
}
if(se || band){
if (verbose>1/2){
if(se && band){
cat(" - Confidence intervals / bands: ")
}else if(se){
cat(" - Confidence intervals: ")
}else if(band){
cat(" - Confidence bands: ")
}
}
out[c("meanRisk","diffRisk","ratioRisk","inference","inference.allContrasts","inference.contrasts","transform")] <- stats::confint(out, p.value = TRUE)
if(iid == FALSE){
out$iid <- NULL
}
if (verbose>1/2){
cat("done\n")
}
}
return(out)
}
ate_initArgs <- function(object.event,
object.treatment,
object.censor,
landmark,
formula,
estimator,
mydata,
data.index,
cause,
times,
handler,
product.limit,
store.iid){
handler <- match.arg(handler, c("foreach","mclapply","snow","multicore"))
if(is.null(data.index)){data.index <- 1:NROW(mydata)}
if(missing(object.event)){
formula.event <- NULL
model.event <- NULL
}else if(inherits(object.event,"formula")){
formula.event <- object.event
if(any(grepl("Hist(",object.event, fixed = TRUE))){
model.event <- do.call(CSC, args = list(formula = object.event, data = mydata))
}else if(any(grepl("Surv(",object.event, fixed = TRUE))){
model.event <- do.call(rms::cph, args = list(formula = object.event, data = mydata, x = TRUE, y = TRUE))
}else{
model.event <- do.call(stats::glm, args = list(formula = object.event, data = mydata, family = stats::binomial(link = "logit")))
}
}else if(is.list(object.event) && all(sapply(object.event, function(iE){inherits(iE,"formula")}))){
formula.event <- object.event
model.event <- CSC(object.event, data = mydata)
}else if(inherits(object.event,"glm") ||inherits(object.event,"wglm") || inherits(object.event,"CauseSpecificCox")){
formula.event <- stats::formula(object.event)
model.event <- object.event
}else if(inherits(object.event,"coxph") || inherits(object.event,"cph") ||inherits(object.event,"phreg")){
formula.event <- coxFormula(object.event)
model.event <- object.event
}else{
formula.event <- NULL
model.event <- NULL
}
if(missing(object.treatment)){
formula.treatment <- NULL
model.treatment <- NULL
}else if(inherits(object.treatment,"formula")){
model.treatment <- do.call(stats::glm, args = list(formula = object.treatment, data = mydata, family = stats::binomial(link = "logit")))
formula.treatment <- object.treatment
}else if(inherits(object.treatment,"glm") || inherits(object.treatment,"nnet")){
formula.treatment <- stats::formula(object.treatment)
model.treatment <- object.treatment
}else{
formula.treatment <- NULL
model.treatment <- NULL
}
if(missing(object.censor)){
formula.censor <- NULL
model.censor <- NULL
}else if(inherits(object.censor,"formula")){
formula.censor <- object.censor
model.censor <- do.call(rms::cph, args = list(formula = object.censor, data = mydata, x = TRUE, y = TRUE))
}else if(inherits(object.censor,"coxph") || inherits(object.censor,"cph") || inherits(object.censor,"phreg")){
formula.censor <- coxFormula(object.censor)
model.censor <- object.censor
}else{
formula.censor <- NULL
model.censor <- NULL
}
if(missing(times) && (inherits(model.event,"glm") || (inherits(model.treatment,"glm") && is.null(model.event) && is.null(model.censor)))){
times <- NA
}
if(inherits(model.censor,"coxph") || inherits(model.censor,"cph") || inherits(model.censor,"phreg")){
censoringMF <- coxModelFrame(model.censor)
test.censor <- censoringMF$status == 1
n.censor <- sapply(times, function(t){sum(test.censor * (censoringMF$stop <= t))})
info.censor <- SurvResponseVar(coxFormula(model.censor))
censorVar.status <- info.censor$status
censorVar.time <- info.censor$time
level.censoring <- unique(mydata[[censorVar.status]][model.censor$y[,2]==1])
}else{
censorVar.status <- NA
censorVar.time <- NA
if(inherits(model.event,"CauseSpecificCox")){
test.censor <- model.event$response[,"status"] == 0
n.censor <- sapply(times, function(t){sum(test.censor * (model.event$response[,"time"] <= t))})
level.censoring <- attr(model.event$response,"cens.code")
}else if(inherits(model.event,"coxph") || inherits(model.event,"cph") || inherits(model.event,"phreg")){
censoringMF <- coxModelFrame(model.event)
test.censor <- censoringMF$status == 0
n.censor <- sapply(times, function(t){sum(test.censor * (censoringMF$stop <= t))})
level.censoring <- 0
}else if(inherits(model.event,"wglm")){
n.censor <- object.event$n.censor
level.censoring <- setdiff(unique(object.event$data[[object.event$var.outcome]]), object.event$causes)
}else{
n.censor <- rep(0,length(times))
}
if(all(n.censor==0)){level.censoring <- NA}
}
if(missing(object.treatment) || is.null(object.treatment)){
treatment <- NULL
}else if(!is.null(formula.treatment)){
treatment <- all.vars(formula.treatment)[1]
}else if(is.character(object.treatment)){
treatment <- object.treatment
}
if(inherits(model.event,"CauseSpecificCox")){
responseVar <- SurvResponseVar(formula.event)
eventVar.time <- responseVar$time
eventVar.status <- responseVar$status
if(is.na(cause)){
cause <- model.event$theCause
}
if(is.null(product.limit)){product.limit <- TRUE}
level.states <- model.event$cause
}else if(inherits(model.event,"coxph") || inherits(model.event,"cph") || inherits(model.event,"phreg")){
responseVar <- SurvResponseVar(formula.event)
eventVar.time <- responseVar$time
eventVar.status <- responseVar$status
if(is.na(cause)){
if(any(model.event$y[,NCOL(model.event$y)]==1)){
modeldata <- try(eval(model.event$call$data), silent = TRUE)
if(inherits(modeldata,"try-error")){
cause <- unique(mydata[[eventVar.status]][model.event$y[,NCOL(model.event$y)]==1])
}else{
cause <- unique(modeldata[[eventVar.status]][model.event$y[,NCOL(model.event$y)]==1])
}
}
}
if(is.null(product.limit)){product.limit <- FALSE}
level.states <- 1
}else if(inherits(model.event,"glm")){
eventVar.time <- as.character(NA)
eventVar.status <- all.vars(formula.event)[1]
if(is.na(cause)){
cause <- unique(stats::model.frame(model.event)[[eventVar.status]][model.event$y==1])
}else{
cause <- NA
}
if(is.null(product.limit)){product.limit <- FALSE}
level.states <- unique(mydata[[eventVar.status]])
}else if(inherits(object.event,"wglm")){
eventVar.time <- object.event$var.time
eventVar.status <- object.event$var.outcome
if(is.na(cause)){
cause <- object.event$theCause
}
level.states <- object.event$causes
if(is.null(product.limit)){product.limit <- (length(level.states)>1)}
}else{
if(identical(names(object.event),c("time","status"))){
eventVar.time <- object.event[1]
eventVar.status <- object.event[2]
}else if(identical(names(object.event),c("status","time"))){
eventVar.status <- object.event[1]
eventVar.time <- object.event[2]
}else if(length(object.event)==2){
eventVar.time <- object.event[1]
eventVar.status <- object.event[2]
}else if(length(object.event)==1){
eventVar.time <- NA
eventVar.status <- object.event[1]
if(is.na(cause)){
if(any(mydata[[eventVar.status]] %in% 0:2 == FALSE)){
stop("The event variable must be an integer variable taking value 0, 1, or 2. \n")
}
cause <- 1
}
}
level.states <- setdiff(unique(mydata[[eventVar.status]]), level.censoring)
if(is.na(cause)){
cause <- sort(level.states)[1]
}
if(is.null(product.limit)){product.limit <- FALSE}
}
TD <- switch(class(object.event)[[1]],
"coxph"=(attr(object.event$y,"type")=="counting"),
"CauseSpecificCox"=(attr(object.event$models[[1]]$y,"type")=="counting"),
FALSE)
if(TD){
fct.pointEstimate <- ATE_TD
}else{
landmark <- NULL
formula <- NULL
fct.pointEstimate <- ATE_TI
}
if(is.null(estimator)){
if(!is.null(model.event) && is.null(model.treatment)){
if(TD){
estimator <- "GFORMULATD"
}else{
estimator <- "GFORMULA"
}
}else if(is.null(model.event) && !is.null(model.treatment)){
if(any(n.censor>0)){
estimator <- "IPTW,IPCW"
}else{
estimator <- "IPTW"
}
}else if(!is.null(model.event) && !is.null(model.treatment)){
if(any(n.censor>0)){
estimator <- "AIPTW,AIPCW"
}else{
estimator <- "AIPTW"
}
}else{
estimator <- NA
}
test.monotone <- FALSE
}else{
estimator <- toupper(estimator)
mestimator <- estimator
estimator <- gsub("MONOTONE","",estimator)
index.westimator <- which(estimator %in% c("IPTW","IPTW,IPCW","AIPTW","AIPTW,AIPCW"))
if(length(index.westimator)>0){
test.monotone <- unique(grepl(pattern = "MONOTONE",mestimator[index.westimator]))
}else{
test.monotone <- FALSE
}
if(any(estimator == "IPTW") && any(n.censor>0)){
estimator[estimator == "IPTW"] <- "IPTW,IPCW"
}
if(any(estimator == "AIPTW") && any(n.censor>0)){
estimator[estimator == "AIPTW"] <- "AIPTW,AIPCW"
}
if(any(estimator == "G-FORMULA")){
estimator[estimator == "G-FORMULA"] <- "GFORMULA"
}
if(any(estimator == "G-FORMULATD")){
estimator[estimator == "G-FORMULATD"] <- "GFORMULA"
}
}
estimator.output <- unname(sapply(estimator, switch,
"GFORMULA" = "GFORMULA",
"GFORMULATD" = "GFORMULA",
"IPTW" = "IPTW",
"IPTW,IPCW" = "IPTW",
"AIPTW" = "AIPTW",
"AIPTW,AIPCW" = "AIPTW"
))
if(TD){
attr(estimator.output,"TD") <- TRUE
}else{
attr(estimator.output,"TD") <- FALSE
}
if(any(estimator %in% c("GFORMULA","GFORMULATD","AIPTW","AIPTW,AIPCW"))){
attr(estimator.output,"GFORMULA") <- TRUE
}else{
attr(estimator.output,"GFORMULA") <- FALSE
}
if(any(estimator %in% c("IPTW","IPTW,IPCW","AIPTW","AIPTW,AIPCW"))){
attr(estimator.output,"IPTW") <- TRUE
}else{
attr(estimator.output,"IPTW") <- FALSE
}
if(any(estimator %in% c("IPTW,IPCW","AIPTW,AIPCW"))){
attr(estimator.output,"IPCW") <- TRUE
}else{
attr(estimator.output,"IPCW") <- FALSE
}
if(any(estimator %in% c("AIPTW,AIPCW"))){
attr(estimator.output,"integral") <- !inherits(object.event,"wglm")
}else{
attr(estimator.output,"integral") <- FALSE
}
if(any(estimator %in% c("AIPTW","AIPTW,AIPCW"))){
attr(estimator.output,"augmented") <- TRUE
}else{
attr(estimator.output,"augmented") <- FALSE
}
if(any(estimator %in% c("GFORMULA","GFORMULATD"))){
attr(estimator.output,"export.GFORMULA") <- TRUE
}else{
attr(estimator.output,"export.GFORMULA") <- FALSE
}
if(any(estimator %in% c("IPTW","IPTW,IPCW"))){
attr(estimator.output,"export.IPTW") <- TRUE
}else{
attr(estimator.output,"export.IPTW") <- FALSE
}
if(any(estimator %in% c("AIPTW","AIPTW,AIPCW"))){
attr(estimator.output,"export.AIPTW") <- TRUE
}else{
attr(estimator.output,"export.AIPTW") <- FALSE
}
attr(estimator.output,"full") <- estimator
attr(estimator.output,"monotone") <- test.monotone
n.obs <- c(data = NROW(mydata),
model.event = if(!is.null(model.event)){stats::nobs(model.event)}else{NA},
model.treatment = if(!is.null(model.treatment)){stats::nobs(model.treatment)}else{NA},
model.censor = if(!is.null(model.censor)){coxN(model.censor)}else{NA}
)
if(is.null(store.iid)){
store.iid <- "minimal"
}
return(list(object.event = model.event,
object.treatment = model.treatment,
object.censor = model.censor,
times = times,
handler = handler,
estimator = estimator.output,
formula = formula,
landmark = landmark,
fct.pointEstimate = fct.pointEstimate,
n.obs = n.obs,
n.censor = n.censor,
treatment = treatment,
cause = cause,
level.censoring = level.censoring,
level.states = level.states,
eventVar.time = eventVar.time,
eventVar.status = eventVar.status,
censorVar.time = censorVar.time,
censorVar.status = censorVar.status,
product.limit = product.limit,
data.index = data.index,
store.iid = store.iid
))
}
ate_checkArgs <- function(call,
object.event,
object.treatment,
object.censor,
mydata,
formula,
treatment,
strata,
contrasts,
allContrasts,
times,
cause,
landmark,
se,
iid,
data.index,
return.iid.nuisance,
band,
B,
confint,
seed,
handler,
mc.cores,
cl,
verbose,
n.censor,
level.censoring,
level.states,
estimator,
eventVar.time,
eventVar.status,
censorVar.time,
censorVar.status,
n.obs){
options <- riskRegression.options()
if(inherits(object.event,"glm") && length(times)!=1){
stop("Argument \'times\' has no effect when using a glm object \n",
"It should be set to NA \n")
}
if(eventVar.status %in% names(mydata) == FALSE){
stop("The data set does not seem to have a variable ",eventVar.status," (argument: event[2]). \n")
}
if(inherits(object.event,"glm") && is.na(cause)){
stop("Argument \'cause\' should not be specified when using a glm model in argument \'event\'")
}
if(length(cause)>1 || is.na(cause)){
stop("Cannot guess which value of the variable \"",eventVar.status,"\" corresponds to the outcome of interest \n",
"Please specify the argument \'cause\'. \n")
}
if(cause %in% mydata[[eventVar.status]] == FALSE){
stop("Value of the argument \'cause\' not found in column \"",eventVar.status,"\" \n")
}
if(any(is.na(estimator))){
stop("No model for the outcome/treatment/censoring has been specified. Cannot estimate the average treatment effect. \n")
}
valid.estimator <- c("GFORMULA","IPTW,IPCW","IPTW","AIPTW,AIPCW","AIPTW")
if(any(estimator %in% valid.estimator == FALSE)){
stop("Incorrect value(s) for argument \'estimator\': \"",paste(estimator[estimator %in% valid.estimator == FALSE], collapse = "\" \""),"\"\n",
"Valid values: \"G-formula\", \"IPTW\", \"AIPTW\" \n")
}
if(attr(estimator,"GFORMULA")){
if(is.null(object.event)){
stop("Using a G-formula/AIPTW estimator requires to specify a model for the outcome (argument \'event\') \n")
}
}
if(attr(estimator,"IPTW")){
if(is.null(object.treatment)){
stop("Using a ITPW/AIPTW estimator requires to specify a model for the treatment allocation (argument \'treatment\') \n")
}
}
if(attr(estimator,"IPCW")){
if(is.null(object.censor)){
stop("Using a ITPW/AIPTW estimator requires to specify a model for the censoring mechanism (argument \'censor\') in presence of right-censoring \n")
}
}
if(length(attr(estimator,"monotone"))>1){
stop("monotonicity constrain should be request for all or none of the IPW estimators \n")
}
if(!is.null(object.event)){
candidateMethods <- paste("predictRisk",class(object.event),sep=".")
if (all(match(candidateMethods,options$method.predictRisk,nomatch=0)==0)){
stop(paste("Could not find predictRisk S3-method for ",class(object.event),collapse=" ,"),sep="")
}
if((inherits(object.event,"wglm") || inherits(object.event,"CauseSpecificCox")) && (cause %in% object.event$causes == FALSE)){
stop("Argument \'cause\' does not match one of the available causes: ",paste(object.event$causes,collapse=" "),"\n")
}
if(inherits(object.event,"wglm") && (cause != object.event$theCause)){
stop("Argument \'cause\' does not match the one of \'object.event\' \n",
"Consider re-fitting the model with appropriate cause.")
}
if(any(is.na(level.censoring)) && any(na.omit(level.censoring) == cause)){
stop("The cause of interest must differ from the level indicating censoring (in the outcome model) \n")
}
if(any(is.na(coef(object.event)))){
stop("Cannot handle missing values in the model coefficients (event) \n")
}
if(!is.null(treatment) && identical(eventVar.status, treatment)){
stop("The treatment variable has the same name as the event variable. \n")
}
}
if(!is.null(object.treatment)){
if(!inherits(object.treatment,"multinom") && (!inherits(object.treatment,"glm") || object.treatment$family$family!="binomial")){
stop("Argument \'treatment\' must be a logistic regression (glm object) or a multinomial regression (nnet::multinom)\n",
" or a character variable giving the name of the treatment variable. \n")
}
if(any(levels(mydata[[treatment]]) %in% mydata[[treatment]] == FALSE)){
mistreat <- levels(mydata[[treatment]])[levels(mydata[[treatment]]) %in% mydata[[treatment]] == FALSE]
stop("Argument \'mydata\' needs to take all possible treatment values when using IPTW/AIPTW \n",
"missing treatment values: \"",paste(mistreat,collapse="\" \""),"\"\n")
}
if(any(is.na(coef(object.treatment)))){
stop("Cannot handle missing values in the model coefficients (object.treatment) \n")
}
if(inherits(object.treatment,"glm") && object.treatment$family$family == "binomial" && length(unique(mydata[[treatment]]))>2){
stop("Cannot use a logistic regression in argument \"treatment\" when there are more than two treatment categories \n",
"Consider subsetting the dataset to have only two treatment categories or using a multinomial regression (nnet::multinom).")
}
}
if(attr(estimator,"IPCW")){
if(!inherits(object.censor,"coxph") && !inherits(object.censor,"cph") && !inherits(object.censor,"phreg")){
stop("Argument \'object.censor\' must be a Cox model \n")
}
if(inherits(object.event,"glm") && any(n.censor > 0) && all(object.event$prior.weights==1)){
stop("Argument \'object.event\' should not be a standard logistic regression in presence of censoring \n")
}
if(!identical(censorVar.time,eventVar.time)){
stop("The time variable should be the same in \'object.event\' and \'object.censor\' \n")
}
if(any(cause == level.censoring)){
stop("The level indicating censoring should differ between the outcome model and the censoring model \n",
"maybe you have forgotten to set the event type == 0 in the censoring model \n")
}
if(!identical(censorVar.status,eventVar.status)){
if(sum(diag(table(mydata[[censorVar.status]] == level.censoring, mydata[[eventVar.status]] %in% level.states == FALSE)))!=NROW(mydata)){
stop("The status variables in object.event and object.censor are inconsistent \n")
}
}
if(any(is.na(coef(object.censor)))){
stop("Cannot handle missing values in the model coefficients (object.treatment) \n")
}
}
if(B>0){
if(se==FALSE){
warning("Argument 'se=0' means 'no standard errors' so number of bootstrap repetitions is forced to B=0.")
}
if(iid==TRUE){
stop("Influence function cannot be computed when using the bootstrap approach \n",
"Either set argument \'iid\' to FALSE to not compute the influence function \n",
"or set argument \'B\' to 0 \n")
}
if(band==TRUE){
stop("Confidence bands cannot be computed when using the bootstrap approach \n",
"Either set argument \'band\' to FALSE to not compute the confidence bands \n",
"or set argument \'B\' to 0 to use the estimate of the asymptotic distribution instead of the bootstrap\n")
}
if(!is.null(object.event) && is.null(object.event$call)){
stop("Argument \'event\' does not contain its own call, which is needed to refit the model in the bootstrap loop.")
}
if(!is.null(object.treatment) && is.null(object.treatment$call)){
stop("Argument \'treatment\' does not contain its own call, which is needed to refit the model in the bootstrap loop.")
}
if(!is.null(object.censor) && is.null(object.censor$call)){
stop("Argument \'censor\' does not contain its own call, which is needed to refit the model in the bootstrap loop.")
}
max.cores <- parallel::detectCores()
if(mc.cores > max.cores){
stop("Not enough available cores \n","available: ",max.cores," | requested: ",mc.cores,"\n")
}
}
if(B==0 && (se|band|iid)){
if(!is.null(landmark)){
stop("Calculation of the standard errors via the functional delta method not implemented for time dependent covariates \n")
}
if(length(unique(stats::na.omit(n.obs[-1])))>1){
stop("Arguments \'",paste(names(stats::na.omit(n.obs[-1])), collapse ="\' "),"\' must be fitted using the same number of observations \n")
}
test.data.index <- any(data.index %in% 1:max(n.obs[-1],na.rm = TRUE) == FALSE)
if(is.null(data.index) || (is.null(call$data.index) && test.data.index)){
stop("Incompatible number of observations between argument \'data\' and the dataset from argument(s) \'",paste(names(stats::na.omit(n.obs[-1])), collapse ="\' "),"\' \n",
"Consider specifying argument \'data.index\' \n \n")
}
if(!is.numeric(data.index) || any(duplicated(data.index)) || any(is.na(data.index)) || test.data.index){
stop("Incorrect specification of argument \'data.index\' \n",
"Must be a vector of integers between 0 and ",max(n.obs[-1],na.rm = TRUE)," \n")
}
if(!is.null(object.event)){
candidateMethods <- paste("predictRiskIID",class(object.event),sep=".")
if (all(match(candidateMethods,options$method.predictRiskIID,nomatch=0)==0)){
stop(paste("Could not find predictRiskIID S3-method for ",class(object.event),collapse=" ,"),"\n",
"Functional delta method not implemented for this type of object \n",
"Set argument \'B\' to a positive integer to use a boostrap instead \n",sep="")
}
}
if(!is.null(object.treatment) && stats::nobs(object.treatment)!=NROW(mydata)){
stop("Argument \'treatment\' must be have been fitted using argument \'data\' for the functional delta method to work\n",
"(discrepancy found in number of rows) \n")
}
if(!is.null(object.censor) && coxN(object.censor)!=NROW(mydata)){
stop("Argument \'censor\' must be have been fitted using argument \'data\' for the functional delta method to work\n",
"(discrepancy found in number of rows) \n")
}
}
if(!is.null(treatment)){
if(treatment %in% names(mydata) == FALSE){
stop("The data set does not seem to have a variable ",treatment," (argument: object.treatment). \n")
}
if(is.numeric(mydata[[treatment]])){
stop("The treatment variable must be a factor variable. \n",
"Convert treatment to factor, re-fit the object using this new variable and then call ate. \n")
}
}else if(is.null(strata)){
stop("The treatment variable must be specified using the argument \'treatment\' \n")
}
if(!is.null(contrasts)){
if(any(contrasts %in% unique(mydata[[treatment]]) == FALSE)){
stop("Incorrect values for the argument \'contrasts\' \n",
"Possible values: \"",paste(unique(mydata[[treatment]]),collapse="\" \""),"\" \n")
}
}
if(!is.null(allContrasts)){
if(any(allContrasts %in% unique(mydata[[treatment]]) == FALSE)){
stop("Incorrect values for the argument \'allContrasts\' \n",
"Possible values: \"",paste(unique(mydata[[treatment]]),collapse="\" \""),"\" \n")
}
if(!is.matrix(allContrasts) || NROW(allContrasts)!=2){
stop("Argument \'allContrasts\' must be a matrix with 2 rows \n")
}
}
if(!is.null(strata)){
if(attr(estimator, "IPTW")){
stop("Argument \'strata\' only compatible with the G-formula estimator \n")
}
if(any(strata %in% names(mydata) == FALSE)){
stop("The data set does not seem to have a variable \"",paste0(strata, collapse = "\" \""),"\" (argument: strata). \n")
}
if(length(strata) != 1){
stop("Argument strata should have length 1. \n")
}
if(attr(estimator,"TD")){
stop("Landmark analysis is not available when argument strata is specified. \n")
}
}
if(!is.na(eventVar.time)){
if(eventVar.time %in% names(mydata) == FALSE){
stop("The data set does not seem to have a variable ",eventVar.time," (argument: object.event[1]). \n")
}
if(is.na(cause)){
stop("Argument \'cause\' not specified\n")
}
data.status <- mydata[[eventVar.status]]
if(!is.null(treatment)){
data.strata <- mydata[[treatment]]
}else{
data.strata <- mydata[[strata]]
}
if(is.factor(data.strata)){
data.strata <- droplevels(data.strata)
}
freq.event <- tapply(data.status, data.strata, function(x){mean(x==cause)})
count.event <- tapply(data.status, data.strata, function(x){sum(x==cause)})
if(any(count.event < 5) ){
warning("Rare event \n")
}
if(any(mydata[[eventVar.time]]<0)){
stop("The time to event variable should only take positive values \n")
}
}
if (attr(estimator,"TD")){
if (missing(formula))
stop("Need formula to do landmark analysis.")
if (missing(landmark))
stop("Need landmark time(s) to do landmark analysis.")
if(length(times)!=1){
stop("In settings with time-dependent covariates argument 'time' must be a single value, argument 'landmark' may be a vector of time points.")
}
}
if((return.iid.nuisance == FALSE) & (iid == TRUE) & (attr(estimator, "augmented") == FALSE)){
warning("Ignoring the uncertainty associated with the estimation of the nuisance parameters may lead to inconsistent standard errors. \n",
"Consider using a double robust estimator or setting the argument \'known.nuisance\' to TRUE \n")
}
return(TRUE)
}
coef.ate <- function(object, ...){
name.coef <- interaction(object$meanRisk[["treatment"]],object$meanRisk[["time"]])
value.coef <- object$meanRisk[[paste0("meanRisk.",object$estimator[1])]]
return(setNames(value.coef, name.coef))
}
vcov.ate <- function(object, ...){
if(is.null(object$iid)){
stop("Missing iid decomposition in object \n",
"Consider setting the argument \'iid\' to TRUE when calling the ate function \n")
}
name.coef <- interaction(object$meanRisk[["treatment"]],object$meanRisk[["time"]])
iid <- NULL
for(iT in names(object$iid[[object$estimator[1]]])){
tempo <- object$iid[[object$estimator[1]]][[iT]]
colnames(tempo) <- interaction(iT,object$time)
iid <- cbind(iid,tempo)
}
return(crossprod(iid[,names(coef(object)),drop=FALSE]))
}
nobs.multinom <- function(object,...){
NROW(object$residuals)
}
|
use_datadriven_cv <- function(full_name = "Sarah Arcos",
data_location = system.file("sample_data/", package = "datadrivencv"),
pdf_location = "https://github.com/nstrayer/cv/raw/master/strayer_cv.pdf",
html_location = "nickstrayer.me/datadrivencv/",
source_location = "https://github.com/nstrayer/datadrivencv",
which_files = "all",
output_dir = getwd(),
create_output_dir = FALSE,
use_network_logo = TRUE,
open_files = TRUE){
if(is.character(which_files) && which_files == "all"){
which_files <- c("cv.rmd", "dd_cv.css", "render_cv.r", "cv_printing_functions.r")
}
which_files <- tolower(which_files)
if("cv.rmd" %in% which_files){
use_ddcv_template(
file_name = "cv.rmd",
params = list(
full_name = full_name,
data_location = data_location,
pdf_location = pdf_location,
html_location = html_location,
source_location = source_location,
use_network_logo = use_network_logo
),
output_dir = output_dir,
create_output_dir = create_output_dir,
open_after_making = open_files
)
}
if("dd_cv.css" %in% which_files){
use_ddcv_template(
file_name = "dd_cv.css",
output_dir = output_dir,
create_output_dir
)
}
if("render_cv.r" %in% which_files){
use_ddcv_template(
file_name = "render_cv.r",
output_dir = output_dir,
create_output_dir,
open_after_making = open_files
)
}
if("cv_printing_functions.r" %in% which_files){
use_ddcv_template(
file_name = "cv_printing_functions.r",
output_dir = output_dir,
create_output_dir
)
}
}
|
snotel_phenology <- function(df){
if (!is.data.frame(df) | base::missing(df)) {
stop("File is not a (SNOTEL) data frame, or missing!")
}
metric <- "temperature_min" %in% colnames(df)
if ( !metric ) {
stop("The content of the data frame might not be (metric) SNOTEL data...")
}
if ( all(is.na(df$snow_water_equivalent)) ) {
warning("Insufficient data, no snow phenology metrics returned...")
return(NULL)
}
df$date <- as.Date(df$date)
year <- format(df$date,"%Y")
df$snow_na <- df$snow_water_equivalent
df$snow_na[df$snow_water_equivalent > 0] <- NA
minmax <- function(x, ...){
if (nrow(x) < 365){
return(rep(NA,4))
}
if ( all(is.na(x$snow_na)) ) {
return(rep(NA,4))
}
minmax_loc <- which(x$snow_water_equivalent == 0)
na_loc <- as.numeric(na.action(stats::na.contiguous(x$snow_na)))
doy <- 1:365
doy[na_loc] <- NA
year <- as.numeric(format(x$date[min(minmax_loc)],"%Y"))
min_loc <- as.numeric(format(x$date[min(minmax_loc)],"%j"))
max_loc <- as.numeric(format(x$date[max(minmax_loc)],"%j"))
min_na_loc <- as.numeric(format(x$date[min(doy, na.rm = TRUE)],"%j"))
max_na_loc <- as.numeric(format(x$date[max(doy, na.rm = TRUE)],"%j"))
max_swe <- max(x$snow_water_equivalent[1:min(minmax_loc)],na.rm=TRUE)
max_swe_doy <- as.numeric(
format(x$date[which(x$snow_water_equivalent == max_swe)[1]],"%j")
)
return(data.frame(year,
min_loc,
max_loc,
min_na_loc,
max_na_loc,
max_swe,
max_swe_doy))
}
output <- do.call("rbind",
by(df, INDICES = c(year),
FUN = minmax))
output <- stats::na.omit(output)
if ( dim(output)[1] == 0 ){
warning("Insufficient data, no snow phenology metrics returned...")
return(NULL)
} else {
colnames(output) <- c("year",
"first_snow_melt",
"cont_snow_acc",
"last_snow_melt",
"first_snow_acc",
"max_swe",
"max_swe_doy"
)
return(output)
}
}
|
interpolateWoods <- function (point, std_point, nq1, nq2, delta) {
term1 <- (point - std_point)/delta
term2 <- nq2 - nq1
term1 * term2 + nq1
}
extrapolateWoods <- function (point, std_point, nq1, nq2, delta, tail) {
if (tail == "left") {
ratio <- nq1/nq2
if(is.nan(ratio) || ratio < .0000001) ratio <- .001
(ratio ^ ((std_point - point) / delta)) * nq1
} else if (tail == "right") {
ratio <- nq2/nq1
if(is.nan(ratio) || ratio < .0000001) ratio <- .001
(ratio ^ ((point - std_point) / delta)) * nq2
}
}
standardizeQuadrature <- function (qp, nq, estmean=FALSE, estsd=FALSE) {
qp_m <- sum(nq*qp) / sum(nq)
qp_sd <- sqrt(sum(nq * (qp - qp_m)^2) / sum(nq))
attr_ret <- c(mean = qp_m, var=qp_sd^2)
if(estmean) qp_m <- 0
if(estsd) qp_sd <- 1
std_qp <- (qp - qp_m) / qp_sd
if(estmean && estsd){
attr(nq, 'mean_var') <- attr_ret
return(nq)
}
min_stdqp <- min(std_qp)
max_stdqp <- max(std_qp)
res <- numeric(length(qp))
delta <- qp[2] - qp[1]
for (i in 1:length(qp)) {
if (qp[i] <= min_stdqp) {
res[i] <- extrapolateWoods(qp[i], min_stdqp, nq[1], nq[2], delta, "left")
} else if (max_stdqp <= qp[i]) {
res[i] <- extrapolateWoods(qp[i], max_stdqp, nq[length(nq)-1], nq[length(nq)], delta, "right")
} else {
std_ind <- max(which(qp[i] > std_qp))
res[i] <- interpolateWoods(qp[i], std_qp[std_ind], nq[std_ind], nq[std_ind+1], delta)
}
}
res <- res / sum(res) * sum(nq)
attr(res, 'mean_var') <- attr_ret
res
}
|
library(grid)
GeomMyPoint <- ggproto("GeomMyPoint", Geom,
required_aes = c("x", "y"),
default_aes = aes(shape = 1),
draw_key = draw_key_point,
draw_panel = function(data, panel_scales, coord) {
coords <- coord$transform(data, panel_scales)
polygonGrob(
x = coords$x,
y = coords$y
)
})
geom_mypoint <- function(mapping = NULL, data = NULL, stat = "identity",
position = "identity", na.rm = FALSE,
show.legend = NA, inherit.aes = TRUE, ...) {
ggplot2::layer(
geom = GeomMyPoint, mapping = mapping,
data = data, stat = stat, position = position,
show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
ggplot(data = cube_df, aes(x, y, group = zorder)) +
geom_mypoint(fill = "pink") +
coord_fixed()
|
context('df_stats()')
test_that("always get a data frame", {
expect_is(df_stats(~ cesd, data = mosaicData::HELPmiss), "data.frame")
expect_is(df_stats(~ cesd | sex, data = mosaicData::HELPmiss), "data.frame")
expect_is(df_stats(cesd ~ sex, data = mosaicData::HELPmiss), "data.frame")
expect_is(df_stats(cesd ~ substance, data = mosaicData::HELPmiss), "data.frame")
expect_is(df_stats(cesd ~ substance + sex, data = mosaicData::HELPmiss), "data.frame")
})
test_that("always get a data frame with simple vectors as columns", {
is_simple_df <- function(data) {
all(sapply(1:ncol(data), rlang::is_bare_numeric))
}
expect_true(
df_stats(~ cesd, data = mosaicData::HELPmiss) %>% is_simple_df())
expect_true(
df_stats(~ cesd | sex, data = mosaicData::HELPmiss) %>% is_simple_df())
expect_true(
df_stats(cesd ~ sex, data = mosaicData::HELPmiss) %>% is_simple_df())
expect_true(
df_stats(cesd ~ substance, data = mosaicData::HELPmiss) %>% is_simple_df())
expect_true(
df_stats(cesd ~ substance + sex, data = mosaicData::HELPmiss) %>% is_simple_df())
expect_true(
df_stats(~ cesd, data = mosaicData::HELPmiss, mean, median) %>% is_simple_df())
expect_true(
df_stats(~ cesd, data = mosaicData::HELPmiss, mean, median, range) %>% is_simple_df())
})
test_that("naming works", {
expect_equivalent(
names(df_stats(~ substance, data = mosaicData::HELPmiss, prop())),
c("response", "prop_alcohol"))
expect_equivalent(
names(df_stats(substance ~ sex, data = mosaicData::HELPmiss, prop())),
c("response", "sex", "prop_alcohol"))
expect_equivalent(
names(df_stats(~ cesd, data = mosaicData::HELPmiss)),
c("response", "min", "Q1", "median", "Q3", "max", "mean", "sd", "n", "missing"))
expect_equivalent(
names(df_stats(~ cesd | sex, data = mosaicData::HELPmiss)),
c("response", "sex", "min", "Q1", "median", "Q3", "max", "mean", "sd", "n", "missing"))
expect_equivalent(
names(df_stats(~ cesd | sex, data = mosaicData::HELPmiss, mean)),
c("response", "sex", "mean"))
expect_equivalent(
names(df_stats(~ cesd | sex, data = mosaicData::HELPmiss, A = mean, median)),
c("response", "sex", "A", "median"))
expect_equivalent(
names(df_stats(~ cesd | sex, data = mosaicData::HELPmiss, A = range, median)),
c("response", "sex", "A_1", "A_2", "median"))
expect_equivalent(
names(df_stats(~ cesd | sex, data = mosaicData::HELPmiss, range)),
c("response", "sex", "range_1", "range_2"))
expect_equivalent(
names(df_stats(~ cesd | sex, data = mosaicData::HELPmiss, range, long_names = FALSE)),
c("response", "sex", "range_1", "range_2"))
})
test_that("mean works", {
expect_equivalent(
df_stats(~ cesd, data = mosaicData::HELPmiss, mean)[, "mean"],
mean( mosaicData::HELPmiss$cesd, na.rm = TRUE)
)
expect_equivalent(
df_stats(cesd ~ substance, data = mosaicData::HELPmiss, mean)[, "mean"],
sapply(c("alcohol", "cocaine", "heroin", "missing"), function(s)
mean( subset(mosaicData::HELPmiss$cesd, mosaicData::HELPmiss$substance == s), na.rm = TRUE)
)
)
})
test_that("formulas can be used to specify groups.", {
expect_equivalent(
df_stats(cesd ~ substance, data = mosaicData::HELPmiss, mean),
df_stats( ~ cesd, groups = ~ substance, data = mosaicData::HELPmiss, mean)
)
expect_equivalent(
df_stats(cesd ~ substance, groups = sex, data = mosaicData::HELPmiss, mean),
df_stats(cesd ~ substance, groups = ~ sex, data = mosaicData::HELPmiss, mean)
)
})
|
gammaNUMCKpar <- function(matAp, matBp, n.cores = NULL, cut.a = 1, cut.p = 2) {
if(any(class(matAp) %in% c("tbl_df", "data.table"))){
matAp <- as.data.frame(matAp)[,1]
}
if(any(class(matBp) %in% c("tbl_df", "data.table"))){
matBp <- as.data.frame(matBp)[,1]
}
matAp[matAp == ""] <- NA
matBp[matBp == ""] <- NA
if(sum(is.na(matAp)) == length(matAp) | length(unique(matAp)) == 1){
cat("WARNING: You have no variation in this variable, or all observations are missing in dataset A.\n")
}
if(sum(is.na(matBp)) == length(matBp) | length(unique(matBp)) == 1){
cat("WARNING: You have no variation in this variable, or all observations are missing in dataset B.\n")
}
if(is.null(n.cores)) {
n.cores <- detectCores() - 1
}
matrix.1 <- as.matrix(as.numeric(matAp))
matrix.2 <- as.matrix(as.numeric(matBp))
max <- max(max(matrix.1, na.rm = T), max(matrix.2, na.rm = T))
end.points <- c((round((max), 0) + 1), (round(max + cut.p, 0) + 3))
matrix.1[is.na(matrix.1)] <- end.points[2]
matrix.2[is.na(matrix.2)] <- end.points[1]
u.values.1 <- unique(matrix.1)
u.values.2 <- unique(matrix.2)
n.slices1 <- max(round(length(u.values.1)/(10000), 0), 1)
n.slices2 <- max(round(length(u.values.2)/(10000), 0), 1)
limit.1 <- round(quantile((0:nrow(u.values.2)), p = seq(0, 1, 1/n.slices2)), 0)
limit.2 <- round(quantile((0:nrow(u.values.1)), p = seq(0, 1, 1/n.slices1)), 0)
temp.1 <- temp.2 <- list()
n.cores2 <- min(n.cores, n.slices1 * n.slices2)
for(i in 1:n.slices2) {
temp.1[[i]] <- list(u.values.2[(limit.1[i]+1):limit.1[i+1]], limit.1[i])
}
for(i in 1:n.slices1) {
temp.2[[i]] <- list(u.values.1[(limit.2[i]+1):limit.2[i+1]], limit.2[i])
}
difference <- function(m, y, cut) {
x <- as.matrix(m[[1]])
e <- as.matrix(y[[1]])
t <- calcPWDcpp(as.matrix(x), as.matrix(e))
t[ t == 0 ] <- cut[1]
t[ t > cut[2] ] <- 0
t <- Matrix(t, sparse = T)
t@x[t@x <= cut[1]] <- cut[2] + 1; gc()
t@x[t@x > cut[1] & t@x <= cut[2]] <- 1; gc()
slice.1 <- m[[2]]
slice.2 <- y[[2]]
indexes.2 <- which(t == cut[2] + 1, arr.ind = T)
indexes.2[, 1] <- indexes.2[, 1] + slice.2
indexes.2[, 2] <- indexes.2[, 2] + slice.1
indexes.1 <- which(t == 1, arr.ind = T)
indexes.1[, 1] <- indexes.1[, 1] + slice.2
indexes.1[, 2] <- indexes.1[, 2] + slice.1
list(indexes.2, indexes.1)
}
do <- expand.grid(1:n.slices2, 1:n.slices1)
if (n.cores2 == 1) '%oper%' <- foreach::'%do%'
else {
'%oper%' <- foreach::'%dopar%'
cl <- makeCluster(n.cores2)
registerDoParallel(cl)
on.exit(stopCluster(cl))
}
temp.f <- foreach(i = 1:nrow(do), .packages = c("Rcpp", "Matrix")) %oper% {
r1 <- do[i, 1]
r2 <- do[i, 2]
difference(temp.1[[r1]], temp.2[[r2]], c(cut.a, cut.p))
}
gc()
reshape2 <- function(s) { s[[1]] }
reshape1 <- function(s) { s[[2]] }
temp.2 <- lapply(temp.f, reshape2)
temp.1 <- lapply(temp.f, reshape1)
indexes.2 <- do.call('rbind', temp.2)
indexes.1 <- do.call('rbind', temp.1)
n.values.2 <- as.matrix(cbind(u.values.1[indexes.2[, 2]], u.values.2[indexes.2[, 1]]))
n.values.1 <- as.matrix(cbind(u.values.1[indexes.1[, 2]], u.values.2[indexes.1[, 1]]))
matches.2 <- lapply(seq_len(nrow(n.values.2)), function(i) n.values.2[i, ])
matches.1 <- lapply(seq_len(nrow(n.values.1)), function(i) n.values.1[i, ])
if(Sys.info()[['sysname']] == 'Windows') {
if (n.cores == 1) '%oper%' <- foreach::'%do%'
else {
'%oper%' <- foreach::'%dopar%'
cl <- makeCluster(n.cores)
registerDoParallel(cl)
on.exit(stopCluster(cl))
}
final.list2 <- foreach(i = 1:length(matches.2)) %oper% {
ht1 <- which(matrix.1 == matches.2[[i]][[1]]); ht2 <- which(matrix.2 == matches.2[[i]][[2]])
list(ht1, ht2)
}
final.list1 <- foreach(i = 1:length(matches.1)) %oper% {
ht1 <- which(matrix.1 == matches.1[[i]][[1]]); ht2 <- which(matrix.2 == matches.1[[i]][[2]])
list(ht1, ht2)
}
} else {
no_cores <- n.cores
final.list2 <- mclapply(matches.2, function(s){
ht1 <- which(matrix.1 == s[1]); ht2 <- which(matrix.2 == s[2]);
list(ht1, ht2) }, mc.cores = getOption("mc.cores", no_cores))
final.list1 <- mclapply(matches.1, function(s){
ht1 <- which(matrix.1 == s[1]); ht2 <- which(matrix.2 == s[2]);
list(ht1, ht2) }, mc.cores = getOption("mc.cores", no_cores))
}
na.list <- list()
na.list[[1]] <- which(matrix.1 == end.points[2])
na.list[[2]] <- which(matrix.2 == end.points[1])
out <- list()
out[["matches2"]] <- final.list2
out[["matches1"]] <- final.list1
out[["nas"]] <- na.list
class(out) <- c("fastLink", "gammaNUMCKpar")
return(out)
}
|
context("do_parallel")
test_that("a missing trajectory fails", {
expect_error(do_parallel(trajectory(), "asdf", .env=simmer()))
})
test_that("do_parallel generates the correct sequence of activities", {
t <- trajectory() %>%
do_parallel(trajectory(), trajectory(), .env=env, wait=TRUE)
expect_equal(length(t), 2)
expect_equal(get_n_activities(t), 8)
expect_output(print(t[[1]]), paste0(
"Clone.*3.*",
"Fork 1.*Trap.*Wait.*Wait.*UnTrap.*",
"Fork 2.*Send.*Fork 3.*Send"))
expect_output(print(t[[2]]), "Synchronize.*1")
t <- trajectory() %>%
do_parallel(trajectory(), trajectory(), .env=env, wait=FALSE)
expect_equal(length(t), 4)
expect_equal(get_n_activities(t), 7)
expect_output(print(t[[1]]), paste0(
"Clone.*3.*",
"Fork 1.*Trap.*",
"Fork 2.*Send.*Fork 3.*Send"))
expect_output(print(t[[2]]), "Synchronize.*0")
expect_output(print(t[[3]]), "Wait")
expect_output(print(t[[4]]), "UnTrap")
})
|
glmnetSE <- function(data, cf.no.shrnkg, alpha=1, method="10CVoneSE", test="none",r=250, nlambda=100, seed=0, family="gaussian", type="basic", conf=0.95, perf.metric="mse", ncore = "mx.core"){
coef.name <- colnames(data)[-1]
c <- which(names(data) %in% coef.name)-1
c <- 1:(ncol(data)-1)
n <- nrow(data)
no.shrink <- which(names(data) %in% cf.no.shrnkg)-1
p.fac <- rep(1, ncol(data)-1)
p.fac[no.shrink] <- 0
dep.var <- colnames(data[1])
if(length(alpha) > 1){
model_type = "Elastic Net"
}else if(alpha == 1){
model_type = "LASSO"
}else if(alpha == 0){
model_type = "Ridge"
}
"%ni%" <- Negate("%in%")
if(class(data)!= "data.frame" && class(data)!= "tbl_df" && class(data)!= "matrix"){
warning("Use an object of class data frame, tibble or matrix as data input")
stop()
}
if(class(class(cf.no.shrnkg))!= "character"){
warning("The input of the coefficients without applied shrinkage has to be a character")
stop()
}
if(class(alpha)!= "numeric"){
warning("Alpha has to be numeric")
stop()
}else if(any(alpha > 1) || any(alpha < 0)){
warning("Alpha should be between 0 and 1")
stop()
}
if(method!= "none" && method!= "10CVmin" && method!= "10CVoneSE"){
warning("The method should be 'none', '10CVmin' or '10CVoneSE'")
stop()
}
if(class(r)!= "numeric"){
warning("The number of bootstrap repetitions has to be numeric")
stop()
}else if(r < 100){
warning("Be aware that you are using less than 100 bootstrap repetitions")
}
if(class(nlambda)!= "numeric"){
warning("The number of tested lambdas has to be numeric")
stop()
}
if(family!= "gaussian" && family!= "binomial"){
warning("The model family should be 'gaussian' or 'binomial'")
stop()
}
if(type!= "basic" && type!= "norm" && type!= "perc" && type!= "bca"){
warning("The bootstrap confidence interval type has to be 'basic', 'norm', 'perc', or 'bca'")
stop()
}
if(class(conf)!= "numeric"){
warning("Conf has to be numeric")
stop()
}else if(any(conf > 1) || any(conf < 0)){
warning("Conf should be between 0 and 1")
stop()
}
if(perf.metric!= "mse" && perf.metric!= "mae" && perf.metric!= "auc" && perf.metric!= "class"){
warning("The performance metric should be 'mse', 'mae', 'class' or 'auc'")
stop()
}
if(family == "binomial" && (perf.metric!= "auc" && perf.metric!= "class")){
warning("With family 'binomial' please use the performance metric 'class' or 'auc'")
stop()
}
if(family == "gaussian" && (perf.metric!= "mse" && perf.metric!= "mae")){
warning("With family 'gaussian' please use the performance metric 'mse' or 'mae'")
stop()
}
if((class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix") & (method != "10CVmin" && method != "10CVoneSE")){
warning("The model performance on the test data is only supplied for method '10CVmin' and '10CVoneSE'")
}
if((r < n) && type=="bca"){
warning("The number of bootstrap repetitions 'r' should at leaste be as large as the sample size.")
stop()
}
if((length(alpha)>1) && seed == 0){
warning("For using automated alpha selection properly please set a seed. The seed should not be 0.")
}
if(length(alpha)>1){
if(all(alpha != 0) && all(alpha != 1)){
enet <- NULL
for(i in alpha){
y = as.matrix(data[,1])
x = as.matrix(data[,-1])
set.seed(seed)
enet.fit <- glmnet::cv.glmnet(x=x, y=y, alpha=i, family=family, nlambda=nlambda, penalty.factor=p.fac, type.measure=perf.metric)
enet.fit[["alpha"]] = i
enet.fit_new = enet.fit
enet[[length(enet) + 1]] = enet.fit_new
}
alpha.n <- 1:length(alpha)
enet.mod.check <- data.frame(alpha = numeric(), mtr.min = numeric(),
mtr.oneSE = numeric())
for(i in alpha.n){
mtr.min = enet[[i]]$cvm[enet[[i]]$lambda == enet[[i]]$lambda.min]
mtr.oneSE = enet[[i]]$cvm[enet[[i]]$lambda == enet[[i]]$lambda.1se]
alpha = enet[[i]]$alpha
enet.mod.check[nrow(enet.mod.check) + 1,] = c(alpha, mtr.min, mtr.oneSE)
}
if(method == "10CVmin"){
alpha <- enet.mod.check$alpha[enet.mod.check$mtr.min==min(enet.mod.check$mtr.min)]
print(paste("The best alpha is: ", alpha))
}else if(method == "10CVoneSE"){
alpha <- enet.mod.check$alpha[enet.mod.check$mtr.oneSE==min(enet.mod.check$mtr.oneSE)]
print(paste("The best alpha is: ", alpha))
}else{
warning("Select method '10CVmin' or '10CVoneSE'")
}
}else{
warning("A Elastic Net should have a alpha >0 and <1. Alpha values of 0 and 1 results in a ridge or LASSO model.")
}
}else{
alpha <- alpha
}
getROC_AUC = function(probs, true_Y){
probsSort = sort(probs, decreasing = TRUE, index.return = TRUE)
val = unlist(probsSort$x)
idx = unlist(probsSort$ix)
roc_y = true_Y[idx];
stack_x = cumsum(roc_y == 0)/sum(roc_y == 0)
stack_y = cumsum(roc_y == 1)/sum(roc_y == 1)
auc = sum((stack_x[2:length(roc_y)]-stack_x[1:length(roc_y)-1])*stack_y[2:length(roc_y)])
return(list(stack_x=stack_x, stack_y=stack_y, auc=auc))
}
envir = environment(glmnetSE)
if(ncore == "mx.core"){
cpus <- parallel::detectCores()
cl <- parallel::makeCluster(ifelse((cpus-1)>32, 32, (cpus-1)))
}else if(typeof(ncore) == "double"){
cpus <- ncore
cl <- parallel::makeCluster(ncore)
}
parallel::clusterExport(cl=cl, varlist = ls(envir), envir = envir)
if(method=="10CVoneSE"){
if(perf.metric == "auc" && (class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix")){
y = as.matrix(data[,1])
x = as.matrix(data[,-1])
set.seed(seed)
fit.roc = glmnet::cv.glmnet(x=x, y=y, alpha=alpha, family=family, nlambda=nlambda, penalty.factor=p.fac, type.measure=perf.metric)
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- stats::predict(fit.roc, s=fit.roc$lambda.1se, newx=x.test, type = "response")
roc = getROC_AUC(p.fit.test, y.test)
roc <- list(roc$stack_y, roc$stack_x)
}
boot.glmnet <- function(data, indices, R) {
d = data[indices,]
y = as.matrix(d[,1])
x = as.matrix(d[,-1])
set.seed(seed)
fit = glmnet::cv.glmnet(x=x, y=y, alpha=alpha, family=family, nlambda=nlambda, penalty.factor=p.fac, type.measure=perf.metric)
coef <- coef(fit, s = "lambda.1se")[-1]
if(perf.metric == "auc"){
y.train = as.matrix(data[,1])
x.train = as.matrix(data[,-1])
p.fit.train <- stats::predict(fit, s=fit$lambda.1se, newx=x.train, type = "response")
roc.auc = getROC_AUC(p.fit.train, y.train)
metric <- roc.auc$auc
}else{
metric <- fit$cvm[fit$lambda == fit$lambda.1se]
}
if(class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix"){
if(dep.var == colnames(test[1]) && ncol(data) == ncol(test)){
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- stats::predict(fit, s=fit$lambda.1se, newx=x.test)
SSE <- sum((p.fit.test - y.test)^2)
if(perf.metric == "mse"){
metric.test <- SSE/nrow(test)
}else if(perf.metric == "auc"){
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- stats::predict(fit, s=fit$lambda.1se, newx=x.test, type = "response")
roc.auc = getROC_AUC(p.fit.test, y.test)
metric.test <- roc.auc$auc
}else if(perf.metric == "class"){
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- as.numeric(stats::predict(fit, s=fit$lambda.1se, newx=x.test, type = "class"))
metric.test <- mean(y.test != p.fit.test, na.rm = TRUE)
}else{
metric.test <- mean(abs(y.test - p.fit.test), na.rm = TRUE)
}
return(c(coef, metric, metric.test))
}else{
warning("Training and test data need to have the same outcome and feature variables.")
stop()
}
}else{
return(c(coef, metric))
}
}
if(seed==0){
results = boot::boot(data=data, statistic=boot.glmnet, R=r, parallel = "snow", ncpus =cpus, cl=cl)
parallel::stopCluster(cl=cl)
}else{
set.seed(seed)
results = boot::boot(data=data, statistic=boot.glmnet, R=r, parallel = "snow", ncpus =cpus, cl=cl)
parallel::stopCluster(cl=cl)
}
}else if(method=="10CVmin"){
if(perf.metric == "auc" && (class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix")){
y = as.matrix(data[,1])
x = as.matrix(data[,-1])
set.seed(seed)
fit.roc = glmnet::cv.glmnet(x=x, y=y, alpha=alpha, family=family, nlambda=nlambda, penalty.factor=p.fac, type.measure=perf.metric)
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- stats::predict(fit.roc, s=fit.roc$lambda.1se, newx=x.test, type = "response")
roc = getROC_AUC(p.fit.test, y.test)
roc <- list(roc$stack_y, roc$stack_x)
}
boot.glmnet <- function(data, indices, R) {
d = data[indices,]
y = as.matrix(d[,1])
x = as.matrix(d[,-1])
set.seed(seed)
fit = glmnet::cv.glmnet(x=x, y=y,alpha=alpha, family=family, nlambda=nlambda, penalty.factor=p.fac, type.measure=perf.metric)
coef <- coef(fit, s = "lambda.min")[-1]
if(perf.metric == "auc"){
y.train = as.matrix(data[,1])
x.train = as.matrix(data[,-1])
p.fit.train <- stats::predict(fit, s=fit$lambda.min, newx=x.train, type = "response")
roc.auc = getROC_AUC(p.fit.train, y.train)
metric <- roc.auc$auc
}else{
metric <- fit$cvm[fit$lambda == fit$lambda.min]
}
if(class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix"){
if(dep.var == colnames(test[1]) && ncol(data) == ncol(test)){
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- stats::predict(fit, s=fit$lambda.min, newx=x.test)
SSE <- sum((p.fit.test - y.test)^2)
if(perf.metric == "mse"){
metric.test <- SSE/nrow(test)
}else if(perf.metric == "auc"){
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- stats::predict(fit, s=fit$lambda.1se, newx=x.test, type = "response")
roc.auc = getROC_AUC(p.fit.test, y.test)
metric.test <- roc.auc$auc
}else if(perf.metric == "class"){
y.test = as.matrix(test[,1])
x.test = as.matrix(test[,-1])
p.fit.test <- as.numeric(stats::predict(fit, s=fit$lambda.1se, newx=x.test, type = "class"))
metric.test <- mean(y.test != p.fit.test, na.rm = TRUE)
}else{
metric.test <- mean(abs(y.test - p.fit.test), na.rm = TRUE)
}
return(c(coef, metric, metric.test))
}else{
warning("Training and test data need to have the same outcome and feature variables.")
}
}else{
return(c(coef, metric))
}
}
if(seed==0){
results = boot::boot(data=data, statistic=boot.glmnet, R=r, parallel = "snow", ncpus =cpus, cl=cl)
parallel::stopCluster(cl=cl)
}else{
set.seed(seed)
results = boot::boot(data=data, statistic=boot.glmnet, R=r, parallel = "snow", ncpus =cpus, cl=cl)
parallel::stopCluster(cl=cl)
}
}else{
boot.glmnet <- function(data, indices, R) {
d = data[indices,]
y = as.matrix(d[,1])
x = as.matrix(d[,-1])
fit = glmnet::glmnet(x=x, y=y,alpha=alpha, family=family, nlambda=nlambda, penalty.factor=p.fac)
return(coef(fit, s = 0.1)[-1])
}
if(seed==0){
results = boot::boot(data=data, statistic=boot.glmnet, R=r, parallel = "snow", ncpus =cpus, cl=cl)
parallel::stopCluster(cl=cl)
}else{
set.seed(seed)
results = boot::boot(data=data, statistic=boot.glmnet, R=r, parallel = "snow", ncpus =cpus, cl=cl)
parallel::stopCluster(cl=cl)
}
}
name <- NULL
coef <- NULL
SE <- NULL
KI_low <- NULL
KI_up <- NULL
p.val <- NULL
star <- NULL
if(type=="norm"){
type.name="normal"
bt.s <- 2
bt.e <- 3
}else if(type=="perc"){
type.name="percent"
bt.s <- 4
bt.e <- 5
}else{
type.name=type
bt.s <- 4
bt.e <- 5
}
if(method == "none"){
iter.loop <- 0
for(C in c){
iter.loop <- iter.loop + 1
coef.nm <- coef.name[iter.loop]
KI <- boot::boot.ci(results, type=type, conf=conf, index=C)[[type.name]][bt.s:bt.e]
if(coef.nm %ni% cf.no.shrnkg){
name_new <- coef.name[iter.loop]
name <- c(name, name_new)
coef_new <- results[["t0"]][C]
coef <- c(coef, coef_new)
SE_new <- NA
SE <- c(SE, SE_new)
p.val_new <- NA
p.val <- c(p.val, p.val_new)
KI_low_new <- NA
KI_low <- c(KI_low, KI_low_new)
KI_up_new <- NA
KI_up <- c(KI_up, KI_up_new)
star_new <- " "
star <- c(star, star_new)
}else{
name_new <- coef.name[iter.loop]
name <- c(name, name_new)
coef_new <- results[["t0"]][C]
coef <- c(coef, coef_new)
SE_new <- apply(results$t,2,stats::sd)[C]
SE <- c(SE, SE_new)
p.val_new <- mean(abs(results$t0[C]-(mean(results$t[,C])-results$t0[C])) <= abs(results$t[,C]-mean(results$t[,C])))
p.val <- c(p.val, p.val_new)
KI_low_new <- KI[1]
KI_low <- c(KI_low, KI_low_new)
KI_up_new <- KI[2]
KI_up <- c(KI_up, KI_up_new)
star_new <- if(p.val[C] < 0.05 && p.val[C] >= 0.01){
"*"
}else if(p.val[C] < 0.01 && p.val[C] >= 0.001){
"**"
}else if(p.val[C] < 0.001){
"***"
}else{
" "
}
star <- c(star, star_new)
}
output <- list(model_type = model_type,
coefficients = name,
outcome_var = dep.var,
variables_no_shrinkage = cf.no.shrnkg,
estimat = coef,
standard_error = SE,
p.value = p.val,
CI_low = KI_low,
CI_up = KI_up,
star = star,
metric_name = "not applied")
}
}else{
if(class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix"){
metric.KI <- boot::boot.ci(results, type=type, conf=conf, index=max(c)+1)[[type.name]][bt.s:bt.e]
metric <- results[["t0"]][max(c)+1]
metric.KI.test <- boot::boot.ci(results, type=type, conf=conf, index=max(c)+2)[[type.name]][bt.s:bt.e]
metric.test <- results[["t0"]][max(c)+2]
test.set <- "test data supplied"
}else{
metric.KI <- boot::boot.ci(results, type=type, conf=conf, index=max(c)+1)[[type.name]][bt.s:bt.e]
metric <- results[["t0"]][max(c)+1]
test.set <- "no test data supplied"
}
iter.loop <- 0
for(C in c){
iter.loop <- iter.loop + 1
coef.nm <- coef.name[iter.loop]
KI <- boot::boot.ci(results, type=type, conf=conf, index=C)[[type.name]][bt.s:bt.e]
if(coef.nm %ni% cf.no.shrnkg){
name_new <- coef.name[iter.loop]
name <- c(name, name_new)
coef_new <- results[["t0"]][C]
coef <- c(coef, coef_new)
SE_new <- NA
SE <- c(SE, SE_new)
p.val_new <- NA
p.val <- c(p.val, p.val_new)
KI_low_new <- NA
KI_low <- c(KI_low, KI_low_new)
KI_up_new <- NA
KI_up <- c(KI_up, KI_up_new)
star_new <- " "
star <- c(star, star_new)
}else{
name_new <- coef.name[iter.loop]
name <- c(name, name_new)
coef_new <- results[["t0"]][C]
coef <- c(coef, coef_new)
SE_new <- apply(results$t,2,stats::sd)[C]
SE <- c(SE, SE_new)
p.val_new <- mean(abs(results$t0[C]-(mean(results$t[,C])-results$t0[C])) <= abs(results$t[,C]-mean(results$t[,C])))
p.val <- c(p.val, p.val_new)
KI_low_new <- KI[1]
KI_low <- c(KI_low, KI_low_new)
KI_up_new <- KI[2]
KI_up <- c(KI_up, KI_up_new)
star_new <- if(p.val[C] < 0.05 && p.val[C] >= 0.01){
"*"
}else if(p.val[C] < 0.01 && p.val[C] >= 0.001){
"**"
}else if(p.val[C] < 0.001){
"***"
}else{
" "
}
star <- c(star, star_new)
}
if(perf.metric == "auc" && (class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix")){
output <- list(model_type = model_type,
coefficients = name,
outcome_var = dep.var,
variables_no_shrinkage = cf.no.shrnkg,
estimat = coef,
standard_error = SE,
p.value = p.val,
CI_low = KI_low,
CI_up = KI_up,
star = star,
metric_name = perf.metric,
metric = metric,
metric_CI = metric.KI,
test.set = test.set,
metric.test = metric.test,
metric_CI.test = metric.KI.test,
roc_y = roc[1],
roc_x = roc[2])
}else if(class(test)== "data.frame" || class(test)== "tbl_df" || class(test)== "matrix"){
output <- list(model_type = model_type,
coefficients = name,
outcome_var = dep.var,
variables_no_shrinkage = cf.no.shrnkg,
estimat = coef,
standard_error = SE,
p.value = p.val,
CI_low = KI_low,
CI_up = KI_up,
star = star,
metric_name = perf.metric,
metric = metric,
metric_CI = metric.KI,
test.set = test.set,
metric.test = metric.test,
metric_CI.test = metric.KI.test)
}else{
output <- list(model_type = model_type,
coefficients = name,
outcome_var = dep.var,
variables_no_shrinkage = cf.no.shrnkg,
test.set = test.set,
estimat = coef,
standard_error = SE,
p.value = p.val,
CI_low = KI_low,
CI_up = KI_up,
star = star,
metric_name = perf.metric,
metric = metric,
metric_CI = metric.KI)
}
}
}
class(output) <- c("glmnetSE")
invisible(output)
}
summary.glmnetSE <- function(object, ...){
if(class(object)!= "glmnetSE"){
warning("A object of the class 'glmnetSE' should be used")
stop()
}
if(object$metric_name == "not applied"){
coef <- data.frame(cbind("Coefficients" = object$coefficients,
"Estimates" = round(object$estimat,4),
"Std.Error" = round(object$standard_error,4),
"CI.low" = round(object$CI_low,4),
"CI.up" = round(object$CI_up,4),
"p-value" = round(object$p.value,4),
"Sig." = object$star))
}else{
coef <- data.frame(cbind("Coefficients" = object$coefficients,
"Estimates" = round(object$estimat,4),
"Std.Error" = round(object$standard_error,4),
"CI.low" = round(object$CI_low,4),
"CI.up" = round(object$CI_up,4),
"p-value" = round(object$p.value,4),
"Sig." = object$star))
if(object$test.set == "test data supplied"){
metric <- data.frame(cbind("Metric" = c(object$metric_name),
"Value" = c(round(object$metric,2)),
"CI.low" = c(round(object$metric_CI[1],2)),
"CI.up" = c(round(ifelse(object$metric_name == "auc" && object$metric_CI[2] > 1,1, object$metric_CI[2]),2))))
metric.test <- data.frame(cbind("Metric" = c(object$metric_name),
"Value" = c(round(object$metric.test,2)),
"CI.low" = c(round(object$metric_CI.test[1],2)),
"CI.up" = c(round(ifelse(object$metric_name == "auc" && object$metric_CI[2] > 1,1, object$metric_CI[2]),2))))
}else{
metric <- data.frame(cbind("Metric" = c(object$metric_name),
"Value" = c(round(object$metric,2)),
"CI.low" = c(round(object$metric_CI[1],2)),
"CI.up" = c(round(ifelse(object$metric_name == "auc" && object$metric_CI[2] > 1,1, object$metric_CI[2]),2))))
}
}
cat(paste0(object$model_type), "model:\n")
cat("Outcome variable:", paste0(object$outcome_var), "\n")
cat("Variables without shrinkage:", paste0(object$variables_no_shrinkage), "\n")
cat("\n\n")
print(coef, row.names = FALSE)
cat("\n\n")
if(object$metric_name == "not applied"){
cat("Performance Metric: \n")
cat(c("Metric only applicable with method '10CVmin' or '10CVoneSE'"), fill = getOption("width"))
}else{
if(object$test.set == "test data supplied"){
cat("Performance metric train data: \n")
print(metric, row.names = FALSE)
cat("\n\n")
cat("Performance metric test data: \n")
print(metric.test, row.names = FALSE)
}else{
cat("Performance Metric: \n")
print(metric, row.names = FALSE)
}
}
}
plot.glmnetSE <- function(x, ...){
if(class(x)!= "glmnetSE"){
warning("A object of the class 'glmnetSE' should be used")
stop()
}
if(x$test.set!= "test data supplied"){
warning("The ROC curve can only be plotted if test data is supplied to 'glmnetSE'")
stop()
}
graphics::plot(x[["roc_x"]][[1]], x[["roc_y"]][[1]], type = "l", col = "blue", xlab = "False Positive Rate", ylab = "True Positive Rate", main = "ROC")
graphics::axis(1, seq(0.0,1.0,0.1))
graphics::axis(2, seq(0.0,1.0,0.1))
graphics::abline(0, 1, col="black", lty=3)
}
|
focus <- function(x, ..., mirror = FALSE) {
focus_(
x = x,
.dots = ...,
... = ...,
mirror = mirror
)
}
dice <- function(x, ...) {
UseMethod("dice")
}
dice.cor_df <- function(x, ...) {
focus(x, ..., mirror = TRUE)
}
focus_ <- function(x, ..., .dots, mirror) {
UseMethod("focus_")
}
focus_if <- function(x, .predicate, ..., mirror = FALSE) {
UseMethod("focus_if")
}
focus_if.default <- function(x, .predicate, ..., mirror = FALSE) {
x <- as_cordf(x)
focus_if.cor_df(x, .predicate, ..., mirror = mirror)
}
stretch <- function(x, na.rm = FALSE, remove.dups = FALSE) {
UseMethod("stretch")
}
stretch.cor_df <- function(x, na.rm = FALSE, remove.dups = FALSE) {
if(remove.dups) x <- shave(x)
row_name <- x$term
x <- x[colnames(x) != "term"]
tb <- imap_dfr(x, ~tibble(x = .y, y = row_name, r = .x))
if(na.rm) tb <- tb[!is.na(tb$r), ]
if(remove.dups) {
stretch_unique(tb)
} else {
tb
}
}
stretch_unique <- function(.data, x = x, y = y, val = r) {
val <- enquo(val)
y <- enquo(y)
x <- enquo(x)
row_names <- unique(.data[, as_label(y)][[1]])
td <- purrr::transpose(.data)
combos <- map_chr(
td,
~paste0(sort(c(.x$x, .x$y)), collapse = " | ")
)
.data$combos <- combos
map_dfr(
unique(combos),
~{
cr <- .data[.data$combos == .x, ]
vl <- cr[, as_label(val)][[1]]
if(nrow(cr) == 2) cr <- cr[!is.na(vl), ]
if(nrow(cr) != 1) stop("Error deduplicating stretched table")
cr[, colnames(cr) != "combos"]
}
)
}
|
library(testthat)
update_expectation <- FALSE
test_that("One Shot: writing with read-only privileges", {
credential <- retrieve_credential_testing(project_id = 153L)
expected_message <- "The REDCapR write/import operation was not successful. The error message was:\nERROR: You do not have API Import/Update privileges"
expected_text <- "ERROR: You do not have API Import/Update privileges"
expect_message(
result <- REDCapR::redcap_write_oneshot(ds=mtcars, redcap_uri=credential$redcap_uri, token=credential$token)
)
expect_false(result$success)
expect_equal(result$status_code, expected=403L)
expect_equal(result$outcome_message, expected_message)
expect_true( is.na(result$records_affected_count))
expect_equal(result$affected_ids, character(0))
expect_equal(result$raw_text, expected_text, ignore_attr = TRUE)
expect_null( result$data)
expect_null( result$records_collapsed)
expect_null( result$fields_collapsed)
})
test_that("Single Batch: writing with read-only privileges", {
credential <- retrieve_credential_testing(project_id = 153L)
expected_message <- "The REDCapR write/import operation was not successful. The error message was:\nERROR: You do not have API Import/Update privileges"
expected_text <- "ERROR: You do not have API Import/Update privileges"
expect_error(
result <- REDCapR::redcap_write(ds=mtcars, redcap_uri=credential$redcap_uri, token=credential$token)
)
})
test_that("Many Batches: writing with read-only privileges", {
credential <- retrieve_credential_testing(project_id = 153L)
expected_message <- "The REDCapR write/import operation was not successful. The error message was:\nERROR: You do not have API Import/Update privileges"
expected_text <- "ERROR: You do not have API Import/Update privileges"
expect_error(
result <- REDCapR::redcap_write(ds=mtcars, redcap_uri=credential$redcap_uri, token=credential$token, batch_size=10)
)
})
test_that("Single Batch: writing with read-only privileges --contiue on error", {
credential <- retrieve_credential_testing(project_id = 153L)
expected_message <- "The REDCapR write/import operation was not successful. The error message was:\nERROR: You do not have API Import/Update privileges"
expect_warning(expect_message(
result <- REDCapR::redcap_write(ds=mtcars, redcap_uri=credential$redcap_uri, token=credential$token, continue_on_error=TRUE)
))
expect_false(result$success)
expect_equal(result$status_code, expected="403")
expect_equal(result$outcome_message, expected_message)
expect_equal( result$records_affected_count, 0L)
expect_equal(result$affected_ids, character(0))
expect_null( result$raw_text)
expect_null( result$records_collapsed)
expect_null( result$fields_collapsed)
})
test_that("Many Batches: writing with read-only privileges --contiue on error", {
credential <- retrieve_credential_testing(project_id = 153L)
expected_message <- "The REDCapR write/import operation was not successful. The error message was:\nERROR: You do not have API Import/Update privileges"
expect_warning(expect_warning(expect_warning(expect_warning(
result <- REDCapR::redcap_write(ds=mtcars, redcap_uri=credential$redcap_uri, token=credential$token, continue_on_error=TRUE, batch_size=10)
))))
expect_false(result$success)
expect_equal(result$status_code, expected="403; 403; 403; 403")
expect_match(result$outcome_message, expected_message)
expect_equal( result$records_affected_count, 0L)
expect_equal(result$affected_ids, character(0))
expect_null( result$raw_text)
expect_null( result$records_collapsed)
expect_null( result$fields_collapsed)
})
|
context("kbdate")
test_that("kbdate works", {
expect_equal(kbdate(), format(Sys.Date(), "%Y-%m-%d"))
})
|
topRunsBatsmenAcrossOversAllOppnAllMatches <- function(matches,t1,plot=1) {
team=ball=totalRuns=total=runsPowerPlay=runsMiddleOvers=runsDeathOvers=batsman=str_extract=NULL
ggplotly=NULL
a <-filter(matches,team==t1)
a1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9))
a2 <- select(a1,ball,totalRuns,batsman)
a3 <- a2 %>% group_by(batsman) %>% summarise(runsPowerPlay= sum(totalRuns)) %>% arrange(desc(runsPowerPlay))
b1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9))
b2 <- select(b1,ball,totalRuns,batsman)
b3 <- b2 %>% group_by(batsman) %>% summarise(runsMiddleOvers= sum(totalRuns)) %>% arrange(desc(runsMiddleOvers))
c1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0))
c2 <- select(c1,ball,totalRuns,batsman)
c3 <- c2 %>% group_by(batsman) %>% summarise(runsDeathOvers= sum(totalRuns)) %>% arrange(desc(runsDeathOvers))
val=min(dim(a3)[1],dim(b3)[1],dim(c3)[1])
m=cbind(a3[1:val,],b3[1:val,],c3[1:val,])
m
}
|
infer_ts_ind_ttest <- function(data, x, y, confint = 0.95,
alternative = c("both", "less", "greater", "all"), ...) UseMethod("infer_ts_ind_ttest")
infer_ts_ind_ttest.default <- function(data, x, y, confint = 0.95,
alternative = c("both", "less", "greater", "all"), ...) {
x1 <- deparse(substitute(x))
y1 <- deparse(substitute(y))
yone <- names(data[y1])
if (check_x(data, x1)) {
stop("x must be a binary factor variable", call. = FALSE)
}
if (check_level(data, x1) > 2) {
stop("x must be a binary factor variable", call. = FALSE)
}
method <- match.arg(alternative)
var_y <- yone
alpha <- 1 - confint
a <- alpha / 2
h <- indth(data, x1, y1, a)
grp_stat <- h
g_stat <- as.matrix(h)
comb <- indcomb(data, y1, a)
k <- indcomp(grp_stat, alpha)
j <- indsig(k$n1, k$n2, k$s1, k$s2, k$mean_diff)
m <- indpool(k$n1, k$n2, k$mean_diff, k$se_dif)
result <- list(alternative = method,
combined = comb,
confint = confint,
conf_diff = round(k$conf_diff, 5),
den_df = k$n2 - 1,
df_pooled = m$df_pooled,
df_satterthwaite = j$d_f,
f = round(k$s1 / k$s2, 4),
f_sig = fsig(k$s1, k$s2, k$n1, k$n2),
levels = g_stat[, 1],
lower = g_stat[, 8],
mean = g_stat[, 3],
mean_diff = round(k$mean_diff, 3),
n = k$n,
num_df = k$n1 - 1,
obs = g_stat[, 2],
sd = g_stat[, 4],
sd_dif = round(k$sd_dif, 3),
se = g_stat[, 5],
se_dif = round(k$se_dif, 3),
sig = j$sig,
sig_l = j$sig_l,
sig_pooled_l = m$sig_pooled_l,
sig_pooled_u = m$sig_pooled_u,
sig_pooled = m$sig_pooled,
sig_u = j$sig_u,
t_pooled = round(m$t_pooled, 4),
t_satterthwaite = round(j$t, 4),
upper = g_stat[, 9],
var_y = var_y)
class(result) <- "infer_ts_ind_ttest"
return(result)
}
print.infer_ts_ind_ttest <- function(x, ...) {
print_two_ttest(x)
}
indth <- function(data, x, y, a) {
h <- data_split(data, x, y)
h$df <- h$length - 1
h$error <- qt(a, h$df) * -1
h$lower <- h$mean_t - (h$error * h$std_err)
h$upper <- h$mean_t + (h$error * h$std_err)
return(h)
}
data_split <- function(data, x, y) {
dat <- data.table(data[c(x, y)])
out <- dat[, .(length = length(get(y)),
mean_t = mean_t(get(y)),
sd_t = sd_t(get(y)),
std_err = std_err(get(y))),
by = x]
setDF(out)
}
indcomb <- function(data, y, a) {
comb <- da(data, y)
comb$df <- comb$length - 1
comb$error <- qt(a, comb$df) * -1
comb$lower <- round(comb$mean_t - (comb$error * comb$std_err), 5)
comb$upper <- round(comb$mean_t + (comb$error * comb$std_err), 5)
names(comb) <- NULL
return(comb)
}
da <- function(data, y) {
dat <- data[[y]]
data.frame(length = length(dat),
mean_t = mean_t(dat),
sd_t = sd_t(dat),
std_err = std_err(dat))
}
mean_t <- function(x) {
round(mean(x), 3)
}
sd_t <- function(x) {
round(sd(x), 3)
}
std_err <- function(x) {
x %>%
sd() %>%
divide_by(x %>%
length() %>%
sqrt()) %>%
round(3)
}
indcomp <- function(grp_stat, alpha) {
n1 <- grp_stat[1, 2]
n2 <- grp_stat[2, 2]
n <- n1 + n2
means <- grp_stat[, 3]
mean_diff <- means[1] - means[2]
sd1 <- grp_stat[1, 4]
sd2 <- grp_stat[2, 4]
s1 <- grp_stat[1, 4] ^ 2
s2 <- grp_stat[2, 4] ^ 2
sd_dif <- sd_diff(n1, n2, s1, s2)
se_dif <- se_diff(n1, n2, s1, s2)
conf_diff <- conf_int_p(mean_diff, se_dif, alpha = alpha)
list(conf_diff = conf_diff,
mean_diff = mean_diff,
n = n,
n1 = n1,
n2 = n2,
s1 = s1,
s2 = s2,
sd1 = sd1,
sd2 = sd2,
sd_dif = sd_dif,
se_dif = se_dif)
}
sd_diff <- function(n1, n2, s1, s2) {
n1 <- n1 - 1
n2 <- n2 - 1
n <- (n1 + n2) - 2
(n1 * s1) %>%
add(n2 * s2) %>%
divide_by(n) %>%
raise_to_power(0.5)
}
se_diff <- function(n1, n2, s1, s2) {
df <- n1 + n2 - 2
n_1 <- n1 - 1
n_2 <- n2 - 1
(n_1 * s1) %>%
add(n_2 * s2) %>%
divide_by(df) -> v
(1 / n1) %>%
add(1 / n2) %>%
multiply_by(v) %>%
sqrt()
}
conf_int_p <- function(u, se, alpha = 0.05) {
a <- alpha / 2
error <- round(qnorm(a), 3) * -1
lower <- u - (error * se)
upper <- u + (error * se)
c(lower, upper)
}
indsig <- function(n1, n2, s1, s2, mean_diff) {
d_f <- as.vector(df(n1, n2, s1, s2))
t <- mean_diff / (((s1 / n1) + (s2 / n2)) ^ 0.5)
sig_l <- round(pt(t, d_f), 4)
sig_u <- round(pt(t, d_f, lower.tail = FALSE), 4)
if (sig_l < 0.5) {
sig <- round(pt(t, d_f) * 2, 4)
} else {
sig <- round(pt(t, d_f, lower.tail = FALSE) * 2, 4)
}
list(d_f = d_f,
sig_l = sig_l,
sig_u = sig_u,
sig = sig,
t = t)
}
df <- function(n1, n2, s1, s2) {
sn1 <- s1 / n1
sn2 <- s2 / n2
m1 <- 1 / (n1 - 1)
m2 <- 1 / (n2 - 1)
num <- (sn1 + sn2) ^ 2
den <- (m1 * (sn1 ^ 2)) + (m2 * (sn2 ^ 2))
round(num / den)
}
fsig <- function(s1, s2, n1, n2) {
round(min(
pf((s1 / s2), (n1 - 1), (n2 - 1)),
pf((s1 / s2), (n1 - 1), (n2 - 1),
lower.tail = FALSE
)
) * 2, 4)
}
indpool <- function(n1, n2, mean_diff, se_dif) {
df_pooled <- (n1 + n2) - 2
t_pooled <- mean_diff / se_dif
sig_pooled_l <- round(pt(t_pooled, df_pooled), 4)
sig_pooled_u <- round(pt(t_pooled, df_pooled, lower.tail = FALSE), 4)
if (sig_pooled_l < 0.5) {
sig_pooled <- round(pt(t_pooled, df_pooled) * 2, 4)
} else {
sig_pooled <- round(pt(t_pooled, df_pooled, lower.tail = FALSE) * 2, 4)
}
list(df_pooled = df_pooled,
sig_pooled_l = sig_pooled_l,
sig_pooled_u = sig_pooled_u,
sig_pooled = sig_pooled,
t_pooled = t_pooled)
}
check_x <- function(data, x) {
!is.factor(data[[x]])
}
check_level <- function(data, x) {
nlevels(data[[x]])
}
|
CACEcov <- function(Y, D, Z, X, grp = NULL, data = parent.frame(),
robust = FALSE, fast = TRUE){
call <- match.call()
Y <- matrix(eval(call$Y, data), ncol = 1)
N <- nrow(Y)
D <- matrix(eval(call$D, data), ncol = 1)
X <- model.matrix(X, data = data)
Z <- cbind(X, matrix(eval(call$Z, data), nrow = N))
X <- cbind(X, D)
grp <- eval(call$grp, data)
if (!is.null(grp)) {
sgrp <- sort(grp, index.return = TRUE)
grp <- grp[sgrp$ix]
X <- X[sgrp$ix,]
Z <- Z[sgrp$ix,]
D <- D[sgrp$ix,]
Y <- Y[sgrp$ix,]
}
dhat <- fitted(tmp <- lm(D ~ -1 + Z))
beta <- coef(lm(Y ~ -1 + X[,-ncol(X)] + dhat))
ZZinv <- (vcov(tmp)/(summary(tmp)$sigma^2))
XZ <- t(X) %*% Z
XPzXinv <- solve(XZ %*% ZZinv %*% t(XZ))
epsilon <- c(Y - X %*% beta)
est <- beta[length(beta)]
if (is.null(grp)) {
if (robust) {
if (fast)
ZOmegaZ <- t(Z) %*% diag(epsilon^2) %*% Z
else {
ZOmegaZ <- matrix(0, ncol = ncol(Z), nrow = ncol(Z))
for (i in 1:nrow(Z))
ZOmegaZ <- ZOmegaZ + crossprod(matrix(Z[i,], nrow = 1)) * epsilon[i]^2
}
var <- XPzXinv %*% XZ %*% ZZinv
var <- var %*% ZOmegaZ %*% t(var)
} else {
sig2 <- c(crossprod(epsilon))/ N
var <- sig2 * XPzXinv
}
} else {
n.grp <- length(unique(grp))
if (fast) {
Omega <- matrix(0, ncol = N, nrow = N)
counter <- 1
for (i in 1:n.grp) {
n.grp.obs <- sum(grp == unique(grp)[i])
Omega[counter:(counter+n.grp.obs-1),counter:(counter+n.grp.obs-1)] <-
epsilon[grp == unique(grp)[i]] %*% t(epsilon[grp == unique(grp)[i]])
counter <- counter + n.grp.obs
}
ZOmegaZ <- t(Z) %*% Omega %*% Z
} else {
ZOmegaZ <- matrix(0, ncol = ncol(Z), nrow = ncol(Z))
for (i in 1:n.grp) {
ZOmegaZ <- ZOmegaZ + t(Z[grp == unique(grp)[i],]) %*%
(epsilon[grp == unique(grp)[i]] %*% t(epsilon[grp == unique(grp)[i]])) %*%
Z[grp == unique(grp)[i],]
}
}
var <- XPzXinv %*% XZ %*% ZZinv
var <- var %*% ZOmegaZ %*% t(var)
}
names(est) <- "CACE"
return(list(est = est, var = var[nrow(var),ncol(var)]))
}
|
getSimilarity = function(x) UseMethod("getSimilarity")
getSimilarity.TopicSimilarity = function(x){
x$sims
}
getRelevantWords = function(x) UseMethod("getRelevantWords")
getRelevantWords.TopicSimilarity = function(x){
x$wordslimit
}
getConsideredWords = function(x) UseMethod("getConsideredWords")
getConsideredWords.TopicSimilarity = function(x){
x$wordsconsidered
}
getParam.TopicSimilarity = function(x){
x$param
}
|
testdat <- iris[1:5, ]
testdatatt <- attributes(testdat)
testdat <- rtf_body(testdat,
border_left = "single",
border_right = "double",
border_top = "double",
border_bottom = "dot",
border_color_left = "black",
border_color_right = "red",
border_color_top = "green",
border_color_bottom = "gold",
border_width = 1440,
text_font = 2,
text_format = "iub",
text_color = "greenyellow",
text_justification = "l",
text_font_size = 12,
text_space_before = 10,
text_space_after = 10,
text_background_color = "lightgoldenrod",
text_convert = matrix(TRUE, nrow(testdat), ncol(testdat)),
cell_justification = "r",
col_rel_width = c(1, 2, 3, 4, 5),
cell_height = 2
)
testdat2 <- rtf_table_content(
tbl = testdat,
use_border_bottom = TRUE
)
test_that("RTF table content generation", {
expect_snapshot_output(testdat2)
})
|
library("exactRankTests")
suppressWarnings(RNGversion("3.5.3"))
set.seed(29081975)
hansi <- c()
seppl <- c()
for (i in 1:10)
{
m <- sample(10:50, 1)
score <- sample(m)
val <- sample(0:m, 1)
hansi <- c(hansi, psignrank(val, m))
cat("psignrank: ", hansi[length(hansi)])
seppl <- c(seppl, pperm(val, score, m, alternative="less"))
cat(" pperm: ", seppl[length(seppl)], "\n")
}
stopifnot(max(abs(hansi - seppl)) <= 1e-10)
hansi <- c()
seppl <- c()
for (i in 1:10)
{
m <- sample(10:50, 1)
score <- sample(m)
prob <- runif(1)
hansi <- c(hansi, qsignrank(prob, m))
cat("qwilcox: ", hansi[length(hansi)])
seppl <- c(seppl, qperm(prob, score, m))
cat(" qperm: ", seppl[length(seppl)], "\n")
}
stopifnot(max(abs(hansi - seppl)) <= 1e-10)
hansi <- c()
seppl <- c()
for (i in 1:10)
{
m <- sample(10:50, 1)
if (runif(1) < 0.5)
n <- sample(10:50, 1)
else
n <- m
score <- sample(n+m)
val <- sample(0:(m*n), 1)
hansi <- c(hansi, pwilcox(val, m, n))
cat("pwilcox: ", hansi[length(hansi)])
seppl <- c(seppl, pperm(val + m*(m+1)/2, score, m,
alternative="less"))
cat(" pperm: ", seppl[length(seppl)], "\n")
}
stopifnot(max(abs(hansi - seppl)) <= 1e-10)
hansi <- c()
seppl <- c()
for (i in 1:10)
{
m <- sample(10:50, 1)
if (runif(1) < 0.5)
n <- sample(10:50, 1)
else
n <- m
score <- sample(n+m)
prob <- runif(1)
hansi <- c(hansi, qwilcox(prob, m, n))
cat("qwilcox: ", hansi[length(hansi)])
seppl <- c(seppl, qperm(prob, score, m) - m*(m+1)/2)
cat(" qperm: ", seppl[length(seppl)], "\n")
}
stopifnot(max(abs(hansi - seppl)) <= 1e-10)
for (i in 1:20) {
x <- rnorm(10)
y <- rnorm(10)
group <- factor(c(rep(0, 10), rep(1, 10)))
stopifnot(all.equal(wilcox.test(x,y)$p.value, wilcox.exact(x,y)$p.value))
stopifnot(all.equal(wilcox.test(y)$p.value, wilcox.exact(y)$p.value))
r <- rank(c(x,y))
stopifnot(all.equal(wilcox.test(r ~ group)$p.value,
perm.test(r ~ group)$p.value))
}
if (FALSE) {
dansari <- function(x, m ,n)
{
.C(dansari, as.integer(length(x)), d = as.double(x), as.integer(m),
as.integer(n))$d
}
n <- 10
x <- rnorm(n, 2, 1)
y <- rnorm(n, 2, 2)
sc <- cscores(c(x,y), type="Ansari")
dabexac <- dperm(0:(n*(2*n+1)/2), sc, n)
sum(dabexac)
tr <- which(dabexac > 0)
dab <- dansari(0:(n*(2*n+1)/2), n, n)
stopifnot(all.equal(max(abs(dab[tr] - dabexac[tr])), 0))
}
|
VarWT <- function(dataTox, saveName = NULL){
saveResult <-function(saveName, dataFrame){
write.table(dataFrame, file = paste(saveName,".txt", sep = ""), sep = "\t")
}
sigma2 <- NULL
V1 <- NULL
V2 <- NULL
varwtdlt <- NULL
n <- NULL
analyf0 <- dataTox[order(dataTox$simulation), ]
analyf0$dlt = rep(0, nrow(analyf0))
analyf0$lagr = rep(0, nrow(analyf0))
nrow = which(analyf0$n>0)
first.trial = findFirstLast(analyf0)$Trial
total = rep(1:nrow(analyf0))
total = total[-c(nrow, first.trial)]
analyf0$dlt[nrow] = analyf0$x[nrow]/analyf0$n[nrow]
analyf0$lagr[nrow] = analyf0$dlt[nrow]
analyf0$dlt[first.trial] = 0
analyf0$lagr[first.trial] = analyf0$dlt[first.trial]
for(k in total){
analyf0$dlt[k] = analyf0$lagr[k-1]
analyf0$lagr[k] = analyf0$dlt[k]
}
zkodltvar <- analyf0
colNum_lagr <- which(colnames(zkodltvar) == "lagr")
zkodltvar <- zkodltvar[, -colNum_lagr]
zkodltvar$sigma2 <- analyf0$n * analyf0$dlt * (1 - analyf0$dlt)
zkodltvar
colNum_Simu <- which(colnames(zkodltvar) == "simulation")
colNum_dose <- which(colnames(zkodltvar) == "dose")
colNum_sigma2 <- which(colnames(zkodltvar) == "sigma2")
varsum <- do.call(data.table, c(lapply(unname(zkodltvar[colNum_Simu:colNum_dose]), as.numeric), zkodltvar[colNum_sigma2]))
varsum <- varsum[, .(sigma2 = sum(sigma2)), by= .(V1, V2)]
colnames(varsum) <- c("simulation", "dose", "sumsigma2")
varsum = as.data.frame(varsum)
zkodltvar <- zkodltvar[order(zkodltvar$simulation, zkodltvar$dose),]
varmerge <- merge(zkodltvar, varsum, by = c("simulation", "dose"))
varweight <- varmerge
varweight$varwt <- ifelse(varweight$sumsigma2 == 0,
1/20,
varweight$sigma2 / varweight$sumsigma2
)
varweight$varwtdlt <- varweight$varwt * varweight$dlt
colNum_Simu2 <- which(colnames(varweight) == "simulation")
colNum_dose2 <- which(colnames(varweight) == "dose")
colNum_n <- which(colnames(varweight) == "n")
colNum_varwtdlt <- which(colnames(varweight) == "varwtdlt")
vardlt1 <- do.call(data.table, c(lapply(unname(varweight[c(colNum_Simu2,colNum_dose2)]), as.numeric), varweight[colNum_varwtdlt]))
vardlt1 <- vardlt1[, .(varwtdlt = sum(varwtdlt)), by= .(V1, V2)]
colnames(vardlt1) <- c("simulation", "dose", "dltvar")
vardlt2 <- do.call(data.table, c(lapply(unname(varweight[c(colNum_Simu2,colNum_dose2)]), as.numeric), varweight[colNum_n]))
vardlt2 <- vardlt2[, .(n = sum(n)), by= .(V1, V2)]
colnames(vardlt2) <- c("simulation", "dose", "totaln")
vardlt <- merge(vardlt2, vardlt1, by = c("simulation", "dose"))
vardlt = as.data.frame(vardlt)
if(is.null(saveName) == "FALSE"){
saveResult(saveName, vardlt)
}
return(list(dataTox = vardlt))
}
|
source('../gsDesign_independent_code.R')
testthat::test_that(desc = "Test: checking class object gsDesign or gsProbability",
code = {
x <- seq(1, 2, 0.5)
local_edition(3)
expect_error(gsCPOS(x,i = 1, theta = c(-1.50, -0.75, 0.00, 0.75, 1.50),
wgts = c(0.064758798, 0.301137432, 0.199471140, 0.301137432, 0.064758798)
))
})
testthat::test_that(desc = "Test: checking lengths of input", code = {
x <- gsDesign(k = 3, test.type = 2, n.fix = 800)
local_edition(3)
expect_error(gsCPOS(x, i = 1, theta = c(-1.50, -0.75, 0.75, 1.50),
wgts = c(0.064758798, 0.301137432, 0.199471140, 0.301137432, 0.064758798)
))
})
testthat::test_that(desc = "Test: checking out of range i ", code = {
x <- gsDesign(k = 3, test.type = 1, n.fix = 800)
local_edition(3)
expect_error(gsCPOS(x, i = 4, theta = c(-1.50, -0.75, 0.75, 1.50),
wgts = c(0.064758798, 0.01137432, 0.199471140, 0.301137432)
))
})
testthat::test_that(desc = "Test: output validation
source: gsDesign_independent_code.R", code = {
x <- gsDesign(k = 3, test.type = 2, n.fix = 800)
theta = c(-1.50, -0.75, 0.00, 0.75, 1.50)
wgts = c(0.064758798, 0.301137432, 0.199471140, 0.301137432, 0.064758798)
i <- 2
local_edition(3)
CPOS <- gsCPOS(x, i = 2, theta = theta, wgts = wgts)
expected_CPOS <- validate_gsCPOS(x, theta, wgts, i)
expect_equal(CPOS , expected_CPOS[1])
})
|
set.seed(0)
options(digits=4)
quadForm <- function(D) {
C <- seq(1, N)
return( - t(D - C) %*% W %*% ( D - C) )
}
N <- 3
library(maxLik)
W <- diag(N)
D <- rep(1/N, N)
res <- maxBFGSR(quadForm, start=D)
all.equal(coef(res), 1:3, tolerance=1e-4)
all.equal(gradient(res), rep(0,3), tolerance=1e-3)
all.equal(nIter(res) < 100, TRUE)
all.equal(returnCode(res) < 4, TRUE)
hat <- function(param) {
x <- param[1]
y <- param[2]
exp(-(x-2)^2 - (y-2)^2)
}
hatNC <- maxBFGSR(hat, start=c(1,1), tol=0, reltol=0)
all.equal(coef(hatNC), rep(2,2), tolerance=1e-4)
all.equal(gradient(hatNC), rep(0,2), tolerance=1e-3)
all.equal(nIter(hatNC) < 100, TRUE)
all.equal(returnCode(hatNC) < 4, TRUE)
hat3 <- function(param) {
x <- param[1]
y <- param[2]
z <- param[3]
exp(-(x-2)^2-(y-2)^2-(z-2)^2)
}
sv <- c(x=1,y=1,z=1)
A <- matrix(c(1,1,1), 1, 3)
B <- -8
constraints <- list(eqA=A, eqB=B)
hat3CF <- maxBFGSR(hat3, start=sv, constraints=constraints, fixed=3)
all.equal(coef(hat3CF), c(x=3.5, y=3.5, z=1), tolerance=1e-4)
all.equal(nIter(hat3CF) < 100, TRUE)
all.equal(returnCode(hat3CF) < 4, TRUE)
all.equal(sum(coef(hat3CF)), 8, tolerance=1e-4)
|
circdensity <- function(x, sigma="nrd0", ..., bw=NULL,
weights=NULL,
unit=c("degree", "radian")) {
xname <- short.deparse(substitute(x))
missu <- missing(unit)
if(missing(sigma) && !is.null(bw))
sigma <- bw
unit <- match.arg(unit)
unit <- validate.angles(x, unit, missu)
FullCircle <- switch(unit, degree = 360, radian = 2*pi)
if(is.character(sigma)) {
sigma <- switch(sigma,
bcv = bw.bcv,
nrd = bw.nrd,
nrd0 = bw.nrd0,
SJ = bw.SJ,
ucv = bw.ucv,
get(paste0("bw.", sigma), mode="function"))
}
if(is.function(sigma)) {
sigma <- sigma(x)
if(!(is.numeric(sigma) && length(sigma) == 1L && sigma > 0))
stop("Bandwidth selector should return a single positive number")
}
check.1.real(sigma)
x <- x %% FullCircle
xx <- c(x - FullCircle, x, x + FullCircle)
if(!is.null(weights)) {
stopifnot(length(weights) == length(x))
weights <- rep(weights, 3)/3
}
z <- do.call(density.default,
resolve.defaults(list(x=xx, bw=sigma, weights=weights),
list(...),
list(from=0, to=FullCircle)))
z$y <- 3 * z$y
z$data.name <- xname
return(z)
}
|
node_insert <- function(tree, node.name, ...) {
the.parent <- node_set(tree, node.name)$parent
if (is.null(the.parent)) {
warning("Li: the non-root node having the name specified is not found.")
return()
}
tmp.parent <- Clone(the.parent)
sibling.node.names <- sapply(the.parent$children, function(x) x$name)
for (name.k in sibling.node.names) {
node_prune(the.parent, name.k)
}
for (name.k in sibling.node.names) {
if (name.k == node.name) {
new.nodes <- list(...)
lapply(new.nodes, function(x) {
switch(class(x)[1],
"character" = {
the.parent$AddChild(x)
},
"R6" = ,
"Node" = {
the.parent$AddChildNode(x)
},
stop("Li: the class of the new node is wrong.")
)
})
}
the.parent$AddChildNode(node_set(tmp.parent, name.k))
}
invisible(the.parent)
}
|
test_that("can set path to local config", {
tmp <- tempdir()
test.pkg <- fs::dir_create(tmp, "test.proj")
expect_equal(
set_config_source(NULL, root = test.pkg),
system.file("pre-commit-config-proj.yaml", package = "precommit")
)
expect_error(
set_config_source(tempfile()),
"does not exist"
)
})
test_that("can set path to remote config", {
skip_on_cran()
path <- set_config_source(
example_remote_config()
)
expect_equal(fs::path_ext(path), "yaml")
expect_silent(yaml::read_yaml(path))
expect_error(set_config_source("https://apple.com"), "valid yaml")
})
test_that("defaults to right config depending on whether or not root is a pkg", {
tmp <- tempdir()
test.pkg <- fs::dir_create(tmp, "test.pkg")
withr::with_dir(test.pkg, {
desc <- desc::description$new("!new")
desc$set(Package = "test.pkg")
desc$write("DESCRIPTION")
})
expect_message(
set_config_source(NULL, root = test.pkg),
"pkg\\.yaml"
)
fs::file_delete(fs::path(test.pkg, "DESCRIPTION"))
expect_message(
set_config_source(NULL, root = test.pkg),
"proj\\.yaml"
)
})
test_that(".Rbuildignore is written to the right directory when root is relative", {
root <- tempfile()
fs::dir_create(root)
withr::with_dir(root, {
desc <- desc::description$new("!new")
desc$set(Package = "test.pkg")
desc$write("DESCRIPTION")
})
withr::with_dir(
fs::path_dir(root),
use_precommit_config(root = fs::path_file(root))
)
expect_true(file_exists(fs::path(root, ".Rbuildignore")))
})
test_that(".Rbuildignore is written to the right directory when root is absolute", {
root <- tempfile()
fs::dir_create(root)
withr::with_dir(root, {
desc <- desc::description$new("!new")
desc$set(Package = "test.pkg")
desc$write("DESCRIPTION")
})
use_precommit_config(root = root)
expect_true(file_exists(fs::path(root, ".Rbuildignore")))
})
|
EM.Iter <-
function(sdata,Xp,r,n.int,order,max.iter,cov.rate){
P<-ncol(Xp)
L<-n.int+order
N<-nrow(sdata)
b0<-rep(0,P)
g0<-rep(1,L)
r.mat<-function(x) matrix(x,ncol=N,nrow=L,byrow=TRUE)
c.mat<-function(x) matrix(x,ncol=N,nrow=L)
ti <- c(sdata$Li[sdata$d2 == 1], sdata$Ri[sdata$d3 == 0])
knots <-quantile(ti,seq(0,1,length.out = (n.int + 2)))
bl.Li<-bl.Ri<-matrix(0,nrow=L,ncol=N)
bl.Li[,sdata$d1==0]<-Ispline(sdata$Li[sdata$d1==0],order=order,knots=knots)
bl.Ri[,sdata$d3==0]<-Ispline(sdata$Ri[sdata$d3==0],order=order,knots=knots)
dif<-numeric()
est.par<-matrix(ncol=ncol(Xp)+L,nrow=max.iter)
ll<-numeric()
dd<-1
ii<-0
while(dd>cov.rate & ii<max.iter){
ii<-ii+1
Lamd.Li<-t(bl.Li)%*%matrix(g0,ncol=1)
Lamd.Ri<-t(bl.Ri)%*%matrix(g0,ncol=1)
exb<-exp(Xp%*%b0)
lambdai<-r*exb*(sdata$d1*Lamd.Ri+sdata$d2*Lamd.Li)
omegai<-r*exb*(sdata$d2*(Lamd.Ri-Lamd.Li)+sdata$d3*Lamd.Li)
lambdail<-c.mat(g0)*r.mat(r*exb)*(r.mat(sdata$d1)*bl.Ri+r.mat(sdata$d2)*bl.Li)
omegail<-c.mat(g0)*r.mat(r*exb)*(r.mat(sdata$d2)*(bl.Ri-bl.Li)+r.mat(sdata$d3)*bl.Li)
Eyi<-sdata$d1*lambdai/r/(sdata$d1*(1-(1+lambdai)^(-1/r))+1-sdata$d1)
Ewi<-sdata$d2*omegai/r/(1+lambdai)/(sdata$d2*(1-((1+lambdai)/(1+lambdai+omegai))^(1/r))+1-sdata$d2)
pc1<-sdata$d1*(1-(1+lambdai)^(-1/r-1))/r/(sdata$d1*(1-(1+lambdai)^(-1/r))+1-sdata$d1)
pc2<-sdata$d2*((1+lambdai)^(-1/r-1)-(1+lambdai+omegai)^(-1/r-1))/r/(sdata$d2*((1+lambdai)^(-1/r)-(1+lambdai+omegai)^(-1/r))+1-sdata$d2)
pc3<-sdata$d3*(1+omegai)^(-1)/r
Efi<-pc1+pc2+pc3
Eyil<-r.mat(sdata$d1/r/(sdata$d1*(1-(1+lambdai)^(-1/r))+1-sdata$d1))*lambdail
Ewil<-r.mat(sdata$d2/r/(1+lambdai)/(sdata$d2*(1-((1+lambdai)/(1+lambdai+omegai))^(1/r))+1-sdata$d2))*omegail
fit<-nlm(bb.gamma,p=b0,sdata=sdata,Xp=Xp,Eyil=Eyil,Ewil=Ewil,Efi=Efi,r=r,bl.Li=bl.Li,bl.Ri=bl.Ri)
if(!is.character(fit)){
b0<-fit$estimate
g0<-gg.beta(bb=b0,sdata=sdata,Xp=Xp,Eyil=Eyil,Ewil=Ewil,Efi=Efi,r=r,bl.Li=bl.Li,bl.Ri=bl.Ri)
est.par[ii,]<-c(b0,g0)
ll<-c(ll,loglik(x0=c(b0,g0),sdata=sdata,Xp=Xp,r=r,bl.Li=bl.Li,bl.Ri=bl.Ri))
}
if(ii>2) dd<-abs(ll[ii]-ll[ii-1])
}
loglik<-ll[ii]
AIC<-2*(L+P)-2*loglik
Hessian<-Louis.VCOV(b0=b0,g0=g0,sdata=sdata,r=r,Xp=Xp,bl.Li=bl.Li,bl.Ri=bl.Ri)
return(list(Beta=b0,gl=g0,Hessian=Hessian,AIC=AIC,loglik=loglik,r=r,n.int=n.int,order=order,knots=knots,sdata=sdata,Xp=Xp,bl.Li=bl.Li,bl.Ri=bl.Ri))
}
|
vi.fun<-function(X){
data.frame(vi=var(X)/mean(X)^2)
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
message = TRUE
)
library(ggplot2)
library(data.table)
library(magrittr)
library(latrend)
knitr::opts_chunk$set(
cache = TRUE,
collapse = TRUE,
comment = "
)
library(latrend)
library(data.table)
options(
latrend.id = "Traj",
latrend.time = "Time",
latrend.verbose = TRUE
)
set.seed(1)
casedata <- generateLongData(
sizes = c(40, 60),
data = data.frame(Time = 0:10),
fixed = Y ~ 1,
fixedCoefs = 1,
cluster = ~ Time,
clusterCoefs = cbind(c(2, -.1), c(0, .05)),
random = ~ Time,
randomScales = cbind(c(.2, .02), c(.2, .02)),
noiseScales = .05
) %>%
as.data.table()
plotTrajectories(casedata, response = "Y")
plotClusterTrajectories(casedata, response = "Y", cluster = "Class")
ggplot(casedata[Time == 0], aes(x = Mu)) +
geom_density(fill = "gray", adjust = .3)
method <- lcMethodStratify(response = "Y", Y[1] > 1.6)
model <- latrend(method, casedata)
clusterProportions(model)
stratfun <- function(data) {
int <- coef(lm(Y ~ Time, data))[1]
factor(int > 1.7,
levels = c(FALSE, TRUE),
labels = c("Low", "High"))
}
m2 <- lcMethodStratify(response = "Y", stratify = stratfun, center = mean)
model2 <- latrend(m2, casedata)
clusterProportions(model2)
casedata[, Intercept := coef(lm(Y ~ Time, .SD))[1], by = Traj]
m3 <- lcMethodStratify(
response = "Y",
stratify = Intercept[1] > 1.7,
clusterNames = c("Low", "High")
)
model3 <- latrend(m3, casedata)
repStep <- function(method, data, verbose) {
dt <- as.data.table(data)
coefdata <- dt[, lm(Y ~ Time, .SD) %>% coef() %>% as.list(), keyby = Traj]
coefmat <- subset(coefdata, select = -1) %>% as.matrix()
rownames(coefmat) <- coefdata$Traj
return(coefmat)
}
clusStep <- function(method, data, repMat, envir, verbose) {
km <- kmeans(repMat, centers = 3)
lcModelCustom(
response = method$response,
method = method,
data = data,
trajectoryAssignments = km$cluster,
clusterTrajectories = method$center,
model = km
)
}
m.twostep <- lcMethodFeature(
response = "Y",
representationStep = repStep,
clusterStep = clusStep
)
model.twostep <- latrend(m.twostep, data = casedata)
summary(model.twostep)
repStep.gen <- function(method, data, verbose) {
dt <- as.data.table(data)
coefdata <- dt[, lm(method$formula, .SD) %>% coef() %>% as.list(), keyby = c(method$id)]
coefmat <- subset(coefdata, select = -1) %>% as.matrix()
rownames(coefmat) <- coefdata[[method$id]]
return(coefmat)
}
clusStep.gen <- function(method, data, repMat, envir, verbose) {
km <- kmeans(repMat, centers = method$nClusters)
lcModelCustom(
response = method$response,
method = method,
data = data,
trajectoryAssignments = km$cluster,
clusterTrajectories = method$center,
model = km
)
}
m.twostepgen <- lcMethodFeature(
response = "Y",
representationStep = repStep.gen,
clusterStep = clusStep.gen
)
model.twostepgen <- latrend(m.twostepgen, formula = Y ~ Time, nClusters = 2, casedata)
summary(model.twostepgen)
setClass("lcMethodSimpleGBTM", contains = "lcMethod")
lcMethodSimpleGBTM <- function(...) {
mc = match.call()
mc$Class = 'lcMethodSimpleGBTM'
do.call(new, as.list(mc))
}
setMethod("getArgumentDefaults", "lcMethodSimpleGBTM", function(object, ...) {
list(
formula = Value ~ Time,
time = getOption("latrend.time"),
id = getOption("latrend.id"),
nClusters = 2,
nwg = FALSE
)
})
setMethod("getName", "lcMethodSimpleGBTM",
function(object, ...) "simple group-based trajectory model")
setMethod("getShortName", "lcMethodSimpleGBTM", function(object, ...) "sgbtm")
setMethod("prepareData", "lcMethodSimpleGBTM", function(method, data, verbose, ...) {
envir <- new.env()
envir$data <- as.data.frame(data)
envir$data[[method$id]] <- factor(data[[method$id]]) %>% as.integer()
return(envir)
})
setMethod("fit", "lcMethodSimpleGBTM", function(method, data, envir, verbose, ...) {
args <- as.list(method, args = lcmm::lcmm)
args$data <- envir$data
args$fixed <- method$formula
if (method$nClusters > 1) {
args$mixture <- update(method$formula, NULL ~ .)
} else {
args$mixture <- NULL
}
args$subject <- method$id
args$ng <- method$nClusters
args$returndata <- TRUE
model <- do.call(lcmm::lcmm, args)
new(
"lcModelSimpleGBTM",
method = method,
data = data,
model = model,
clusterNames = LETTERS[seq_len(method$nClusters)]
)
})
setClass("lcModelSimpleGBTM", contains = "lcModel")
slotNames("lcModelSimpleGBTM")
fitted.lcModelSimpleGBTM <- function(object, clusters = trajectoryAssignments(object)) {
predNames <- paste0("pred_m", 1:nClusters(object))
predMat <- as.matrix(object@model$pred[predNames])
colnames(predMat) <- clusterNames(object)
transformFitted(pred = predMat, model = object, clusters = clusters)
}
setMethod("predictForCluster", "lcModelSimpleGBTM", function(
object, newdata, cluster, what = 'mu', ...)
{
predMat = lcmm::predictY(object@model, newdata = newdata)$pred %>%
set_colnames(clusterNames(object))
clusIdx = match(cluster, clusterNames(object))
predMat[, clusIdx]
})
setMethod("postprob", signature("lcModelSimpleGBTM"), function(object) {
as.matrix(object@model$pprob)[, c(-1, -2), drop = FALSE]
})
setMethod("converged", signature("lcModelSimpleGBTM"), function(object, ...) {
object@model$conv
})
m <- lcMethodSimpleGBTM(formula = Y ~ Time)
show(m)
sgbtm <- latrend(m, casedata)
summary(sgbtm)
plot(sgbtm)
|
GENMETA.control <- function(epsilon = 1e-06, maxit = 1000)
{
return(list(epsilon = epsilon, maxit = maxit))
}
|
str <- "abc abc cba cba bac xxx abc abc cba cba bac"
test_that("RePair test
grammar <- str_to_repair_grammar(str)
expect_equal("R4 xxx R4", grammar[[1]]$rule_string)
expect_equal("R3", grammar[[4]]$rule_string)
})
|
parent_representation = function(node_number, rep_matrix, nodiv_data, metric = c("rval", "SR"))
{
desc = Descendants(node_number, nodiv_data)
if (desc[1] < basal_node(nodiv_data) | desc[2] < basal_node(nodiv_data))
return(rep(NA, nrow(rep_matrix)))
desc1col = desc[1] - Nspecies(nodiv_data)
desc2col = desc[2] - Nspecies(nodiv_data)
desc1 = rep_matrix[,desc1col]
desc2 = -rep_matrix[, desc2col]
if (metric == "rval")
desc2 = desc2 + 1
return(rowMeans(cbind(desc1, desc2)))
}
nodenames <- function(nodiv_data)
{
ret <- nodenumbers(nodiv_data)
if (!is.null(nodiv_data$phylo$node.label))
ret <- paste(ret, nodiv_data$phylo$node.label)
ret
}
nodiv_res <- function(results, nodiv_data, repeats, method)
{
ret <- nodiv_data
class(ret) <- c("nodiv_result", class(nodiv_data))
ret$method <- method
ret$repeats <- repeats
SR <- sapply(results, "[[", 1)
ret$SOS <- sapply(nodenumbers(nodiv_data), function(node) parent_representation(node, SR, nodiv_data, metric = "SR"))
colnames(ret$SOS) <- nodenames(nodiv_data)
rownames(ret$SOS) <- nodiv_data$coords$sites
rval <- sapply(results, "[[", 2)
par_rval <- sapply(nodenumbers(nodiv_data), function(node) parent_representation(node, rval, nodiv_data, metric = "rval"))
pval <- apply(par_rval, 2, pval_sig)
pval[pval > 1-2/repeats] <- 1-2/repeats
pval[pval < 2/repeats] <- 2/repeats
ret$GND <- apply(pval, 2, function(x) 1-inv_logit(mean(logit(x), na.rm = T)))
return(ret)
}
|
require(knitr)
old_ops <- options(width=80)
set.seed(1121)
stdt<-date()
library(intcensROC)
U <- runif(100, min = 0.1, max = 5)
V <- runif(100, min = 0.1, max = 5) + U
Marker <- runif(100, min = 5, max = 10)
Delta <- sample.int(3, size = 100, replace = TRUE)
pTime <- 4
res <- intcensROC(U, V, Marker, Delta, pTime, gridNumber = 500)
head(res)
auc <- intcensAUC(res)
print(auc)
library("copula")
f <- function(x, L0, rate, censor){
1/((x-L0)*rate)*exp(-L0*rate)-1/((x-L0)*rate)*exp(-x*rate)-censor
}
dataSim <- function(kendall_tau = 0.3, n = 100, rho = 0.3, lambda = log(2)/6){
b_alpha <- 2.35
b_beta <- 1.87
scale <- 10
kendall_tau <- iTau( claytonCopula(), kendall_tau)
Int_cop <- claytonCopula(param = kendall_tau, dim = 2)
Int_mvdc <- mvdc(Int_cop, c("exp","beta"), paramMargins =
list(list(rate = lambda), list(shape1=b_alpha,shape2=b_beta)))
Int_obs_data <- rMvdc(n, Int_mvdc)
colnames(Int_obs_data) <- c("event_time", "marker")
Int_obs_data[,"marker"] <- Int_obs_data[,"marker"]*scale
L0 <-0.1
size <-n
U <-rep(0,size)
L <-uniroot(f, lower = 10^(-6), upper = 500, tol=0.000001,
L0=L0, rate=lambda, censor=rho)
V <-runif(size,L0,L$root)
for (i in 1:size) U[i] <-runif(1,0,(V[i]-L0))
delta_1 <- Int_obs_data[ ,"event_time"] < U
delta_2 <- Int_obs_data[ ,"event_time"] >= U&
Int_obs_data[ ,"event_time"] <= V
delta_3 <- Int_obs_data[ ,"event_time"] > V
data <- data.frame(U = U, V = V, delta = delta_1+2*delta_2+3*delta_3,
marker=Int_obs_data[,"marker"])
}
mydata <- dataSim(kendall_tau = 0.7, n = 300, rho = 0.3, lambda = log(2)/24)
roc <- intcensROC(U=mydata[,"U"],V=mydata[,"V"], Marker=mydata[,"marker"],
Delta=mydata[,"delta"], PredictTime=12)
print(intcensAUC(roc))
plot(roc$fp, roc$tp, type = "l", lwd = 1.2, col="blue", main = "Example ROC",
xlab = "False Positive Rate", ylab = "True Positive Rate" )
toLatex(sessionInfo(), locale=FALSE)
print(paste("Start Time",stdt))
print(paste("End Time ",date()))
options(old_ops)
|
library(checkargs)
context("isNumberScalarOrNull")
test_that("isNumberScalarOrNull works for all arguments", {
expect_identical(isNumberScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNumberScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNumberScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNumberScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
})
|
setMethod(f="plot",signature=c(x="cold",y="missing"),
definition=function(x,which=c(1:3),xlab=NULL,ylab=NULL,main=NULL,
factor,subSET,ident=FALSE,caption=c("Individual mean profiles"),
cex.caption=1)
{
if (!is.numeric(which) || any(which < 1) || any(which > 3))
stop("'which' must be in 1:3")
if(missing(which))
{which=1}
show <- rep(FALSE, 3)
show[which] <- TRUE
x2<-x@Fitted
depend<- x@call$dependence
subset1<-x@call$subSET
time<-x@Time
x3<-unique(x@Time)
n.time<-length(x3)
x4<-unique([email protected])
n.id<[email protected]
data<[email protected]
data$id<[email protected]
data$y<-as.vector(t([email protected]))
id.new<-unique(data$id)
n<-dim(x4)[1]
if(missing(factor))
{ ncurves<-1
trace.label=" "}
if(!missing(factor))
{
factor1 <- deparse(substitute(factor))
f.value <- as.factor(data[[factor1]])
f<-f.value
level.f<-unique(f)
nlevel.f<-length(unique(f))
levg<-as.vector(level.f)
colg<-seq(1:nlevel.f)
ncurves<-nlevel.f
if (length(factor1)==0 && length(subset1)==0)
{ trace.label=" "}
else if(length(factor1)==0 && length(subset1)!=0)
{trace.label=deparse(substitute(subset1))}
else if (length(factor1)!=0)
{trace.label=deparse(substitute(factor))}
}
aa<-matrix(x@Fitted,n.id,n.time,byrow=TRUE)
aanew<-numeric(n.id)
x3new<-numeric(n.id)
pos.id<-seq(1:n.id)
id.numb<-unique(data$id)
afit<-data.frame(id.numb,pos.id,aa)
xlab2<-"Time"
if (any(show[1:2])){
if(length(ylab)==0) ylab="Number"
else ylab<-ylab
if(length(main)==0) main=" "
else main<-main
}
if (any(show[1:2])){
if(length(xlab)==0) xlab="Time"
else xlab<-xlab
if(length(main)==0) main=" "
else main<-main
}
if(show[1]) {
coef<-x@coefficients
npar <-length(coef)
omega<-as.double(coef[npar])
n.col<-ncol(x4)
coef1<-as.double(x@coefficients[1:n.col])
eta<-x4%*%coef1
n.time<-length(x3)
l<-exp(eta)
ylim<-range(l,na.rm=TRUE)
ylim<-extendrange(l,f=0.08)
plot(x3,c(0,rep(1,n.time-1)), type="n", xlab=xlab,ylab=ylab,
main=" ",ylim=ylim)
mtext(main,side=3,0.25, cex=1)
n1<-1
n2<-n.time
p<-round(ylim[2])
p1<-ylim[2]-0.08
for(j1 in 1:ncurves)
{
n2<-j1*(n.time)
lines(x3,exp(eta[n1:n2]),col="grey60",lty=j1,lwd=1.25)
n1<-n2+1
}
if(ncurves>1)
{legend(x3[2],p1,levg,lty=c(seq(1:ncurves)),col="grey60",bty="n",
cex=0.75)}
if(ncurves==1){legend(x3[1],p,paste(trace.label),bty="n",cex=0.75)}
}
if(show[2]) {
if (depend=="ind"||depend=="AR1")
stop("dependence must be indR or AR1R")
l1<-aa
ylim<-range(l1,na.rm=TRUE)
ylim<-extendrange(l1,f=0.05)
plot(x3,c(0,rep(1,n.time-1)), type="n", xlab=xlab,ylab=ylab,main=" ",ylim=ylim)
mtext(main,side=3,0.75, cex=0.8)
if(missing(subSET)){
for(i in 1:n.id) {
lines(x3,aa[i,],col=1,lty=i)
if(i<=n.time){aanew[i]<-aa[i,i]
x3new[i]<-x3[i]}
else{aanew[i]<-aa[i,n.time]
x3new[i]<-x3[n.time]}
}
aanew<-matrix(aanew,n.id,1)
aanew1<-data.frame(id.new,x3new,aanew)
if(ident==TRUE)
{
text(aanew1[,2],aanew1[,3],labels=aanew1[,1],cex=0.8)
}
}
if(!missing(subSET)){
id1 <- eval(substitute(subSET), data)
data<-subset(data, id1)
n.subj<-length(unique(data$id))
id.new1<-unique(data$id)
aanew2<-numeric(n.subj)
x3new1<-numeric(n.subj)
for(j in 1:n.subj) {
id.numbj<-id.new1[j]
i<-afit[afit$id.numb==id.numbj,2]
lines(x3,aa[i,],col=1,lty=i)
if(i<=n.time){aanew2[j]<-aa[i,i]
x3new1[j]<-x3[i]}
else{aanew2[j]<-aa[i,n.time]
x3new1[j]<-x3[n.time]}
}
aanew2<-matrix(aanew2,n.subj,1)
aanew3<-data.frame(id.new1,x3new1,aanew2)
if(ident==TRUE){
text(aanew3[,2],aanew3[,3],labels=aanew3[,1],cex=0.8)}
}
}
if(show[3]) {
if (depend=="ind"||depend=="AR1")
stop("dependence must be indR or AR1R")
if(missing(subSET))
stop("number of id must be given")
l1<-data$y
ylim<-range(l1,na.rm=TRUE)
ylim<-extendrange(l1,f=0.10)
plot(x3,c(0,rep(1,n.time-1)), type="n", xlab=xlab,ylab=ylab,main=" ",ylim=ylim)
mtext(main,side=3,0.75, cex=0.8)
id1 <- eval(substitute(subSET), data)
data<-subset(data, id1)
n.subj<-length(unique(data$id))
id.new1<-unique(data$id)
aanew2<-numeric(n.subj)
x3new1<-numeric(n.subj)
ynew<-data$y
for(j in 1:n.subj) {
id.numbj<-id.new1[j]
i<-afit[afit$id.numb==id.numbj,2]
p2<-round(ylim[2])
p3<-p2-1
points(x3,ynew,pch=19,col="grey50",cex=1.3)
points(x3,aa[i,],pch=19,col="grey70")
if(i<=n.time){aanew2[j]<-aa[i,i]
x3new1[j]<-x3[i]}
else{aanew2[j]<-aa[i,n.time]
x3new1[j]<-x3[n.time]}
}
aanew2<-matrix(aanew2,n.subj,1)
aanew3<-data.frame(id.new1,x3new1,aanew2)
legend(x3[1],p2,c("Observed","Fitted"),pch=c(19,19),col=c("grey50","grey70"),cex=0.8,bty="n")
}
}
)
|
library(copula)
a <- c(1/4, 1/2)
b <- c(1/3, 1)
stopifnot(0 <= a, a <= 1, 0 <= b, b <= 1, a <= b)
ic <- indepCopula()
vol <- prob(ic, l = a, u = b)
p <- (b[1] - a[1]) * (b[2] - a[2])
stopifnot(all.equal(vol, p))
vol. <- prob(indepCopula(dim = 3), l = c(a, 1/8), u = c(b, 3/8))
p. <- p * (3/8 - 1/8)
stopifnot(all.equal(vol., p.))
W <- function(u1, u2) max(u1 + u2 - 1, 0)
vol <- W(b[1], b[2]) - W(b[1], a[2]) - W(a[1], b[2]) + W(a[1], a[2])
p <- sqrt(2*(b[1] - a[1])^2) / sqrt(2)
stopifnot(all.equal(vol, p))
a. <- a
b. <- c(1/3, 1/2)
stopifnot(0 <= a., a. <= 1, 0 <= b., b. <= 1, a.[1]+a.[2] <= 1, b. >= a.)
W(b.[1], b.[2]) - W(b.[1], a.[2]) - W(a.[1], b.[2]) + W(a.[1], a.[2])
a. <- c(2/3, 1/2)
b. <- c(3/4, 3/4)
stopifnot(0 <= a., a. <= 1, 0 <= b., b. <= 1, a.[1]+a.[2] >= 1, b. >= a.)
W(b.[1], b.[2]) - W(b.[1], a.[2]) - W(a.[1], b.[2]) + W(a.[1], a.[2])
nu <- 3
tc <- tCopula(iTau(tCopula(df = nu), tau = 0.5), df = nu)
vol <- prob(tc, l = a, u = b)
p <- pCopula(b, copula = tc) - pCopula(c(b[1], a[2]), copula = tc) -
pCopula(c(a[1], b[2]), copula = tc) + pCopula(a, copula = tc)
stopifnot(all.equal(vol, p))
N <- 1e6
set.seed(271)
U <- rCopula(N, copula = tc)
volMC <- mean(a[1] < U[,1] & U[,1] <= b[1] & a[2] < U[,2] & U[,2] <= b[2])
stopifnot(all.equal(volMC, p, tol = 1e-2))
|
test_that('Xcol argument checking works',{
expect_error(.checkargs(Xcol = 1))
})
test_that('Ycol argument checking works',{
expect_error(.checkargs(Ycol = NA))
})
test_that('Pcol argument checking works',{
expect_error(.checkargs(Pcol = 1))
})
test_that('Spcol argument checking works',{
expect_error(.checkargs(Spcol = 2))
})
test_that('name argument checking works',{
expect_error(.checkargs(name = 1))
})
test_that('Spname argument checking works',{
expect_error(.checkargs(Spname = 1))
})
test_that('PA argument checking works',{
expect_error(.checkargs(PA = 1))
})
test_that('rep argument checking works',{
expect_error(.checkargs(rep = 'deux'))
})
test_that('cv argument checking works',{
expect_error(.checkargs(cv = 4))
})
test_that('cv.param argument checking works',{
expect_error(.checkargs(cv.param = 1))
})
test_that('thresh argument checking works',{
expect_error(.checkargs(thresh = 'thousand'))
})
test_that('metric argument checking works',{
expect_error(.checkargs(metric = 2))
})
test_that('axes.metric argument checking works',{
expect_error(.checkargs(axes.metric = 2))
})
test_that('select argument checking works',{
expect_error(.checkargs(select = 'TRUE'))
})
test_that('select.metric argument checking works',{
expect_error(.checkargs(select.metric = 2))
})
test_that('select.thresh argument checking works',{
expect_error(.checkargs(select.thresh = 'zero'))
})
test_that('verbose argument checking works',{
expect_error(.checkargs(verbose = 'TRUE'))
})
test_that('GUI argument checking works',{
expect_error(.checkargs(GUI = 'TRUE'))
})
test_that('uncertainty argument checking works',{
expect_error(.checkargs(uncertainty = 'TRUE'))
})
test_that('tmp argument checking works',{
expect_error(.checkargs(tmp = 'TRUE'))
})
test_that('ensemble.metric argument checking works',{
expect_error(.checkargs(ensemble.metric = 2))
})
test_that('ensemble.thresh argument checking works',{
expect_error(.checkargs(ensemble.thresh = 'zero'))
})
test_that('weight argument checking works',{
expect_error(.checkargs(weight = 'TRUE'))
})
test_that('method argument checking works',{
expect_error(.checkargs(method = 2))
})
test_that('rep.B argument checking works',{
expect_error(.checkargs(method = 'B', rep.B = 'thousand'))
})
test_that('GeoRes argument checking works',{
expect_error(.checkargs(GeoRes = 'TRUE'))
})
test_that('reso argument checking works',{
expect_error(.checkargs(reso = 'zero'))
})
test_that('file argument checking works',{
expect_error(.checkargs(file = 1))
})
test_that('files argument checking works',{
expect_error(.checkargs(files = 1))
})
test_that('format argument checking works',{
expect_error(.checkargs(format = 2))
})
test_that('categorical argument checking works',{
expect_error(.checkargs(categorical = 1))
})
test_that('Norm argument checking works',{
expect_error(.checkargs(Norm = 'TRUE'))
})
test_that('enm argument checking works',{
expect_error(.checkargs(enm = numeric()))
})
test_that('stack argument checking works',{
expect_error(.checkargs(stack = numeric()))
})
test_that('range argument checking works',{
expect_error(.checkargs(range = 'one-two'))
})
test_that('endemism argument checking works',{
expect_error(.checkargs(endemism = c(1,2)))
})
test_that('cores argument checking works',{
expect_error(.checkargs(cores = 'one'))
})
|
timestamp_new <- function() {
timestamp_class$new()
}
timestamp_class <- R6::R6Class(
classname = "tar_timestamp",
inherit = reporter_class,
class = FALSE,
portable = FALSE,
cloneable = FALSE,
public = list(
report_started = function(target, progress = NULL) {
cli_start(
target_get_name(target),
target_get_type_cli(target),
time_stamp = TRUE
)
},
report_built = function(target, progress) {
cli_built(
target_get_name(target),
target_get_type_cli(target),
time_stamp = TRUE
)
},
report_skipped = function(target, progress) {
cli_skip(
target_get_name(target),
target_get_type_cli(target),
time_stamp = TRUE
)
},
report_errored = function(target, progress = NULL) {
cli_error(
target_get_name(target),
target_get_type_cli(target),
time_stamp = TRUE
)
},
report_canceled = function(target = NULL, progress = NULL) {
cli_cancel(
target_get_name(target),
target_get_type_cli(target),
time_stamp = TRUE
)
},
report_workspace = function(target) {
cli_workspace(target_get_name(target), time_stamp = TRUE)
},
report_end = function(progress = NULL) {
progress$cli_end(time_stamp = TRUE)
super$report_end(progress)
}
)
)
|
as.data.frame.function <- function(x, row.names, optional, ...) {
function(...) data.frame(value = x(...))
}
|
context("nltt_plot")
test_that("use", {
testthat::expect_silent(nltt_plot(ape::rcoal(10)))
testthat::expect_silent(nltt_lines(ape::rcoal(10)))
})
test_that("abuse", {
testthat::expect_error(
nltt_plot("not a phylogeny"),
"phylogeny must be of class 'phylo'"
)
testthat::expect_error(
nltt_lines("not a phylogeny"),
"phylogeny must be of class 'phylo'"
)
})
|
scanPhyloQTL <-
function(crosses, partitions, chr, pheno.col=1,
model=c("normal","binary"), method=c("em","imp","hk"),
addcovar, maxit=4000, tol=0.0001, useAllCrosses=TRUE,
verbose=FALSE)
{
if(missing(chr)) chr <- names(crosses[[1]]$geno)
model <- match.arg(model)
method <- match.arg(method)
thecrosses <- names(crosses)
taxa <- sort(unique(unlist(strsplit(thecrosses, ""))))
thecrosses <- names(crosses) <- checkPhyloCrosses(thecrosses, taxa)
if(missing(partitions)) {
partitions <- genAllPartitions(length(taxa), taxa)
}
checkPhyloPartition(partitions, taxa)
crossmat <- qtlByPartition(thecrosses, partitions)
dimnames(crossmat) <- list(thecrosses, partitions)
if(!missing(addcovar)) {
if(!is.list(addcovar) || length(addcovar) != length(crosses))
stop("addcovar must be a list with the same length as crosses (", length(crosses), ")")
n.ind <- sapply(crosses, nind)
if(is.matrix(addcovar[[1]])) {
nind.addcovar <- sapply(addcovar, nrow)
n.addcovar <- sapply(addcovar, ncol)
}
else {
nind.addcovar <- sapply(addcovar, length)
n.addcovar <- 1
}
if(any(nind.addcovar != n.ind)) {
err <- paste("crosses: ", paste(n.ind, collapse=" "), "\n",
"addcovar:", paste(n.addcovar, collapse=" "), "\n")
stop("Mismatch between no. individuals in addcovar and crosses.\n", err)
}
if(length(unique(n.addcovar)) > 1)
stop("Mismatch in no. add've covariates: ", paste(n.addcovar, collapse=" "))
}
n.chr <- sapply(crosses, nchr)
if(!all(n.chr == n.chr[1]))
stop("Different numbers of chromosomes")
chrnam1 <- chrnames(crosses[[1]])
for(j in 2:length(crosses)) {
chrnam2 <- chrnames(crosses[[j]])
if(!all(chrnam1 == chrnam2))
stop("Different chromosome names")
}
n.mar1 <- nmar(crosses[[1]])
for(j in 2:length(crosses)) {
n.mar2 <- nmar(crosses[[j]])
if(!all(n.mar1 == n.mar2))
stop("Different numbers of markers")
}
mn1 <- markernames(crosses[[1]])
for(j in 2:length(crosses)) {
mn2 <- markernames(crosses[[j]])
if(!all(mn1 == mn2))
stop("Different marker names")
}
mp1 <- unlist(pull.map(crosses[[1]]))
for(j in 2:length(crosses)) {
mp2 <- unlist(pull.map(crosses[[j]]))
if(!all(mp1 == mp2))
stop("Different marker positions")
}
out <- vector("list", length(partitions))
for(i in seq(along=partitions)) {
if(verbose) cat("Partition", i, "of", length(partitions), "\n")
cm <- crossmat[,i]
if(!any(cm > 0)) cm <- -cm
if(!useAllCrosses) {
whcm <- which(cm != 0)
x <- crosses[whcm]
cm <- cm[whcm]
}
else {
o <- order(abs(cm), decreasing=TRUE)
cm <- cm[o]
whcm <- seq(along=cm)
x <- crosses[o]
if(!missing(addcovar))
addcovar <- addcovar[o]
}
if(any(cm < 0))
for(j in which(cm < 0))
x[[j]] <- flipcross(x[[j]])
xx <- x[[1]]
n.phe <- nphe(x[[1]])
if(length(x) > 1) {
for(j in 2:length(x)) {
xx <- c(xx, x[[j]])
xx$pheno <- xx$pheno[,1:n.phe,drop=FALSE]
}
}
if(length(x)==1) alladdcovar<-NULL
else {
ni <- sapply(x, nind)
alladdcovar <- matrix(0, ncol=length(x)-1, nrow=sum(ni))
thestart <- cumsum(c(1,ni))
end <- cumsum(ni)
for(j in 2:length(x))
alladdcovar[thestart[j]:end[j],j-1] <- 1
}
if(!missing(addcovar)) {
theaddcovar <- as.matrix(addcovar[[whcm[1]]])
if(length(whcm) > 1)
for(j in 2:length(whcm))
theaddcovar <- rbind(theaddcovar, as.matrix(addcovar[[whcm[j]]]))
if(ncol(theaddcovar)>1 || length(unique(theaddcovar))>1)
alladdcovar <- cbind(alladdcovar, theaddcovar)
}
ind.noqtl <- rep(cm == 0, sapply(x, nind))
out[[i]] <- scanone(xx, chr=chr, pheno.col=pheno.col, addcovar=alladdcovar,
model=model, method=method, maxit=maxit, tol=tol,
ind.noqtl=ind.noqtl)
}
if(length(out) == 1) return(out[[1]])
result <- out[[1]]
for(j in 2:length(out))
result <- c(result, out[[j]])
colnames(result)[-(1:2)] <- partitions
class(result) <- c("scanPhyloQTL", "scanone", "data.frame")
result
}
max.scanPhyloQTL <-
function(object, chr, format=c("postprob", "lod"), ...)
{
format <- match.arg(format)
if(!missing(chr))
object <- subset.scanone(object, chr=chr)
mx <- summary.scanPhyloQTL(object, format=format)
if(nrow(mx) > 1) {
nc <- ncol(mx)
mx <- mx[!is.na(mx[,nc]) & mx[,nc]==max(mx[,nc], na.rm=TRUE),,drop=FALSE]
}
class(mx) <- c("summary.scanPhyloQTL", "summary.scanone", "data.frame")
mx
}
summary.scanPhyloQTL <-
function(object, format=c("postprob", "lod"), threshold, ...)
{
format <- match.arg(format)
themax <- apply(object[,-(1:2)], 2, tapply, object[,1], max, na.rm=TRUE)
if(length(unique(object[,1]))==1) {
themax <- as.data.frame(matrix(themax, nrow=1), stringsAsFactors=TRUE)
names(themax) <- colnames(object)[-(1:2)]
}
wh <- apply(themax, 1, function(a) { a <- which(a==max(a)); if(length(a) > 1) a <- sample(a, 1); a })
whpos <- rep(NA, length(wh))
names(whpos) <- unique(object[,1])
for(i in seq(along=whpos)) {
temp <- object[object[,1]==names(whpos)[i],,drop=FALSE]
temp2 <- which(temp[,wh[i]+2]==max(temp[,wh[i]+2],na.rm=TRUE))
if(length(temp2) > 1) temp2 <- sample(temp2, 1)
whpos[i] <- temp[temp2,2]
names(whpos)[i] <- rownames(temp)[temp2]
}
if(format=="lod") {
out <- data.frame(chr=unique(object[,1]), pos=whpos, themax,
loddif=apply(themax, 1, function(a) -diff(sort(a, decreasing=TRUE)[1:2])),
inferred=colnames(object)[wh+2],
maxlod=apply(themax, 1, max),
stringsAsFactors=TRUE)
}
else {
out <- data.frame(chr=unique(object[,1]), pos=whpos, themax,
inferred=colnames(object)[wh+2],
maxlod=apply(themax, 1, max),
stringsAsFactors=TRUE)
temp <- out[,-c(1:2, ncol(out)-0:1)]
out[,-c(1:2, ncol(out)-0:1)] <- t(apply(temp, 1, function(a) 10^a/sum(10^a)))
}
colnames(out)[(1:ncol(themax))+2] <- colnames(themax)
rownames(out) <- names(whpos)
if(!missing(threshold))
out <- out[out$maxlod >= threshold,,drop=FALSE]
class(out) <- c("summary.scanPhyloQTL", "summary.scanone", "data.frame")
out
}
plot.scanPhyloQTL <-
function(x, chr, incl.markers=TRUE, col, xlim, ylim, lwd=2,
gap=25, mtick=c("line", "triangle"),
show.marker.names=FALSE, alternate.chrid=FALSE,
legend=TRUE, ...)
{
mtick <- match.arg(mtick)
if(!missing(chr)) x <- subset(x, chr=chr)
if(missing(col)) {
col <- c("black","blue","red","green","orange","brown","gray","cyan","magenta")
if(ncol(x)-2 > length(col))
stop("Please give a list of colors")
col <- col[1:(ncol(x)-2)]
}
if(missing(ylim))
ylim <- c(0, max(apply(x[,-(1:2)], 2, max)))
dots <- list(...)
if(missing(xlim)) {
if("ylab" %in% names(dots))
plot.scanone(x, incl.markers=incl.markers, col=col[1], lodcolumn=1,
ylim=ylim, lwd=lwd, gap=gap, mtick=mtick,
show.marker.names=show.marker.names, alternate.chrid=alternate.chrid, ...)
else
plot.scanone(x, incl.markers=incl.markers, col=col[1], lodcolumn=1,
ylim=ylim, lwd=lwd, gap=gap, mtick=mtick,
show.marker.names=show.marker.names, alternate.chrid=alternate.chrid,
ylab="LOD score", ...)
}
else {
if("ylab" %in% names(dots))
plot.scanone(x, incl.markers=incl.markers, col=col[1], lodcolumn=1,
ylim=ylim, xlim=xlim, lwd=lwd, gap=gap, mtick=mtick,
show.marker.names=show.marker.names, alternate.chrid=alternate.chrid, ...)
else
plot.scanone(x, incl.markers=incl.markers, col=col[1], lodcolumn=1,
ylim=ylim, xlim=xlim, lwd=lwd, gap=gap, mtick=mtick,
show.marker.names=show.marker.names, alternate.chrid=alternate.chrid,
ylab="LOD score", ...)
}
if(ncol(x) > 3)
for(i in 2:(ncol(x)-2))
plot.scanone(x, col=col[i], lodcolumn=i, add=TRUE, ...)
if(is.character(legend) || legend) {
if(is.character(legend))
legend(legend, legend=colnames(x)[-(1:2)], col=col, lwd=lwd)
else
legend("topright", legend=colnames(x)[-(1:2)], col=col, lwd=lwd)
}
invisible()
}
inferredpartitions <-
function(output, chr, lodthreshold, probthreshold=0.9)
{
if(!inherits(output, "scanPhyloQTL"))
stop("Argument 'output' must be of class \"scanPhyloQTL\", as output by scanPhyloQTL.")
if(missing(chr)) {
chr <- output[1,1]
warning("Missing chromosome; using ", chr)
}
else if(!any(output[,1]==chr))
stop("Chromosome \"", chr, "\" not found.")
if(missing(lodthreshold)) {
warning("No lodthreshold given; using lodthreshold=0.")
lodthreshold=0
}
if(probthreshold >= 1 || probthreshold <= 0) {
stop("probthreshold should be in (0,1)")
}
output <- output[output[,1]==chr,]
output[,1] <- as.factor(as.character(output[,1]))
output <- summary(output, format="postprob")
if(output$maxlod < lodthreshold) return("null")
prob <- sort(unlist(output[,3:(ncol(output)-2)]), decreasing=TRUE)
cs <- cumsum(as.numeric(prob))
if(!any(cs >= probthreshold)) {
warning("No values >= probthreshold")
return(NULL)
}
wh <- min(which(cs >= probthreshold))
names(prob)[seq_len(wh)]
}
|
"_PACKAGE"
if (getRversion() >= "2.15.1")
utils::globalVariables(c("abbr", "county", "group", "x", "y"))
us_map <- function(regions = c("states", "state", "counties", "county"),
include = c(),
exclude = c()) {
regions_ <- match.arg(regions)
if (regions_ == "state") regions_ <- "states"
else if (regions_ == "county") regions_ <- "counties"
df <- utils::read.csv(system.file("extdata", paste0("us_", regions_, ".csv"), package = "usmap"),
colClasses = col_classes(regions_),
stringsAsFactors = FALSE)
if (length(include) > 0) {
df <- df[df$full %in% include |
df$abbr %in% include |
df$fips %in% include |
substr(df$fips, 1, 2) %in% include, ]
}
if (length(exclude) > 0) {
df <- df[!(df$full %in% exclude |
df$abbr %in% exclude |
df$fips %in% exclude |
substr(df$fips, 1, 2) %in% exclude), ]
}
df
}
col_classes <- function(regions) {
result <- c("numeric", "numeric", "integer", "logical", "integer", rep("character", 4))
if (regions %in% c("county", "counties")) {
result <- c(result, "character")
}
result
}
|
colhalfnorm.mle <- function(x) {
n <- dim(x)[1]
s <- sqrt( Rfast::colsums(x^2)/n )
loglik <- n/2 * log( 2 / pi / s) - n/2
res <- cbind(s, loglik)
colnames(res) <- c("sigma.squared", "loglik")
res
}
colordinal.mle <- function (x, link = "logit") {
ina <- Rfast::colTabulate(x)
d <- dim(ina)[2]
for (i in 1:d) ina[, i] <- as.numeric(ina[, i])
k <- dim(ina)[1] - Rfast::colCountValues(ina, rep(0, d) )
ni <- Rfast::colCumSums(ina)/dim(x)[1]
if (link == "logit") {
param <- log(ni/(1 - ni))
} else param <- qnorm(ni)
ep <- which( is.infinite(param) )
param[ep] <- NA
loglik <- Rfast::rowsums( t(ina) * log( cbind( ni[1, ], Rfast::coldiffs( t(ni)) ) ), na.rm = TRUE )
list(param = param, loglik = loglik)
}
collognorm.mle <- function(x) {
n <- dim(x)[1]
x <- Rfast::Log(x)
sx <- Rfast::colsums(x)
m <- sx/n
s <- Rfast::colsums(x^2)/n - m^2
loglik <- -0.5 * n * (log(2 * pi * s) + 1) - sx
res <- cbind(m, s, loglik)
colnames(res) <- c("mean", "variance", "loglik")
res
}
collogitnorm.mle <- function(x) {
n <- dim(x)[1]
lx1 <- Rfast::Log(x)
lx2 <- Rfast::Log(1 - x)
y <- lx1 - lx2
sy <- Rfast::colsums(y)
m <- sy/n
s <- ( Rfast::colsums(y^2) - n * m^2 ) / n
loglik <- Rfast::rowsums( dnorm(t(y), m, sqrt(s), log = TRUE) ) - Rfast::colsums(lx1) - Rfast::colsums(lx2)
res <- cbind(m, n * s/(n - 1), loglik)
colnames(res) <- c("mean", "unbiased variance", "loglik")
res
}
colborel.mle <- function(x) {
n <- dim(x)[1]
sx <- Rfast::colsums(x)
m <- 1 - n/sx
loglik <- -sx + n + Rfast::colsums( (x - 1) * log( t( t(x) * m ) ) ) -
Rfast::colsums( Rfast::Lgamma(x + 1) )
res <- cbind(m, loglik)
colnames(res) <- c("m", "loglik")
res
}
colspml.mle <- function(x, tol = 1e-07, maxiters = 100, parallel = FALSE) {
res <- .Call( Rfast2_colspml_mle,x, tol, maxiters, parallel)
colnames(res) <- c("mu1", "mu2", "gamma", "loglik")
res
}
colcauchy.mle <- function (x, tol = 1e-07, maxiters = 100, parallel = FALSE) {
res <- .Call(Rfast2_colcauchy_mle, x, tol, parallel, maxiters)
colnames(res) <- c("location", "scale", "loglik")
res
}
colbeta.mle <- function(x, tol = 1e-07, maxiters = 100, parallel = FALSE) {
res <- .Call(Rfast2_colbeta_mle, x, tol, parallel, maxiters)
colnames(res) <- c("alpha", "beta", "loglik")
res
}
colunitweibull.mle <- function(x, tol = 1e-07, maxiters = 100, parallel = FALSE) {
lx <- - log(x)
mod <- Rfast::colweibull.mle( lx, tol = tol, maxiters = maxiters, parallel = parallel )
param <- mod[, 1:2]
colnames(param) <- c("alpha", "beta")
a <- param[, 1] ; b <- param[, 2]
n <- dim(x)[1]
loglik <- Rfast::colsums(lx) + n * log(a * b) + (b - 1) * Rfast::colsums( log(lx) ) - a * Rfast::rowsums( t(lx)^b )
param <- cbind(param, loglik)
param
}
|
library(hamcrest)
expected <- c(-0x1.064434e52cd78p+10 + 0x0p+0i, 0x1.8d0136158ab2p+4 + -0x1.59d55390dd1bfp+8i,
0x1.7451f918f3bc5p+6 + 0x1.930a2422786dcp+6i, -0x1.398ec3b749565p+6 + 0x1.28bdbd79c138ep+8i,
-0x1.74748e6bf28d5p+7 + -0x1.e90c9ffbdc9f4p+3i, -0x1.05e161facd218p+7 + -0x1.b02a8f0ab7f7cp+7i,
0x1.e02be52ec9c62p+6 + 0x1.0159245633f06p+7i, -0x1.6f72f73630853p+6 + 0x1.9663ff776ba1ap+6i,
-0x1.ccef2d256bb8ap+8 + -0x1.f8f38522353d4p+7i, 0x1.3c675ee1efb85p+5 + 0x1.df9c557b3be2ep+5i,
-0x1.c96d0fc5de40cp+5 + -0x1.c47fdf597c086p+6i, 0x1.5eeb89627b7e8p+7 + 0x1.200b0dbacb7fep+7i,
-0x1.013c76e2bbad2p+8 + 0x1.6d07c80aa2e2dp+7i, -0x1.423302a82d54p+0 + -0x1.4c13db02c48dbp+5i,
-0x1.b28691b96eb6p+4 + 0x1.97b773159a7b2p+6i, -0x1.616599568f352p+4 + 0x1.da9775c12f2f3p+4i,
-0x1.123210d139548p+3 + 0x1.e969db35deb4p+4i, 0x1.42f440d275d12p+4 + 0x1.7bd00686fe8e8p+4i,
-0x1.ba435666f0a7cp+4 + -0x1.e5ddf70e55b64p+2i, -0x1.5a9b0a8b7693ap+6 + 0x1.13b21635a4d99p+8i,
0x1.de70abc025248p+5 + 0x1.15b208535441cp+6i, -0x1.93f5dd3515378p+6 + 0x1.1265b2476f6c4p+6i,
0x1.924133eeec99cp+2 + 0x1.4336410a761cdp+5i, -0x1.2d76deb892e59p+7 + 0x1.e547f3aa4ead6p+6i,
0x1.089045da1b629p+7 + -0x1.895ea0a49ace5p+6i, 0x1.f5ed4b47fcfccp+6 + 0x1.60b1ad9de0196p+6i,
-0x1.3987ad68d127ap+3 + 0x1.36783a135ddd1p+7i, -0x1.a41a885cdb864p+6 + 0x1.de5ace05a8e22p+5i,
0x1.0423d958ae69p+8 + 0x1.af537fcdf37ddp+5i, 0x1.7a623d8f4016ep+6 + 0x1.31070076fb719p+5i,
-0x1.31bbee051719p+5 + -0x1.15cde40838a3ep+6i, -0x1.2e70269ad529p+3 + -0x1.81660475818aep+4i,
0x1.50c55ac480a94p+6 + 0x1.5e5c2860cfd8p+1i, 0x1.592a4897081cap+6 + 0x1.1233c5b2ec7e1p+5i,
-0x1.ba655187caae7p+5 + -0x1.90e0f55b504e4p+6i, 0x1.e5a5f085ed289p+6 + 0x1.a2fc85bd835d2p+5i,
0x1.0bdc309c1aa71p+6 + 0x1.1060c90714068p+4i, -0x1.81f2c632f9cdbp+2 + -0x1.a9e119e9f9524p+4i,
0x1.8839113f237ccp+2 + 0x1.046a03385d0cp-2i, -0x1.2e5b5add0e06p+2 + -0x1.7e7ed60d12822p+5i,
0x1.de5c4271f0a64p+5 + 0x1.6ac965f50f058p+7i, -0x1.10a4199d8f8ecp+5 + 0x1.386523d8cbc8p+1i,
-0x1.6ca13047f6b57p+6 + 0x1.092d2fda7d2dap+4i, 0x1.3f29ac48a2ba1p+6 + 0x1.17094eea3cd3p+6i,
0x1.767b013eb0149p+6 + 0x1.63c2d02224427p+4i, -0x1.5db6afbbb7948p+3 + 0x1.3df089c19f863p+6i,
-0x1.f64d574245d18p+5 + -0x1.002e583559dddp+4i, 0x1.829a2e28f604p-1 + 0x1.6058a66a7dcd4p+3i,
-0x1.89af0a205384ap+3 + -0x1.0d93ba6311ebbp+5i, 0x1.35ffd99ded70fp+6 + 0x1.9ca05d2536552p+6i,
-0x1.1caf93a6e61d4p+4 + 0x1.0b92e046b2f6p+1i, 0x1.f184baeb60514p+2 + 0x1.50aa1677a0f9cp+5i,
-0x1.69d79fb351478p+2 + 0x1.0d330d5570782p+5i, 0x1.cd96550194383p+5 + 0x1.0af6c636ea484p+4i,
-0x1.83712c81d551p+4 + -0x1.33bda65529fd8p+6i, -0x1.7abe36a4650aap+4 + 0x1.7ac696837b4acp+5i,
-0x1.7f5bffbb42e0ep+4 + 0x1.0f324e1cc30f4p+4i, -0x1.32ccb69219de8p+4 + -0x1.d79036f340ap+1i,
-0x1.138c96bf7dbdp+4 + -0x1.12a7c7e5fa904p+4i, -0x1.08b45f83a91d4p+5 + -0x1.48427893cc484p+5i,
-0x1.25b25cf157cffp+7 + 0x1.10965f2a6b85cp+5i, -0x1.214760b1c47dap+4 + -0x1.57e9f045c4822p+6i,
0x1.0e691af8132ep+3 + 0x1.4e848ea7279e4p+3i, 0x1.3c86adc2f40ep+1 + 0x1.0e22a83a65ffep+5i,
-0x1.06970be16f2a9p+7 + 0x1.32289d842f75p+1i, -0x1.8c0f45cce8d04p+4 + 0x1.c4cd21458656cp+4i,
-0x1.5ae8e31231cp+3 + 0x1.00438ac8e864cp+6i, -0x1.a5ea11f21ac4dp+5 + 0x1.0e3bc7e5bdb6dp+6i,
0x1.ac9b3d135d68p-1 + 0x1.b6c357032b00fp+5i, -0x1.93c6b39348832p+6 + -0x1.ca1c317965198p+1i,
-0x1.3caf039983d9p+1 + 0x1.865db26b3fc51p+6i, -0x1.296792c1c2916p+5 + -0x1.2f988bfd38b7ap+3i,
0x1.f9fe118f97819p+4 + 0x1.7c0905d297d6ep+6i, -0x1.f7547f2aa362p+5 + 0x1.bce0ccf5dba84p+3i,
-0x1.65d1ecaf68174p+5 + -0x1.e7d9383b6802p+0i, -0x1.cb7349b389c64p+4 + -0x1.5b9a13e46b1c8p+3i,
-0x1.02f31298a85cap+4 + 0x1.1695f9eb72854p+6i, -0x1.31bd8d0cce7e3p+5 + 0x1.c1de747cc1e26p+4i,
-0x1.1c7487b0f6ff5p+4 + 0x1.5952e4708598ep+5i, -0x1.32cf16ebd0ap+4 + -0x1.a17d0b36a63fap+4i,
-0x1.e8a04eb18039p+3 + -0x1.7440411854b94p+2i, -0x1.4350b6ef3594p+4 + -0x1.051d9a7e2afbp+2i,
-0x1.cc803de874976p+4 + 0x1.4ce986a53d602p+3i, -0x1.1a108e238574cp+4 + -0x1.00e59f2015be8p+6i,
-0x1.5ce9b16713598p+3 + 0x1.6dd038daaef19p+5i, -0x1.17b67d4b8d9aep+5 + 0x1.3f97f12f56c17p+5i,
-0x1.644ae14db62b1p+5 + 0x1.5f7ca698db957p+5i, -0x1.ed54aeca7744dp+4 + -0x1.0de1f475334f8p+3i,
0x1.b7b69a3a1faccp+5 + -0x1.8b2c69e89b674p+3i, -0x1.66862bc9c41b4p+2 + 0x1.78183ccc9791p+3i,
-0x1.416bde296d173p+5 + 0x1.6bd26d6879a38p+1i, 0x1.6cb0aa5f0a8cfp+5 + -0x1.8363bc4bd811bp+3i,
0x1.885f8aa7973e8p+5 + -0x1.ed0cb00681eacp+3i, 0x1.fff03c1ba9d4p+3 + 0x1.059616f7daa8fp+6i,
-0x1.d077528e3f062p+6 + 0x1.82400cc6310c1p+5i, -0x1.2a9c12a99c7b6p+5 + 0x1.64019311e16ap+0i,
0x1.e76a484fa1ap+1 + -0x1.9d4acd2f58ce8p+5i, -0x1.daee9a65ace5p+5 + 0x1.86cae79eb243p+4i,
-0x1.2c342532852e5p+6 + -0x1.bc732cbd7cc6ap+5i, -0x1.4049b465ab548p+5 + -0x1.43ab0900e290cp+3i,
-0x1.1b5ab510be79ep+5 + 0x1.54461a3830f6cp+3i, -0x1.41d4d1d89be12p+5 + 0x1.9a6d1bfb219cp+3i,
-0x1.9046dfbb92d88p+5 + 0x1.42a9909cc2622p+5i, -0x1.286538b6cf49ep+5 + 0x1.40a01fac7afcap+4i,
-0x1.2ed399010cd73p+6 + -0x1.3d4993ed2953dp+2i, -0x1.2e0ab41d921cp+2 + 0x1.13738e6f11cep+1i,
-0x1.6561a269e1487p+5 + 0x1.a8a02c6d7922cp+4i, -0x1.51d2c4c2a6c4p+6 + -0x1.693325812a0b6p+4i,
-0x1.ff04eafaa3264p+4 + -0x1.2194cacc79b59p+4i, 0x1.4a70ac1d6443cp+5 + 0x1.27f89d7e5af7ap+3i,
-0x1.d9045afcf2373p+5 + 0x1.61899a5683c24p+5i, -0x1.6725d05d718c4p+5 + 0x1.a6e3532b19fb8p+1i,
-0x1.a74af98202813p+4 + -0x1.605c5b016daccp+4i, -0x1.f6f8f75113986p+4 + -0x1.7caf8d295693dp+4i,
0x1.1fb3b722eee64p+3 + 0x1.46330eb808aacp+6i, -0x1.246e8b78ad546p+6 + 0x1.0db371b907e3ap+5i,
-0x1.b9b030a2092edp+5 + -0x1.b383fd292481ep+2i, 0x1.f013398f7292ep+5 + -0x1.0e16680a4347dp+4i,
-0x1.c0ec23cb4cffdp+5 + 0x1.45b330ac047b5p+5i, 0x1.3bc81a4e88b28p+2 + 0x1.10fd8b18e5fd7p+5i,
-0x1.9b448cb74cd8ap+6 + -0x1.37fc38e42e966p+3i, 0x1.24b761aacc5bp+4 + -0x1.67bd277ed5ed6p+5i,
-0x1.af00d9d383ccep+5 + 0x1.8be0ab9ca13a3p+4i, -0x1.03323f9534c53p+6 + -0x1.32e249bf4b438p+6i,
-0x1.02a1d384e3ecbp+7 + 0x1.64a5955760326p+2i, -0x1.de513b6680361p+4 + -0x1.1bf962b93618dp+2i,
-0x1.14dbf754ce9b5p+4 + -0x1.40cc98bcad5b7p+5i, -0x1.3cdc0d1430368p+5 + 0x1.7f68afae0fc84p+5i,
-0x1.5ab9b02469dabp+5 + 0x1.01914e07d1b48p+7i, 0x1.6d1a19cfc8f88p+3 + -0x1.7cda4cbad8a9dp+5i,
0x1.47f02d9639bccp+5 + -0x1.97a46d83c9fcbp+6i, 0x1.654bffd590884p+3 + 0x1.120974c6ad39ap+4i,
-0x1.652acfc0015dp+7 + 0x1.7dfc85ad913b4p+5i, -0x1.4bd8a374a9823p+3 + -0x1.734a32aa9351cp+6i,
0x1.7e46d97809dd1p+5 + 0x1.88d386bab3b05p+4i, 0x1.16e7ae676ea86p+5 + 0x1.69a552d0759a8p+4i,
-0x1.a0b2b9a07d80ep+5 + 0x1.4fff1af614902p+6i, 0x1.04b7bcefc07b6p+6 + -0x1.b6271d00df2b9p+3i,
0x1.31221e6771d6p+6 + 0x1.3eec0445b1c9ep+4i, -0x1.4effe86c82a44p+5 + -0x1.172fcc8421dcp+6i,
-0x1.39c3e496f0e5dp+6 + -0x1.c5c7ec04b12cdp+5i, 0x1.5101bdbf540ap+2 + -0x1.cdc9aa4bfb679p+3i,
-0x1.0435bb2d2a04cp+3 + 0x1.fece182f023ffp+3i, -0x1.919eeb8d1be88p+5 + -0x1.43165a895f957p+4i,
-0x1.09c04a4898201p+7 + 0x1.e68b8e96371fp+1i, 0x1.77c30914663f4p+3 + -0x1.00dbda33a402cp+6i,
0x1.3bebfc7776d1ep+5 + 0x1.e8f308684273p+4i, 0x1.0ffcc098427e2p+5 + -0x1.7bf3ce6d35779p+5i,
-0x1.e9b73852c3d36p+5 + 0x1.c21d8d63c93cfp+2i, -0x1.7c9ee2c1494a6p+6 + -0x1.143c26daf9f4p+1i,
-0x1.6cf24a8c62a96p+5 + -0x1.92d15d9a3b12cp+6i, -0x1.ee3bb03094779p+4 + -0x1.02746f073d268p+6i,
-0x1.4eb9b6218483cp+6 + 0x1.0f9f2c6c4c467p+6i, -0x1.ddf75b9dc5e92p+5 + -0x1.63a1690e2766cp+6i,
-0x1.c9f8466f6e3f4p+6 + -0x1.21751610b88d2p+6i, 0x1.5c28aecf9aea2p+6 + 0x1.b3a060aa8101ap+5i,
-0x1.8052c3b658c96p+5 + -0x1.43a6727d3a35dp+6i, -0x1.46682ee7feeap+7 + -0x1.a5145529073ebp+4i,
-0x1.e3c97eee530c2p+5 + -0x1.3c2f7cf358fbfp+7i, -0x1.2b41bdd70fc32p+6 + 0x1.fb02fe00a1ddap+5i,
-0x1.0716d6dc170a4p+7 + -0x1.8cac3594423f4p+6i, 0x1.c547855675c4bp+6 + -0x1.9306e3acf9accp+6i,
-0x1.296d154b5978fp+8 + -0x1.97052eabcc44cp+6i, 0x1.25394b9f72eb4p+7 + -0x1.bc5d8960fe63cp+7i,
0x1.1d65b93aa4a96p+6 + -0x1.8281846bf18a8p+6i, -0x1.427e70a0a0ab1p+3 + 0x1.ff67a7c30c064p+6i,
-0x1.5ea78472be434p+8 + 0x1.2c80492d642a6p+6i, 0x1.49071b07270bcp+5 + -0x1.a973be44f6992p+7i,
0x1.835cd116c470ep+7 + 0x1.b26d2dc1331p+5i, -0x1.f052650cd0d9dp+7 + 0x1.f7e683d41c5e1p+6i,
-0x1.50dd99e57046bp+8 + -0x1.edde5eb520c28p+7i, 0x1.e7c1e6be3edf4p+7 + -0x1.4a2ab3246387ep+7i,
0x1.eec61e1b59b7ap+5 + 0x1.f60d54bdc04ap+3i, 0x1.674ead79c8763p+4 + 0x1.7612fa9f728d8p+7i,
-0x1.39553b99faffep+8 + 0x1.a2c0003936dd6p+5i, -0x1.fcfd11771039p+1 + -0x1.0409ec0f9bc0dp+7i,
0x1.076531694668bp+4 + 0x1.d3e9241beabe4p+7i, 0x1.d73d851af933p+0 + -0x1.5159b1a751577p+6i,
-0x1.016820c2aeffep+8 + -0x1.735b00a57c81dp+6i, 0x1.ac2ebbdfb36abp+6 + 0x1.02bb00608ebb2p+5i,
0x1.1a489ae7ca6a6p+6 + -0x1.bfbd431970ceep+5i, 0x1.938921a65faf4p+5 + 0x1.9b76d2f2b269p+6i,
-0x1.9cdf53f55bad7p+7 + 0x1.052951816467p+6i, 0x1.b3df904fc0bf6p+5 + 0x1.84193f92deb32p+5i,
-0x1.43e795b87cddcp+7 + -0x1.3f2924b5e3cccp+3i, 0x1.18921d0639944p+7 + -0x1.8ee8589f83f64p+3i,
-0x1.2e362b7e02fa4p+7 + -0x1.4aa344f6999bep+2i, 0x1.199cfefaf6cbap+4 + 0x1.45ea961d28812p+5i,
0x1.16320d00df576p+4 + 0x1.02966c37d5d44p+5i, 0x1.15eacbdf2e7a7p+5 + -0x1.450c47cd7063cp+5i,
0x1.3a13028be1694p+5 + 0x1.f01da5a0e984p+4i, 0x1.499b7d0303b34p+0 + 0x1.b33ca2dea14b1p+5i,
0x1.5463eb13d34f4p+5 + 0x1.141054c8c6027p+7i, -0x1.9214c17a74abcp+6 + 0x1.78064a3d2d8cp+0i,
0x1.3137f823c7a4ap+7 + 0x1.8c2b27ac5a0e3p+5i, -0x1.52c9e3f098e5p+2 + 0x1.6df241b4a5176p+2i,
-0x1.64c5ef079924ep+6 + 0x1.ba4c472ac36d5p+6i, 0x1.324d542b6c3c4p+2 + -0x1.86fc45b2eb338p+5i,
0x1.def661ce3ddccp+5 + -0x1.ae56327ff029cp+3i, -0x1.4c06d107b5284p+4 + 0x1.26f97d09927abp+6i,
0x1.b4c66b465578p+0 + 0x1.44b88f4e8dc06p+7i, -0x1.448062f580096p+7 + -0x1.baab633a261cbp+5i,
0x1.95088877888d9p+5 + 0x1.491faf2b00ecdp+7i, -0x1.6df2728c33b52p+4 + 0x1.1cf9151948155p+6i,
0x1.b0be9c6461e68p+5 + -0x1.7ccaa09b17102p+4i, -0x1.4ce6bee121c26p+6 + -0x1.51e8b4570895dp+6i,
0x1.e5c75ed1a6576p+5 + 0x1.748cc4eda5504p+2i, -0x1.e6aea577916dap+5 + 0x1.1928b1243eb49p+4i,
-0x1.ad4dd338cf87p+0 + 0x1.9695bbd6423bap+6i, 0x1.d8df47e199cep+0 + -0x1.c6d250f2f0678p+4i,
0x1.7ace9cd175728p+5 + 0x1.0d22cc8e8df01p+5i, -0x1.de7e0ebc5242ap+2 + -0x1.90ccf22f721c6p+3i,
0x1.366a4d9e6dad1p+6 + 0x1.6b7a34488dbe2p+6i, 0x1.d9222a4825facp+2 + -0x1.17fb918e7845bp+5i,
0x1.17284d14951d3p+6 + -0x1.05f6d9af1ba1p+5i, -0x1.8079d90ab868ep+6 + 0x1.6ff0be669414cp+4i,
0x1.bd6ecd9632248p+6 + 0x1.8dcaf655c8a34p+6i, 0x1.07e2cdeea9e6p+5 + -0x1.3e8b0e9698178p+5i,
0x1.5ec02380984b8p+4 + -0x1.7351abe74f608p+2i, -0x1.1f500d86562ebp+6 + 0x1.3dab535ac8258p+5i,
0x1.e4c1af93299f8p+6 + -0x1.49b608ac374cp+2i, -0x1.4e2a9098a3624p+5 + 0x1.ef69409a73092p+4i,
-0x1.0957e250bf176p+6 + -0x1.5c1431555116p+3i, -0x1.7bfac6316627ap+5 + -0x1.6712a5c7c0ab7p+6i,
-0x1.b438628640a88p+4 + -0x1.15733ce6e81eap+4i, -0x1.0cf3bac949832p+7 + -0x1.80355eb70fadp+3i,
-0x1.0af8b6fcac736p+7 + 0x1.ccbae4298f15ap+5i, -0x1.9c688fde593c4p+5 + -0x1.5c558516080ap+4i,
-0x1.d9762caadf13p+5 + 0x0p+0i, -0x1.9c688fde593c8p+5 + 0x1.5c558516080ep+4i,
-0x1.0af8b6fcac73ep+7 + -0x1.ccbae4298f16p+5i, -0x1.0cf3bac949836p+7 + 0x1.80355eb70fa9p+3i,
-0x1.b438628640a68p+4 + 0x1.15733ce6e81eap+4i, -0x1.7bfac63166274p+5 + 0x1.6712a5c7c0ac8p+6i,
-0x1.0957e250bf17ep+6 + 0x1.5c14315551148p+3i, -0x1.4e2a9098a3622p+5 + -0x1.ef69409a730ap+4i,
0x1.e4c1af9329a12p+6 + 0x1.49b608ac375p+2i, -0x1.1f500d86562ecp+6 + -0x1.3dab535ac826p+5i,
0x1.5ec02380984c4p+4 + 0x1.7351abe74f638p+2i, 0x1.07e2cdeea9e56p+5 + 0x1.3e8b0e969817cp+5i,
0x1.bd6ecd9632252p+6 + -0x1.8dcaf655c8a3ep+6i, -0x1.8079d90ab869p+6 + -0x1.6ff0be669414ap+4i,
0x1.17284d14951d5p+6 + 0x1.05f6d9af1ba13p+5i, 0x1.d9222a4825f8p+2 + 0x1.17fb918e7845ap+5i,
0x1.366a4d9e6dad9p+6 + -0x1.6b7a34488dbe3p+6i, -0x1.de7e0ebc5243p+2 + 0x1.90ccf22f721b9p+3i,
0x1.7ace9cd17572ap+5 + -0x1.0d22cc8e8dfp+5i, 0x1.d8df47e199dep+0 + 0x1.c6d250f2f066cp+4i,
-0x1.ad4dd338cf8cp+0 + -0x1.9695bbd6423bep+6i, -0x1.e6aea577916dp+5 + -0x1.1928b1243eb5p+4i,
0x1.e5c75ed1a6572p+5 + -0x1.748cc4eda5518p+2i, -0x1.4ce6bee121c24p+6 + 0x1.51e8b45708958p+6i,
0x1.b0be9c6461e64p+5 + 0x1.7ccaa09b1711p+4i, -0x1.6df2728c33b56p+4 + -0x1.1cf9151948156p+6i,
0x1.95088877888d6p+5 + -0x1.491faf2b00ecfp+7i, -0x1.448062f580098p+7 + 0x1.baab633a261cap+5i,
0x1.b4c66b465578p+0 + -0x1.44b88f4e8dc07p+7i, -0x1.4c06d107b528ep+4 + -0x1.26f97d09927aap+6i,
0x1.def661ce3ddccp+5 + 0x1.ae56327ff0294p+3i, 0x1.324d542b6c3e3p+2 + 0x1.86fc45b2eb33bp+5i,
-0x1.64c5ef079925p+6 + -0x1.ba4c472ac36dcp+6i, -0x1.52c9e3f098e58p+2 + -0x1.6df241b4a5158p+2i,
0x1.3137f823c7a4dp+7 + -0x1.8c2b27ac5a0e1p+5i, -0x1.9214c17a74abbp+6 + -0x1.78064a3d2d8dp+0i,
0x1.5463eb13d34f2p+5 + -0x1.141054c8c6029p+7i, 0x1.499b7d0303c0cp+0 + -0x1.b33ca2dea14aap+5i,
0x1.3a13028be1698p+5 + -0x1.f01da5a0e983fp+4i, 0x1.15eacbdf2e799p+5 + 0x1.450c47cd70638p+5i,
0x1.16320d00df575p+4 + -0x1.02966c37d5d42p+5i, 0x1.199cfefaf6cbcp+4 + -0x1.45ea961d2880ap+5i,
-0x1.2e362b7e02fa4p+7 + 0x1.4aa344f6999d6p+2i, 0x1.18921d0639946p+7 + 0x1.8ee8589f83f7p+3i,
-0x1.43e795b87cddep+7 + 0x1.3f2924b5e3ca6p+3i, 0x1.b3df904fc0bfep+5 + -0x1.84193f92deb26p+5i,
-0x1.9cdf53f55badap+7 + -0x1.0529518164679p+6i, 0x1.938921a65fb01p+5 + -0x1.9b76d2f2b2698p+6i,
0x1.1a489ae7ca6a8p+6 + 0x1.bfbd431970cf1p+5i, 0x1.ac2ebbdfb36adp+6 + -0x1.02bb00608ebbcp+5i,
-0x1.016820c2aefffp+8 + 0x1.735b00a57c81ep+6i, 0x1.d73d851af91bp+0 + 0x1.5159b1a751578p+6i,
0x1.0765316946696p+4 + -0x1.d3e9241beabe2p+7i, -0x1.fcfd11771045p+1 + 0x1.0409ec0f9bc1p+7i,
-0x1.39553b99fafffp+8 + -0x1.a2c0003936de8p+5i, 0x1.674ead79c875ap+4 + -0x1.7612fa9f728dap+7i,
0x1.eec61e1b59b7dp+5 + -0x1.f60d54bdc04bp+3i, 0x1.e7c1e6be3edf7p+7 + 0x1.4a2ab3246387fp+7i,
-0x1.50dd99e57046dp+8 + 0x1.edde5eb520c28p+7i, -0x1.f052650cd0d9bp+7 + -0x1.f7e683d41c5e6p+6i,
0x1.835cd116c4711p+7 + -0x1.b26d2dc133108p+5i, 0x1.49071b07270c1p+5 + 0x1.a973be44f6993p+7i,
-0x1.5ea78472be435p+8 + -0x1.2c80492d642a4p+6i, -0x1.427e70a0a0af8p+3 + -0x1.ff67a7c30c067p+6i,
0x1.1d65b93aa4a99p+6 + 0x1.8281846bf18aep+6i, 0x1.25394b9f72eb2p+7 + 0x1.bc5d8960fe63ap+7i,
-0x1.296d154b5979p+8 + 0x1.97052eabcc446p+6i, 0x1.c547855675c56p+6 + 0x1.9306e3acf9ad3p+6i,
-0x1.0716d6dc170a6p+7 + 0x1.8cac3594423eep+6i, -0x1.2b41bdd70fc2ep+6 + -0x1.fb02fe00a1ddp+5i,
-0x1.e3c97eee530bfp+5 + 0x1.3c2f7cf358fcp+7i, -0x1.46682ee7fee9ep+7 + 0x1.a5145529073efp+4i,
-0x1.8052c3b658c98p+5 + 0x1.43a6727d3a35ep+6i, 0x1.5c28aecf9ae9cp+6 + -0x1.b3a060aa81023p+5i,
-0x1.c9f8466f6e3f2p+6 + 0x1.21751610b88ccp+6i, -0x1.ddf75b9dc5e96p+5 + 0x1.63a1690e2766ep+6i,
-0x1.4eb9b6218483cp+6 + -0x1.0f9f2c6c4c468p+6i, -0x1.ee3bb0309477ap+4 + 0x1.02746f073d266p+6i,
-0x1.6cf24a8c62a9ap+5 + 0x1.92d15d9a3b12dp+6i, -0x1.7c9ee2c1494a6p+6 + 0x1.143c26daf9f94p+1i,
-0x1.e9b73852c3d3p+5 + -0x1.c21d8d63c9444p+2i, 0x1.0ffcc098427d8p+5 + 0x1.7bf3ce6d3577ap+5i,
0x1.3bebfc7776d2fp+5 + -0x1.e8f3086842733p+4i, 0x1.77c3091466444p+3 + 0x1.00dbda33a402ep+6i,
-0x1.09c04a4898202p+7 + -0x1.e68b8e96371dp+1i, -0x1.919eeb8d1be88p+5 + 0x1.43165a895f952p+4i,
-0x1.0435bb2d2a04cp+3 + -0x1.fece182f0240dp+3i, 0x1.5101bdbf5406cp+2 + 0x1.cdc9aa4bfb67ep+3i,
-0x1.39c3e496f0e5ap+6 + 0x1.c5c7ec04b12dbp+5i, -0x1.4effe86c82a4ap+5 + 0x1.172fcc8421dbbp+6i,
0x1.31221e6771d5ep+6 + -0x1.3eec0445b1c9bp+4i, 0x1.04b7bcefc07bap+6 + 0x1.b6271d00df2dbp+3i,
-0x1.a0b2b9a07d804p+5 + -0x1.4fff1af614908p+6i, 0x1.16e7ae676ea7cp+5 + -0x1.69a552d07599fp+4i,
0x1.7e46d97809dep+5 + -0x1.88d386bab3b2ep+4i, -0x1.4bd8a374a97eep+3 + 0x1.734a32aa9351cp+6i,
-0x1.652acfc0015d1p+7 + -0x1.7dfc85ad913bp+5i, 0x1.654bffd59088p+3 + -0x1.120974c6ad3a4p+4i,
0x1.47f02d9639bcap+5 + 0x1.97a46d83c9fcbp+6i, 0x1.6d1a19cfc8f7bp+3 + 0x1.7cda4cbad8a9fp+5i,
-0x1.5ab9b02469da2p+5 + -0x1.01914e07d1b45p+7i, -0x1.3cdc0d143036p+5 + -0x1.7f68afae0fc8ap+5i,
-0x1.14dbf754ce9bp+4 + 0x1.40cc98bcad5bep+5i, -0x1.de513b668035cp+4 + 0x1.1bf962b936176p+2i,
-0x1.02a1d384e3ecap+7 + -0x1.64a5955760343p+2i, -0x1.03323f9534c59p+6 + 0x1.32e249bf4b437p+6i,
-0x1.af00d9d383ccbp+5 + -0x1.8be0ab9ca13aep+4i, 0x1.24b761aacc5c2p+4 + 0x1.67bd277ed5ed5p+5i,
-0x1.9b448cb74cd89p+6 + 0x1.37fc38e42e96ap+3i, 0x1.3bc81a4e88b3p+2 + -0x1.10fd8b18e5fdap+5i,
-0x1.c0ec23cb4d003p+5 + -0x1.45b330ac047aap+5i, 0x1.f013398f72928p+5 + 0x1.0e16680a43493p+4i,
-0x1.b9b030a2092e4p+5 + 0x1.b383fd292482p+2i, -0x1.246e8b78ad544p+6 + -0x1.0db371b907e3ap+5i,
0x1.1fb3b722eee4ep+3 + -0x1.46330eb808aa8p+6i, -0x1.f6f8f75113984p+4 + 0x1.7caf8d2956939p+4i,
-0x1.a74af9820281ap+4 + 0x1.605c5b016dabp+4i, -0x1.6725d05d718c6p+5 + -0x1.a6e3532b19f28p+1i,
-0x1.d9045afcf236fp+5 + -0x1.61899a5683c31p+5i, 0x1.4a70ac1d64445p+5 + -0x1.27f89d7e5af79p+3i,
-0x1.ff04eafaa3262p+4 + 0x1.2194cacc79b57p+4i, -0x1.51d2c4c2a6c3fp+6 + 0x1.693325812a0b9p+4i,
-0x1.6561a269e1488p+5 + -0x1.a8a02c6d7921dp+4i, -0x1.2e0ab41d92204p+2 + -0x1.13738e6f11c8p+1i,
-0x1.2ed399010cd6ep+6 + 0x1.3d4993ed2952ap+2i, -0x1.286538b6cf496p+5 + -0x1.40a01fac7afd7p+4i,
-0x1.9046dfbb92d88p+5 + -0x1.42a9909cc261dp+5i, -0x1.41d4d1d89be0ep+5 + -0x1.9a6d1bfb219d6p+3i,
-0x1.1b5ab510be79bp+5 + -0x1.54461a3830fa8p+3i, -0x1.4049b465ab54ap+5 + 0x1.43ab0900e2914p+3i,
-0x1.2c342532852e4p+6 + 0x1.bc732cbd7cc66p+5i, -0x1.daee9a65ace47p+5 + -0x1.86cae79eb2436p+4i,
0x1.e76a484fa19ep+1 + 0x1.9d4acd2f58ce4p+5i, -0x1.2a9c12a99c7b5p+5 + -0x1.64019311e172p+0i,
-0x1.d077528e3f062p+6 + -0x1.82400cc6310b6p+5i, 0x1.fff03c1ba9cf7p+3 + -0x1.059616f7daa8cp+6i,
0x1.885f8aa7973fp+5 + 0x1.ed0cb00681ea4p+3i, 0x1.6cb0aa5f0a8d9p+5 + 0x1.8363bc4bd8107p+3i,
-0x1.416bde296d17ap+5 + -0x1.6bd26d68799d8p+1i, -0x1.66862bc9c41a8p+2 + -0x1.78183ccc9791ep+3i,
0x1.b7b69a3a1fad6p+5 + 0x1.8b2c69e89b61cp+3i, -0x1.ed54aeca77448p+4 + 0x1.0de1f47533505p+3i,
-0x1.644ae14db62bbp+5 + -0x1.5f7ca698db956p+5i, -0x1.17b67d4b8d9a8p+5 + -0x1.3f97f12f56c22p+5i,
-0x1.5ce9b167135ap+3 + -0x1.6dd038daaef1bp+5i, -0x1.1a108e2385756p+4 + 0x1.00e59f2015bep+6i,
-0x1.cc803de874968p+4 + -0x1.4ce986a53d60fp+3i, -0x1.4350b6ef35947p+4 + 0x1.051d9a7e2afe8p+2i,
-0x1.e8a04eb180378p+3 + 0x1.7440411854b9bp+2i, -0x1.32cf16ebd0ap+4 + 0x1.a17d0b36a63e4p+4i,
-0x1.1c7487b0f6febp+4 + -0x1.5952e47085988p+5i, -0x1.31bd8d0cce7ep+5 + -0x1.c1de747cc1e22p+4i,
-0x1.02f31298a85cp+4 + -0x1.1695f9eb72859p+6i, -0x1.cb7349b389c65p+4 + 0x1.5b9a13e46b1ccp+3i,
-0x1.65d1ecaf68178p+5 + 0x1.e7d9383b6802p+0i, -0x1.f7547f2aa3618p+5 + -0x1.bce0ccf5dba7ep+3i,
0x1.f9fe118f97815p+4 + -0x1.7c0905d297d6fp+6i, -0x1.296792c1c291ap+5 + 0x1.2f988bfd38b56p+3i,
-0x1.3caf039983d18p+1 + -0x1.865db26b3fc4ep+6i, -0x1.93c6b39348836p+6 + 0x1.ca1c317965248p+1i,
0x1.ac9b3d135d9p-1 + -0x1.b6c357032b00fp+5i, -0x1.a5ea11f21ac46p+5 + -0x1.0e3bc7e5bdb7p+6i,
-0x1.5ae8e31231c2p+3 + -0x1.00438ac8e864cp+6i, -0x1.8c0f45cce8cecp+4 + -0x1.c4cd21458657cp+4i,
-0x1.06970be16f2a4p+7 + -0x1.32289d842f83p+1i, 0x1.3c86adc2f409cp+1 + -0x1.0e22a83a65ff8p+5i,
0x1.0e691af81329p+3 + -0x1.4e848ea7279fcp+3i, -0x1.214760b1c47c5p+4 + 0x1.57e9f045c481cp+6i,
-0x1.25b25cf157cfcp+7 + -0x1.10965f2a6b854p+5i, -0x1.08b45f83a91dcp+5 + 0x1.48427893cc47ep+5i,
-0x1.138c96bf7dbdp+4 + 0x1.12a7c7e5fa8fp+4i, -0x1.32ccb69219ddp+4 + 0x1.d79036f340aap+1i,
-0x1.7f5bffbb42df5p+4 + -0x1.0f324e1cc30e4p+4i, -0x1.7abe36a4650a5p+4 + -0x1.7ac696837b4bp+5i,
-0x1.83712c81d552p+4 + 0x1.33bda65529fdbp+6i, 0x1.cd96550194387p+5 + -0x1.0af6c636ea488p+4i,
-0x1.69d79fb351484p+2 + -0x1.0d330d557078ap+5i, 0x1.f184baeb60524p+2 + -0x1.50aa1677a0f94p+5i,
-0x1.1caf93a6e61e8p+4 + -0x1.0b92e046b2fcp+1i, 0x1.35ffd99ded715p+6 + -0x1.9ca05d2536551p+6i,
-0x1.89af0a205383ap+3 + 0x1.0d93ba6311eb8p+5i, 0x1.829a2e28f6p-1 + -0x1.6058a66a7dcep+3i,
-0x1.f64d574245d14p+5 + 0x1.002e583559de6p+4i, -0x1.5db6afbbb7968p+3 + -0x1.3df089c19f859p+6i,
0x1.767b013eb0145p+6 + -0x1.63c2d0222441ap+4i, 0x1.3f29ac48a2bap+6 + -0x1.17094eea3cd32p+6i,
-0x1.6ca13047f6b58p+6 + -0x1.092d2fda7d2c2p+4i, -0x1.10a4199d8f8e2p+5 + -0x1.386523d8cbc68p+1i,
0x1.de5c4271f0a5fp+5 + -0x1.6ac965f50f057p+7i, -0x1.2e5b5add0e038p+2 + 0x1.7e7ed60d1282p+5i,
0x1.8839113f237e4p+2 + -0x1.046a03385d6p-2i, -0x1.81f2c632f9c8dp+2 + 0x1.a9e119e9f953ep+4i,
0x1.0bdc309c1aa7p+6 + -0x1.1060c90714058p+4i, 0x1.e5a5f085ed282p+6 + -0x1.a2fc85bd835dap+5i,
-0x1.ba655187caaddp+5 + 0x1.90e0f55b504e2p+6i, 0x1.592a4897081cdp+6 + -0x1.1233c5b2ec7d1p+5i,
0x1.50c55ac480a8ep+6 + -0x1.5e5c2860cfcep+1i, -0x1.2e70269ad527p+3 + 0x1.8166047581888p+4i,
-0x1.31bbee051719p+5 + 0x1.15cde40838a44p+6i, 0x1.7a623d8f4016dp+6 + -0x1.31070076fb70ap+5i,
0x1.0423d958ae68cp+8 + -0x1.af537fcdf37cap+5i, -0x1.a41a885cdb865p+6 + -0x1.de5ace05a8e1dp+5i,
-0x1.3987ad68d1274p+3 + -0x1.36783a135ddcdp+7i, 0x1.f5ed4b47fcfdp+6 + -0x1.60b1ad9de0195p+6i,
0x1.089045da1b628p+7 + 0x1.895ea0a49ace2p+6i, -0x1.2d76deb892e55p+7 + -0x1.e547f3aa4eadbp+6i,
0x1.924133eeec9d4p+2 + -0x1.4336410a761ccp+5i, -0x1.93f5dd3515379p+6 + -0x1.1265b2476f6b3p+6i,
0x1.de70abc02523cp+5 + -0x1.15b208535441ep+6i, -0x1.5a9b0a8b76934p+6 + -0x1.13b21635a4d98p+8i,
-0x1.ba435666f0a68p+4 + 0x1.e5ddf70e55c28p+2i, 0x1.42f440d275d06p+4 + -0x1.7bd00686fe8f5p+4i,
-0x1.123210d139558p+3 + -0x1.e969db35deb3fp+4i, -0x1.616599568f347p+4 + -0x1.da9775c12f2fdp+4i,
-0x1.b28691b96eb5p+4 + -0x1.97b773159a7b4p+6i, -0x1.423302a82d6ap+0 + 0x1.4c13db02c48eap+5i,
-0x1.013c76e2bbacfp+8 + -0x1.6d07c80aa2e28p+7i, 0x1.5eeb89627b7e8p+7 + -0x1.200b0dbacb7fcp+7i,
-0x1.c96d0fc5de406p+5 + 0x1.c47fdf597c084p+6i, 0x1.3c675ee1efb84p+5 + -0x1.df9c557b3be1cp+5i,
-0x1.ccef2d256bb86p+8 + 0x1.f8f38522353cap+7i, -0x1.6f72f73630848p+6 + -0x1.9663ff776ba1cp+6i,
0x1.e02be52ec9c5ap+6 + -0x1.0159245633efep+7i, -0x1.05e161facd218p+7 + 0x1.b02a8f0ab7f76p+7i,
-0x1.74748e6bf28d3p+7 + 0x1.e90c9ffbdc98cp+3i, -0x1.398ec3b749564p+6 + -0x1.28bdbd79c138ap+8i,
0x1.7451f918f3bbep+6 + -0x1.930a2422786d9p+6i, 0x1.8d0136158abp+4 + 0x1.59d55390dd1bcp+8i
)
assertThat(stats:::fft(z=c(-23.7708328961019, -2.48921505288605, -4.90830773790793, -14.4661842424985,
-0.0112409636343406, -18.5187018260077, -11.083880463647, -5.33346401321436,
-21.001660964052, -2.47440694787375, -3.64289619709057, -0.485671274325257,
-1.79150748730684, -0.00699051626401592, -5.84161465236154, 3.93541806689383,
0.580090052642676, 8.83280397726006, -0.0855815903316173, 4.86314588739365,
0.893315847228107, -1.39413198498495, -9.43505914289666, -1.89582261049555,
-2.92584908474875, -0.167023699559072, -0.95211123444879, -0.0850797145816957,
-2.27890951884572, -0.0240852501124118, 0.297792537522955, 4.07403716521123,
-1.55709869399089, 0.794901604001893, 0.61639845328725, 0.60652209619971,
-1.73787669761526, -4.42267314671622, -2.25810095330843, -2.38106109234659,
-0.152614629435355, -3.5818727977903, -3.79637026343724, -0.0628129499795985,
-5.45480541078524, -5.25873801964453, -0.524089349557156, -1.64797077778525,
-8.81562418347194, -2.203854673928, -0.465662662602988, -4.27473933998855,
-1.15524467357413, -1.3173188710311, 0.0261379057483793, -13.2515228047897,
0.579270570920853, -3.76365942440711, -6.09045013757277, -4.09447631000989,
-0.594551821624292, -3.13583397010958, 2.1948508590458, 3.17925315041831,
-0.336522923571445, 1.77027254991647, -3.35912813364607, 0.767620154866166,
-0.519152728792464, -5.59072572408497, 0.351053050125732, -1.47227845477831,
-3.29702326535081, -4.460501645463, 1.52352976889322, -4.44252504084926,
0.751113315054035, -3.421485926237, -0.0011131292069267, -0.611950853556652,
2.00633725675673, -0.328110272508359, 3.61905869429299, -1.0387114622791,
-1.97069348996823, 0.957313748450439, -3.04446310768145, 0.476038535978084,
1.71992445613516, -1.87173432459001, 2.31592422483145, -3.89693114502531,
-0.00231724417211365, -1.37856367193994, 4.66621624867694, 1.84820218129735,
4.53703512467387, -3.11217913779258, -4.98728947434255, 1.85212739292499,
-6.09479337590528, -0.739389424181602, -6.13477905916407, 1.26666787409151,
-6.60037366550041, -7.31723751792718, 0.364699359003178, -10.9086928700515,
-9.67060579259072, 7.01274179196495, -3.05386630925926, 1.90465844957369,
6.74978018731347, -0.157958709779155, 8.21784987499043, -4.88920451071072,
3.88169217013359, -2.51846998794342, -7.6482159924715, -2.67093252742662,
-0.795368258356022, -10.0767647689672, -0.744350077963692, -3.5023958195383,
-0.557160274458648, -0.796910998277958, 2.06672597719393, 0.150284569933939,
3.60909318296994, 3.41878757873279, 0.150117842665926, 3.83376341569708,
0.0056135019428917, -0.94002986557939, 5.98096615092899, 5.06302546555031,
-1.47198614356067, 8.50795526087376, 0.294391090897194, 9.66282612560964,
-2.08205932867156, 3.65346402206044, 0.817169735872419, 0.932363354024994,
0.0838267021344608, 4.35696604612699, 0.0011403547375502, 1.87624668305354,
0.118114143455508, -3.56918046914932, 2.48958723337287, -9.79955497292962,
-1.53517280463178, 0.262116677362443, -8.15360823029713, 7.47698965906146,
-0.896188552072715, 0.853563522421709, -2.34303467101326, -3.40927262943559,
1.39711266137523, -8.58976501193787, 0.0673953311905804, -7.01249516176988,
-1.81953774771164, -0.75028488737011, -7.85089806213536, -0.115439816286216,
1.88751694393334, -11.1217917608909, -3.9268463960581, -3.68175431954811,
-12.6368639218082, 0.0964019615309718, -10.7992420808952, -7.03604736814949,
-1.48809939406581, -6.58079559232476, -3.83651375198913, 0.0412560858732186,
-0.470671295619956, 0.715188870932853, 0.0161282637791481, -2.07497355320696,
-8.77215545542282, -1.87146186385855, -5.79663959819262, -0.0220820188886129,
3.26187500832309, -0.597975134956941, 1.04140895918285, 0.847425492903929,
0.171097595802369, -0.269053071844262, 0.200776424169706, 0.946810931635553,
0.0535106818155922, -1.5662852174347, -11.4462035679278, -1.34505606949549,
-4.70291881416161, -0.161173920653758, 1.50028203409213, 0.512906238070806,
3.34841196153997, -0.405650415891143, -0.286226001565449, 4.01481669642967,
-2.51995805250717, 6.62068561542198, 0.0186414157827039, 4.36835005407095,
3.01018100235096, -3.37294516113314, 5.30349993964238, -1.04740683554501,
-2.77957505019764, -5.47003826094368, -12.9205653962092, -1.31054197471382,
-12.7006806639148, 0.98071531505332, -9.3337132816696, -7.88202142164254,
0.0290063956716996, -15.9463258109089, -0.249851816611657, 2.51845535401001,
-12.3831584719474, -5.09800673335618, 7.71774284278186, -14.4272937650689,
12.7750092928108, -9.75517948564174, 5.58092474352622, -2.0786740214615,
-16.6076418415933, 1.93546019463257, -7.22941825349685, -0.604779345248724,
-0.0380796614495173, -0.442412191893814, -5.19003574435343, -1.51425133367873,
0.328449276296988, -2.30676657138257, 4.51359805143108, 5.94900325472736,
2.55780713186469, 12.0365097591601, -0.350983180146331, 2.03137884695212,
2.59702831888015, -0.286166583217754, -0.301369922198854, -0.609741219605781,
-3.94636013356208, -1.07059680270632, 0.279290355232868, -2.59224305773414,
-0.782055223621052, 4.08193163726087, -10.5815036701018, -7.39266086900985,
-0.406112911818016, -17.2813308745814, -1.85936095421505, -15.806565214123,
-8.59802311713947, -3.31232179056552, -15.8804404253228, 0.338994453453923,
-2.48229567490467, -12.3949326434608, -0.125799452112133, -4.76193938087667,
-9.08056108879784, -0.960827207462225, -8.61349346045266, -5.11465044429881,
1.85608607955244, -7.76662678870028, -2.41185063029492, -6.00872596773918,
-0.0961085034219549, -0.226751413320635, -0.701154301093359,
3.75799494635908, 0.484263025818292, 0.650839155322851, 2.09820817230294,
0.461505956959652, 3.0719822690346, 1.96619289958002, -1.28329335671985,
3.92345110436591, 1.4796962189703, -2.87503911708975, 0.016449694713669,
-2.7973903416279, -4.44677865337309, -1.83128370986172, -9.24368939400586,
0.16176300273731, -4.44672359700833, -5.38128714422861, -0.505292299085497,
-4.75338356447713, -3.64267185145559, 9.32698648939374, -3.72079007515387,
-3.72085980600647, 0.851471462286869, -3.98502900524379, -4.69399475838604,
-1.0146650902497, -9.35315442132272, -0.432872368819136, -5.45273299190182,
-20.2358431688654, -0.0580885705320379, -12.3400069994593, -13.2357278451641,
10.3029992236082, -8.824015078503, -6.97048285863946, 5.0998435467116,
-5.4906060918701, 0.278974228302104, -2.86450419989226, -6.97741646531178,
3.26857829808821, -8.62427487521362, -19.5435094704963, -0.430284610840763,
-33.3971576710936, -9.4960610648362, -8.0517802734759, -24.2842566595871,
-0.302509243111669, -15.888937036993, -10.0974809181923, -0.825107439627948,
-18.2363783722242, -1.34238282407111, -13.9482247487648, -23.339636337563,
6.94670264911198, -8.19409730508363, -30.8453598515067, 4.3492422636956,
-17.8500283608891, -0.342537230017422, 0.466879231667901, -16.9150299607625,
1.29754784316414, -10.8255811654385, -13.0962743046474, -0.718287360059733,
-4.73560549883694, 0.92555876224882, 0.894667253879575, 3.04681288490875,
3.41031751671125, -1.76960993297074, 1.28231715573552, 0.0447747411873069,
-1.5816298496508, -1.65746997241004, -0.521929750354521, -4.84376045266799,
-0.377763205198271, 4.43657188857965, -1.05747013923845, -0.488748151471062,
1.59757423651317, -1.35932049537957, -2.67581452717236, -0.653970483263626,
-0.780747293148137, -1.96747937745114, 0.464219672364819, 1.57846726067049,
-2.38268223797788, -1.01151859434694, 0.334921929412904, -8.86110181014566,
-0.897558543432608, -8.3392573466435, -6.60368996348284, -2.32360044534742,
-7.49048926597187, -1.48266109891754, -8.85536791013645, -9.30677909523497,
-1.05682779622314, -7.24028288954046, -2.6520361148532, 1.76248220023412,
-8.6136738139441, 4.0484970522523, 2.50149988391237, -3.45376596079403,
7.72639905329669, -8.08941080048887, 4.08648617701736, 8.59258828063225,
-6.50741110419116, 2.4495301999403, -3.04486607588424, -2.07422050173826,
0.530759052159716, -0.458774960575477, -2.41734927444894, -1.44428807078285,
-0.502305972586792, -0.0280919109939653, 0.257846089968202, -1.42436350767346,
1.81221254933213, 4.59350664320127, 1.11332742192993, 1.16149503171754,
0.36535808966167, -2.68535388040155, 0.721475247046701, -0.15725590789861,
-1.41146428874462, 2.85950639992502, 0.101103088164485, -0.160726220552455,
-0.31692834219527, -0.338286779841711, -4.14497474944947, -2.50789089266492,
1.40254044921914, -4.68839189801662, 0.130727831047866, -12.2055694701825,
0.435136114228676, -2.73052231356705, -2.21111393534214, -2.00361466932587,
1.81668340740864, -5.3313559132075, 0.345897001172932, 1.13686232350228,
-5.26651213380651, -4.78973178084752, -1.5936337086337, -11.9481636405046,
2.98236949155947, -7.99370525305061, 0.905741341963133, 11.0514655594728,
2.54671290745589))
, identicalTo( expected, tol = 1e-6 ) )
|
`rbfkernel` <-
function(X, sigma = 1, Y = NULL)
{
if(!is.matrix(X))
{
print("X must be a matrix containing samples in its rows")
return()
}
if(length(sigma) != 1 || sigma <= 0)
{
print("sigma must be a number > 0 specifying the rbf-kernel width")
return()
}
if(!is.null(Y))
{
if(!is.matrix(Y))
{
print("Y must be a matrix containing samples in its rows or NULL if it should not be used")
return()
}
if(ncol(X) != ncol(Y))
{
print("The samples in the rows of X and Y must be of same dimension")
return()
}
}
n <- nrow(X)
if(is.null(Y))
{
XtX <- tcrossprod(X)
XX <- matrix(1, n) %*% diag(XtX)
D <- XX - 2*XtX + t(XX)
}
else
{
m <- nrow(Y)
XX <- matrix(apply(X ^ 2, 1, sum), n, m)
YY <- matrix(apply(Y ^ 2, 1, sum), n, m, byrow = TRUE)
XY <- tcrossprod(X, Y)
D <- XX - 2*XY + YY
}
K <- exp(-D/(2*sigma))
return(K)
}
|
focalMultiBand <- function(x,
w,
fun,
filename = "",
na.rm = FALSE,
pad = FALSE,
padValue = NA,
NAonly = FALSE,
keepNA = TRUE,
...) {
UseMethod("focalMultiBand", x)
}
focalMultiBand.Raster <- function(x,
w,
fun,
filename = "",
na.rm = FALSE,
pad = FALSE,
padValue = NA,
NAonly = FALSE,
keepNA = TRUE,
...) {
if (class(x)[1] == "RasterLayer") {
if (missing(fun)) {
out <- raster::focal(x = x, w = w, filename = "", na.rm = na.rm, pad = pad
, padValue = padValue, NAonly = NAonly, ...)
} else {
out <- raster::focal(x = x, w = w, fun = fun, filename = "", na.rm = na.rm
, pad = pad, padValue = padValue, NAonly = NAonly, ...)
}
} else if (class(x)[1] %in% c("RasterStack", "RasterBrick")) {
x.list <- raster::as.list(x)
if (missing(fun)) {
out <- lapply(x.list, function(r) raster::focal(x = r, w = w, na.rm =
na.rm, pad = pad, padValue = padValue, NAonly = NAonly, filename = ""))
} else {
out <- lapply(x.list, function(r) raster::focal(x = r, w = w, fun = fun,
na.rm = na.rm, pad = pad, padValue = padValue, NAonly = NAonly, filename
= ""))
}
out <- raster::stack(out)
} else {
stop("x must be a Raster object")
}
if (keepNA) {
out <- raster::mask(x = out, mask = x, maskValue = NA)
}
if (filename != "") {
names(out) <- names(x)
out <- raster::writeRaster(out, filename = filename, ...)
}
names(out) <- names(x)
return(out)
}
focalMultiBand.list <- function(x,
w,
fun,
filename = "",
na.rm = FALSE,
pad = FALSE,
padValue = NA,
NAonly = FALSE,
keepNA = TRUE,
...) {
if (length(filename) < length(list)) {
toAdd <- length(list) - length(filename)
filename = c(filename, rep("", toAdd))
}
filename_non_empty <- filename[filename != ""]
if (length(unique(filename_non_empty)) != length(filename_non_empty)) {
stop("filename must have unique values (other than \"\") for each element of the list x")
}
args <- c(as.list(environment()), list(...))
args <- args[ ! names(args) %in% c("x", "filename")]
mapply(focalMultiBand, x, filename, MoreArgs = args)
}
|
Pi.matrix <- function(group, data, formula, ref.level){
if (!is.factor(group))
group <- factor(group, levels=unique(group))
if (is.numeric(ref.level)) ref.level <- as.character(ref.level)
if (!(ref.level %in% levels(group))) stop("'ref.level' is not a level of 'group'")
if (missing(data)) {
stop("Needs data to calculate probailities")
}else{
if (nrow(data) != length(group)) { stop("'data' has wrong dimensions") }
}
alt.levels <- levels(group)[levels(group) != ref.level]
data.reg <- as.data.frame(data)
if(missing(formula)){
formula <- as.formula(paste("~", paste(colnames(data), collapse = "+")))}
data.reg <- cbind(ind.pheno = group, data.reg)
rownames(data.reg) <- NULL
data.reg <- dfidx(data.reg, varying = NULL, shape = "wide", choice = "ind.pheno")
z <- as.character(formula)
if (z[1] != "~" | length(z) != 2) stop("'formula' should be a formula of the form \"~ var1 + var2\"")
z <- z[2]
my.formula <- Formula(as.formula(paste("ind.pheno ~ 0 | ", z)))
fit <- tryCatch(mlogit(my.formula, data = data.reg, reflevel = ref.level), error = identity, warning = identity)
if (is(fit, "error")) {
pi.matrix <- matrix(NA, ncol=nlevels(group), nrow=nrow(data), byrow=TRUE, dimnames=list(rownames(data), levels(group)))
}else{
pi.matrix <- matrix(fit$model$probabilities, ncol=nlevels(group), nrow=nrow(data), byrow=TRUE, dimnames=list(rownames(data), fit$model$idx$id2[1:nlevels(group)]))
pi.matrix <- pi.matrix[,levels(group)]
}
return(pi.matrix)
}
|
expected <- structure(8.33333333333333, units = "mins", .Names = "a", class = "difftime")
test(id=0, code={
argv <- structure(list(x = structure(500, units = "secs", class = "difftime", .Names = "a"),
value = "mins"), .Names = c("x", "value"))
do.call('units<-.difftime', argv);
}, o = expected);
|
setConstructorS3("GString", function(..., sep="") {
s <- paste(..., sep=sep)
if (length(s) > 1L) {
throw("Trying to coerce more than one character string to a GString, which is not supported.")
}
extend(s, "GString")
})
setMethodS3("getRaw", "GString", function(object, ...) {
unclass(object)
})
setMethodS3("print", "GString", function(x, ...) {
object <- x
print(as.character(object), ...)
})
setMethodS3("getBuiltinPid", "GString", function(static, ...) {
pid <- Sys.getpid()
pid
}, static=TRUE)
setMethodS3("getBuiltinHostname", "GString", function(static, ...) {
host <- Sys.getenv(c("HOST", "HOSTNAME", "COMPUTERNAME"))
host <- host[host != ""]
if (length(host) == 0L) {
tryCatch({
host <- readLines(pipe("/usr/bin/env uname -n"))
host <- host[host != ""]
}, error = function(ex) {})
}
if (length(host) == 0L)
host <- NA
host[1L]
}, static=TRUE)
setMethodS3("getBuiltinUsername", "GString", function(static, ...) {
user <- Sys.info()["user"]
user <- user[user != "unknown"]
if (length(user) == 0L) {
user <- Sys.getenv(c("USER", "USERNAME"))
user <- user[user != ""]
}
if (length(user) == 0L) {
tryCatch({
user <- readLines(pipe("/usr/bin/env whoami"))
user <- user[user != ""]
}, error = function(ex) {})
}
if (length(user) == 0L)
user <- NA
user[1L]
}, static=TRUE)
setMethodS3("getBuiltinDate", "GString", function(static, format="%Y-%m-%d", ...) {
args <- list(Sys.time(), format=format)
do.call(base::format, args)
}, static=TRUE)
setMethodS3("getBuiltinTime", "GString", function(static, format="%H:%M:%S", ...) {
args <- list(Sys.time(), format=format)
do.call(base::format, args)
}, static=TRUE)
setMethodS3("getBuiltinDatetime", "GString", function(static, format=NULL, ...) {
args <- list(Sys.time(), format=format)
do.call(base::format, args)
}, static=TRUE)
setMethodS3("getBuiltinRversion", "GString", function(static, ...) {
getRversion()
}, static=TRUE)
setMethodS3("getBuiltinRhome", "GString", function(static, ...) {
R.home()
}, static=TRUE)
setMethodS3("getBuiltinOs", "GString", function(static, ...) {
.Platform$OS.type
}, static=TRUE)
setMethodS3("getVariableValue", "GString", function(static, name, attributes="", where=c("builtin", "envir", "parent", "Sys.getenv", "getOption"), envir=parent.frame(), inherits=TRUE, missingValue=NA, ...) {
if (is.null(name)) {
throw("Argument 'name' is NULL.")
} else if (!is.character(name)) {
throw("Argument 'name' must be a character string: ", mode(name))
}
.stop_if_not(is.environment(envir))
attrs <- strsplit(attributes, split=", ")[[1L]]
if (length(attrs) > 0L) {
isSimpleAttr <- (regexpr("^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9._]+=.*$", attrs) == -1L)
simpleAttrs <- attrs[isSimpleAttr]
if (length(simpleAttrs) == 0L)
simpleAttrs <- NULL
attrs <- paste(attrs[!isSimpleAttr], collapse=", ")
attrs <- eval(parse(text=paste("list(", attrs, ")")))
} else {
attrs <- NULL
simpleAttrs <- NULL
}
value <- NULL
for (ww in where) {
if (ww == "builtin") {
capitalizedName <- paste(toupper(substr(name, start=1L, stop=1L)), substr(name, start=2L, stop=nchar(name)), sep="")
builtInMethodName <- paste("getBuiltin", capitalizedName, sep="")
tryCatch({
args <- list(static)
args <- c(args, attrs)
value <- do.call(builtInMethodName, args=args)
}, error = function(ex) { })
} else if (ww == "Sys.getenv") {
value <- Sys.getenv(name)
if (nchar(value) == 0L)
value <- NULL
} else if (ww == "getOption") {
value <- getOption(name)
} else if (ww == "envir") {
if (exists(name, envir=envir, inherits=inherits)) {
value <- get(name, envir=envir, inherits=inherits)
}
} else if (ww == "parent") {
envirL <- NULL
n <- 0L
while (TRUE) {
n <- n + 1L
envirP <- parent.frame(n=n)
if (identical(envirP, envirL))
break
envirL <- envirP
if (exists("...abcdef", envir=envirP, inherits=FALSE))
next
if (exists(name, envir=envirP, inherits=FALSE)) {
value <- get(name, envir=envirP, inherits=FALSE)
break
}
if (identical(envir, .GlobalEnv))
break
}
} else {
if (exists(ww, mode="function")) {
tryCatch({
args <- c(attrs, list(...))
value <- do.call(name, args=args)
}, error = function(ex) {})
} else {
throw("Unknown search location of variable '", name, "': ", ww)
}
}
if (!is.null(value)) {
tryCatch({
value <- as.character(value)
}, error = function(ex) {
value <<- NA
})
for (attr in simpleAttrs) {
if (attr == "capitalize") {
value <- paste(toupper(substring(value, first=1L, last=1L)),
substring(value, first=2L), sep="")
} else {
tryCatch({
fcn <- get(attr, mode="function")
value <- fcn(value)
}, error = function(ex) {})
}
}
if (any(nchar(value) > 0L))
break
}
}
if (is.null(value)) {
value <- missingValue
}
value
}, static=TRUE, private=TRUE)
setMethodS3("parse", "GString", function(object, ...) {
s <- getRaw(object)
if (length(s) == 0L || !regexpr("${", s, fixed=TRUE) != -1L) {
return(list(text=s))
}
parts <- list()
while(TRUE) {
pattern <- "^\\$(\\[.*\\]|)\\{([^\\}]*)\\}"
pos <- regexpr(pattern, s)
matchLen <- attr(pos, "match.length")
pos <- pos[1L]
if (pos != -1L) {
text <- ""
} else {
pattern <- "[^\\\\$]\\$(\\[.*\\]|)\\{([^\\}]*)\\}"
pos <- regexpr(pattern, s)
matchLen <- attr(pos, "match.length")
pos <- pos[1]
if (pos != -1) {
text <- substr(s, start=1L, stop=pos)
text <- gsub("\\\\\\$", "$", text)
} else {
text <- s
text <- gsub("\\\\\\$", "$", text)
parts <- c(parts, list(text=text))
break
}
}
prefix <- list(text=text)
parts <- c(parts, prefix)
last <- pos + matchLen - 1L
var <- substr(s, start=pos, stop=last)
attributes <- gsub(pattern, "\\1", var)
attributes <- gsub("^\\[", "", attributes)
attributes <- gsub("\\]$", "", attributes)
name <- gsub(pattern, "\\2", var)
searchReplace <- NULL
patterns <- c("^[']([^']*)[']$", '^["]([^"]*)["]$')
if (all(sapply(patterns, FUN=regexpr, name) == -1L)) {
pattern <- "^(.*)/(.*)/(.*)"
if (regexpr(pattern, name) != -1L) {
searchPattern <- gsub(pattern, "\\2", name)
replacePattern <- gsub(pattern, "\\3", name)
name <- gsub(pattern, "\\1", name)
searchReplace <- list(search=searchPattern, replace=replacePattern)
}
} else {
for (pattern in patterns) {
name <- gsub(pattern, "\\1", name)
}
}
pattern <- "^`(.*)`"
isExpression <- (regexpr(pattern, name) != -1L)
if (isExpression) {
call <- gsub(pattern, "\\1", name)
part <- list(expression=list(call=call))
} else {
part <- list(variable=list(name=name))
}
part[[1L]]$attributes <- attributes
part[[1L]]$searchReplace <- searchReplace
parts <- c(parts, part)
s <- substr(s, start=last+1L, stop=nchar(s))
if (nchar(s) == 0L)
break
}
parts
}, private=TRUE)
setMethodS3("evaluate", "GString", function(object, envir=parent.frame(), ...) {
.stop_if_not(is.environment(envir))
s <- unclass(object)
if (length(s) == 0L || !regexpr("${", s, fixed=TRUE) != -1L) {
return(s)
}
parts <- parse(object, ...)
keys <- names(parts)
...abcdef <- TRUE
isVariable <- (keys == "variable")
for (kk in which(isVariable)) {
part <- parts[[kk]]
value <- getVariableValue(object, name=part$name,
attributes=part$attributes, envir=envir, ...)
if (!is.null(part$searchReplace))
value <- gsub(part$searchReplace$search,
part$searchReplace$replace, value)
parts[[kk]] <- value
}
isExpression <- (keys == "expression")
for (kk in which(isExpression)) {
part <- parts[[kk]]
expr <- parse(text=part$call)
value <- eval(expr)
if (!is.null(part$searchReplace))
value <- gsub(part$searchReplace$search,
part$searchReplace$replace, value)
parts[[kk]] <- value
}
s <- ""
for (kk in seq_along(parts)) {
part <- parts[[kk]]
s <- paste(s, part, sep="")
}
s
}, protected=TRUE)
setMethodS3("as.character", "GString", function(x, envir=parent.frame(), ...) {
evaluate(x, envir=envir, ...)
})
|
"CellCycle"
|
WPSOutputDescription <- R6Class("WPSOutputDescription",
inherit = WPSDescriptionParameter,
private = list(),
public = list(
initialize = function(xml = NULL, version, logger = NULL, ...){
super$initialize(xml = xml, version = version, logger = logger, ...)
}
)
)
|
prev = getOption("batchtools.verbose")
options(batchtools.verbose = FALSE)
test_that("batchmark", {
requirePackagesOrSkip("batchtools")
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE, seed = 1)
task.names = c("binary", "multiclass")
tasks = list(binaryclass.task, multiclass.task)
learner.names = c("classif.lda", "classif.rpart")
learners = lapply(learner.names, makeLearner)
rin = makeResampleDesc("CV", iters = 2L)
ids = batchmark(learners = makeLearner("classif.lda", predict.type = "prob"),
tasks = binaryclass.task, resamplings = rin, reg = reg)
expect_data_table(ids, ncol = 1L, nrow = 2, key = "job.id")
expect_set_equal(ids$job.id, 1:2)
tab = summarizeExperiments(reg = reg)
expect_equal(tab$problem, "binary")
expect_equal(tab$algorithm, "classif.lda")
expect_set_equal(findExperiments(reg = reg)$job.id, 1:2)
submitJobs(reg = reg)
expect_true(waitForJobs(reg = reg))
res = reduceBatchmarkResults(reg = reg)
preds = getBMRPredictions(res, as.df = FALSE)
expect_true(is.list(preds))
expect_true(setequal(names(preds), "binary"))
preds1 = preds[[1L]]
expect_true(is.list(preds1))
expect_true(setequal(names(preds1), "classif.lda"))
preds11 = preds1[[1L]]
expect_s3_class(preds11, "Prediction")
preds = getBMRPredictions(res, as.df = TRUE)
expect_s3_class(preds, "data.frame")
expect_equal(nrow(preds), getTaskSize(binaryclass.task))
expect_equal(ncol(preds), 9)
expect_equal(unique(preds$iter), 1:2)
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE, seed = 1)
res = batchmark(learners = learners, tasks = tasks, resamplings = rin, reg = reg)
submitJobs(reg = reg)
expect_true(waitForJobs(reg = reg))
res = reduceBatchmarkResults(reg = reg)
expect_true(all(sapply(res$results$binary[[1]]$extract, function(x) is.null(x))))
expect_true("BenchmarkResult" %in% class(res))
df = as.data.frame(res)
expect_true(is.data.frame(df))
expect_equal(dim(df), c(rin$iters * length(task.names) * length(learner.names), 4L))
expect_true(setequal(df$task.id, task.names))
expect_true(setequal(df$learner.id, learner.names))
expect_true(is.numeric(df$mmce))
expect_equal(getBMRTaskIds(res), task.names)
expect_equal(getBMRLearnerIds(res), learner.names)
expect_equal(getBMRMeasures(res), list(mmce))
expect_equal(getBMRMeasureIds(res), "mmce")
preds = getBMRPredictions(res, as.df = FALSE)
expect_true(is.list(preds))
expect_true(setequal(names(preds), task.names))
preds1 = preds[[1L]]
expect_true(is.list(preds1))
expect_true(setequal(names(preds1), learner.names))
preds11 = preds1[[1L]]
expect_s3_class(preds11, "Prediction")
preds = getBMRPredictions(res, as.df = TRUE)
expect_s3_class(preds, "data.frame")
expect_equal(nrow(preds), 2 * (getTaskSize(multiclass.task) + getTaskSize(binaryclass.task)))
p = getBMRPerformances(res, as.df = TRUE)
expect_s3_class(p, "data.frame")
expect_equal(nrow(p), length(task.names) * length(learner.names) * rin$iters)
a = getBMRAggrPerformances(res, as.df = TRUE)
expect_s3_class(a, "data.frame")
expect_equal(nrow(a), length(task.names) * length(learner.names))
ps = makeParamSet(makeDiscreteLearnerParam("cp", values = c(0.01, 0.1)))
learner.names = c("classif.lda", "classif.rpart", "classif.lda.featsel",
"classif.rpart.tuned", "classif.lda.filtered")
learners = list(makeLearner("classif.lda"), makeLearner("classif.rpart"))
learners = c(learners, list(
makeFeatSelWrapper(learners[[1L]], resampling = rin, control = makeFeatSelControlRandom(maxit = 3)),
makeTuneWrapper(learners[[2L]], resampling = rin, par.set = ps, control = makeTuneControlGrid()),
makeFilterWrapper(learners[[1L]], fw.perc = 0.5)
))
resamplings = list(rin, makeResampleDesc("Bootstrap", iters = 2L))
measures = list(mmce, acc)
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE, seed = 1)
res = batchmark(learners = learners, tasks = tasks, resamplings = resamplings,
measures = measures, reg = reg, keep.extract = TRUE)
submitJobs(reg = reg)
expect_true(waitForJobs(reg = reg))
expect_data_table(findErrors(reg = reg), nrow = 0L)
res = reduceBatchmarkResults(reg = reg)
expect_true("BenchmarkResult" %in% class(res))
df = as.data.frame(res)
expect_true(is.data.frame(df))
expect_equal(dim(df), c(rin$iters * length(task.names) * length(learner.names), 5L))
expect_true(setequal(df$task.id, task.names))
expect_true(setequal(df$learner.id, learner.names))
expect_true(is.numeric(df$mmce))
expect_true(is.numeric(df$acc))
expect_equal(getBMRTaskIds(res), task.names)
expect_equal(getBMRLearnerIds(res), learner.names)
preds = getBMRPredictions(res, as.df = FALSE)
expect_true(is.list(preds))
expect_true(setequal(names(preds), task.names))
preds1 = preds[[1L]]
expect_true(is.list(preds1))
expect_true(setequal(names(preds1), learner.names))
preds11 = preds1[[1L]]
expect_s3_class(preds11, "Prediction")
preds = getBMRPredictions(res, as.df = TRUE)
expect_s3_class(preds, "data.frame")
p = getBMRPerformances(res, as.df = TRUE)
expect_s3_class(p, "data.frame")
expect_equal(nrow(p), length(task.names) * length(learner.names) * rin$iters)
a = getBMRAggrPerformances(res, as.df = TRUE)
expect_s3_class(a, "data.frame")
expect_equal(nrow(a), length(task.names) * length(learner.names))
tr = getBMRTuneResults(res, as.df = FALSE)
expect_list(tr)
expect_equal(length(tr), 2)
expect_true(setequal(names(tr), task.names))
tr1 = tr[[task.names[1L]]]
expect_true(is.list(tr1))
expect_true(setequal(names(tr1), learner.names))
tr11 = tr1[[paste0(learner.names[2L], ".tuned")]]
expect_equal(length(tr11), 2)
tr111 = tr11[[1L]]
expect_s3_class(tr111, "TuneResult")
trd = getBMRTuneResults(res, as.df = TRUE)
expect_s3_class(trd, "data.frame")
expect_equal(ncol(trd), 5)
expect_equal(nrow(trd), 4)
expect_equal(levels(as.factor(trd$task.id)), task.names)
expect_equal(levels(as.factor(trd$learner.id)), "classif.rpart.tuned")
expect_equal(unique(trd$iter), 1:2)
tf = getBMRFeatSelResults(res, as.df = FALSE)
expect_list(tf)
expect_equal(length(tf), 2)
expect_true(setequal(names(tf), task.names))
tf1 = tf[[task.names[1L]]]
expect_true(is.list(tf1))
expect_true(setequal(names(tf1), learner.names))
tf11 = tf1[[paste0(learner.names[1L], ".featsel")]]
expect_equal(length(tf11), 2)
tf111 = tf11[[1L]]
expect_s3_class(tf111, "FeatSelResult")
tfd = getBMRFeatSelResults(res, as.df = TRUE)
expect_s3_class(tfd, "data.frame")
expect_equal(ncol(tfd), 4)
feats = c(
lapply(tf$binary$classif.lda.featsel, function(x) x$x),
lapply(tf$multiclass$classif.lda.featsel, function(x) x$x)
)
expect_equal(nrow(tfd), sum(lengths(feats)))
expect_equal(levels(as.factor(tfd$task.id)), task.names)
expect_equal(levels(as.factor(tfd$learner.id)), "classif.lda.featsel")
expect_equal(unique(tfd$iter), 1:2)
tff = getBMRFilteredFeatures(res, as.df = FALSE)
expect_list(tff)
expect_equal(length(tff), 2)
expect_true(setequal(names(tff), task.names))
tff1 = tff[[task.names[1L]]]
expect_true(is.list(tff1))
expect_true(setequal(names(tff1), learner.names))
tff11 = tff1[[paste0(learner.names[1L], ".filtered")]]
expect_equal(length(tff11), 2)
tff111 = tff11[[1L]]
expect_type(tff111, "character")
tffd = getBMRFilteredFeatures(res, as.df = TRUE)
expect_s3_class(tffd, "data.frame")
expect_equal(ncol(tffd), 4)
expect_equal(nrow(tffd), 64)
expect_equal(levels(as.factor(tffd$task.id)), task.names)
expect_equal(levels(as.factor(tffd$learner.id)), "classif.lda.filtered")
expect_equal(unique(tffd$iter), 1:2)
f = function(tmp, cl) {
expect_true(is.list(tmp))
expect_true(setequal(names(tmp), task.names))
tmp = tmp[[1L]]
expect_equal(length(tmp), length(learners))
tmp = Filter(Negate(is.null), tmp)
expect_equal(length(tmp), 1L)
tmp = tmp[[1L]]
expect_true(inherits(tmp[[1L]], cl))
}
f(getBMRFeatSelResults(res), "FeatSelResult")
f(getBMRTuneResults(res), "TuneResult")
f(getBMRFilteredFeatures(res), "character")
})
test_that("keep.preds and models are passed down to resample()", {
skip_if_not_installed("batchtools")
requirePackagesOrSkip("batchtools")
task.names = "binary"
tasks = list(binaryclass.task)
learner.names = "classif.lda"
learners = lapply(learner.names, makeLearner)
rin = makeResampleDesc("CV", iters = 2L)
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE)
res = batchmark(learners = makeLearner("classif.lda", predict.type = "prob"), task = binaryclass.task, resampling = rin, models = TRUE, reg = reg)
submitJobs(reg = reg)
expect_true(waitForJobs(reg = reg))
res = reduceBatchmarkResults(reg = reg, keep.pred = TRUE)
x = res$results$binary$classif.lda
expect_s3_class(x, "ResampleResult")
expect_list(x$models, types = "WrappedModel")
expect_s3_class(x$pred, "ResamplePrediction")
models = getBMRModels(res)
expect_true(is.list(models))
expect_true(setequal(names(models), "binary"))
models1 = models[[1L]]
expect_true(is.list(models1))
expect_true(setequal(names(models1), "classif.lda"))
models11 = models1[[1L]]
expect_true(is.list(models11))
expect_equal(length(models11), 2L)
models111 = models11[[1L]]
expect_s3_class(models111, "WrappedModel")
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE)
res = batchmark(learners = makeLearner("classif.lda", predict.type = "prob"),
tasks = binaryclass.task, resamplings = rin, models = FALSE, reg = reg)
submitJobs(reg = reg)
expect_true(waitForJobs(reg = reg))
res = reduceBatchmarkResults(reg = reg, keep.pred = FALSE)
x = res$results$binary$classif.lda
models11 = getBMRModels(res)[[1L]][[1L]]
expect_s3_class(x, "ResampleResult")
expect_null(x$pred)
expect_null(models11)
})
test_that("batchmark works with resampling instances", {
requirePackagesOrSkip("batchtools")
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE, seed = 1)
task = binaryclass.task
learner.names = c("classif.lda", "classif.rpart")
learners = lapply(learner.names, makeLearner)
rdesc = makeResampleDesc("CV", iters = 2L)
rin = makeResampleInstance(rdesc, task)
ids = batchmark(learners = learners, tasks = task, resamplings = rin, reg = reg)
expect_data_table(ids, nrow = 4)
})
test_that("batchmark works with incomplete results", {
requirePackagesOrSkip("batchtools")
reg = makeExperimentRegistry(file.dir = NA, make.default = FALSE)
task = binaryclass.task
learner.names = c("classif.lda", "classif.rpart")
learners = lapply(learner.names, makeLearner)
rdesc = makeResampleDesc("CV", iters = 4L)
rin = makeResampleInstance(rdesc, task)
ids = batchmark(learners = learners, tasks = task, resamplings = rin, reg = reg)
submitJobs(1:6, reg = reg)
expect_true(waitForJobs(reg = reg))
expect_warning({
res = reduceBatchmarkResults(ids = 1:6, reg = reg, keep.pred = FALSE)
}, "subset")
expect_set_equal(getBMRLearnerIds(res), c("classif.lda", "classif.rpart"))
expect_warning({
res = reduceBatchmarkResults(ids = 1:3, reg = reg, keep.pred = FALSE)
}, "subset")
expect_set_equal(getBMRLearnerIds(res), "classif.lda")
expect_warning({
res = reduceBatchmarkResults(ids = data.table(job.id = 5), reg = reg, keep.pred = FALSE)
}, "subset")
expect_set_equal(getBMRLearnerIds(res), "classif.rpart")
})
options(batchtools.verbose = prev)
|
expected <- eval(parse(text="structure(list(coefficients = structure(NA_real_, .Names = \"x\"), residuals = structure(c(-0.667819876370237, 0.170711734013213, 0.552921941721332, -0.253162069270378, -0.00786394222146348, 0.0246733498130512, 0.0730305465518564, -1.36919169254062, 0.0881443844426084, -0.0834190388782434), .Names = c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\")), effects = structure(c(-0.667819876370237, 0.170711734013213, 0.552921941721332, -0.253162069270378, -0.00786394222146348, 0.0246733498130512, 0.0730305465518564, -1.36919169254062, 0.0881443844426084, -0.0834190388782434), .Names = c(\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\")), rank = 0L, fitted.values = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Names = c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\")), assign = 1L, qr = structure(list(qr = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 1L), .Dimnames = list(c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"), \"x\"), assign = 1L), qraux = 0, pivot = 1L, tol = 1e-07, rank = 0L), .Names = c(\"qr\", \"qraux\", \"pivot\", \"tol\", \"rank\"), class = \"qr\"), df.residual = 10L, xlevels = structure(list(), .Names = character(0)), call = quote(lm(formula = y ~ x + 0)), terms = quote(y ~ x + 0), model = structure(list(y = c(-0.667819876370237, 0.170711734013213, 0.552921941721332, -0.253162069270378, -0.00786394222146348, 0.0246733498130512, 0.0730305465518564, -1.36919169254062, 0.0881443844426084, -0.0834190388782434), x = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c(\"y\", \"x\"), terms = quote(y ~ x + 0), row.names = c(NA, 10L), class = \"data.frame\")), .Names = c(\"coefficients\", \"residuals\", \"effects\", \"rank\", \"fitted.values\", \"assign\", \"qr\", \"df.residual\", \"xlevels\", \"call\", \"terms\", \"model\"), class = \"lm\")"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(coefficients = structure(NA_real_, .Names = \"x\"), residuals = structure(c(-0.667819876370237, 0.170711734013213, 0.552921941721332, -0.253162069270378, -0.00786394222146348, 0.0246733498130512, 0.0730305465518564, -1.36919169254062, 0.0881443844426084, -0.0834190388782434), .Names = c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\")), effects = structure(c(-0.667819876370237, 0.170711734013213, 0.552921941721332, -0.253162069270378, -0.00786394222146348, 0.0246733498130512, 0.0730305465518564, -1.36919169254062, 0.0881443844426084, -0.0834190388782434), .Names = c(\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\")), rank = 0L, fitted.values = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Names = c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\")), assign = 1L, qr = structure(list(qr = structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(10L, 1L), .Dimnames = list(c(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"), \"x\"), assign = 1L), qraux = 0, pivot = 1L, tol = 1e-07, rank = 0L), .Names = c(\"qr\", \"qraux\", \"pivot\", \"tol\", \"rank\"), class = \"qr\"), df.residual = 10L, xlevels = structure(list(), .Names = character(0)), call = quote(lm(formula = y ~ x + 0)), terms = quote(y ~ x + 0), model = structure(list(y = c(-0.667819876370237, 0.170711734013213, 0.552921941721332, -0.253162069270378, -0.00786394222146348, 0.0246733498130512, 0.0730305465518564, -1.36919169254062, 0.0881443844426084, -0.0834190388782434), x = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), .Names = c(\"y\", \"x\"), terms = quote(y ~ x + 0), row.names = c(NA, 10L), class = \"data.frame\")), .Names = c(\"coefficients\", \"residuals\", \"effects\", \"rank\", \"fitted.values\", \"assign\", \"qr\", \"df.residual\", \"xlevels\", \"call\", \"terms\", \"model\"), class = \"lm\"))"));
do.call(`(`, argv);
}, o=expected);
|
"peccary"
|
expected <- eval(parse(text="c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49)"));
test(id=0, code={
argv <- eval(parse(text="list(0L, 49, 1)"));
do.call(`seq.int`, argv);
}, o=expected);
|
setMethodS3("equals", "default", function(object, other, ...) {
(is.null(object) && is.null(other)) || identical(object, other)
})
|
ctmaCombPRaw <- function(listOfStudyFits=NULL, moderatorValues=NULL) {
allSampleSizes <- maxLatents <- allTpoints <- c()
n.latent <- listOfStudyFits$n.latent; n.latent
n.manifest <- listOfStudyFits$n.manifest; n.manifest
if (is.null(n.manifest)) n.manifest <- 0
allSampleSizes <- listOfStudyFits$statisticsList$allSampleSizes; allSampleSizes
allTpoints <- listOfStudyFits$statisticsList$allTpoints; allTpoints; length(allTpoints)
currentVarnames <- c()
for (j in 1:(max(allTpoints))) {
if (n.manifest == 0) {
for (h in 1:n.latent) {
currentVarnames <- c(currentVarnames, paste0("V",h,"_T", (j-1)))
}
} else {
for (h in 1:n.manifest) {
currentVarnames <- c(currentVarnames, paste0("y",h,"_T", (j-1)))
}
}
}
targetColNames <- c(c(currentVarnames, paste0("dT", seq(1:(max(allTpoints)-1))))); targetColNames
n.var <- max(n.latent, n.manifest); n.var
alldata <- matrix(NA, 0, (n.var*max(allTpoints)+max(allTpoints)-1)); dim(alldata)
colnames(alldata) <- targetColNames; alldata
groups <- c()
if (!(is.null(moderatorValues))) {
moderatorGroups <- matrix(NA, nrow=0, ncol=dim(moderatorValues)[[2]])
}
for (i in 1:length(listOfStudyFits$studyFitList)) {
tmp <- listOfStudyFits$emprawList[[i]]
tmp2 <- colnames(tmp); tmp2
if (n.manifest > 0) colnames(tmp) <- gsub("V", "y", tmp2)
tmp <- tmp[, colnames(tmp) %in% targetColNames]
missingColNames <- colnames(alldata)[!(colnames(alldata) %in% colnames(tmp))]; missingColNames
tmp2 <- matrix(NA, dim(tmp)[1], length(missingColNames));
colnames(tmp2) <- missingColNames
tmp2 <- cbind(tmp, tmp2)
tmp2 <- as.data.frame(tmp2)
tmp3 <- grep("dT", colnames(tmp2)); tmp3
tmp2[tmp3][is.na(tmp2[tmp3])] <- .00001
alldata <- rbind(alldata, tmp2[, targetColNames])
groups <- c(groups, rep(i, dim(tmp)[1]))
if (!(is.null(moderatorValues))) {
if (!(is.na(moderatorValues[i]))) {
moderatorGroups <- rbind(moderatorGroups, (matrix(rep(unlist(moderatorValues[i, ]), dim(tmp2)[1]), nrow=dim(tmp2)[1], byrow=T)))
} else {
moderatorGroups <- rbind(moderatorGroups, (matrix(rep(NA, dim(tmp2)[1]), nrow=dim(tmp2)[1], byrow=T)))
}
}
}
casesToDelete <- c()
if(exists("moderatorGroups")) {
if (any(is.na(moderatorGroups))) {
casesToDelete <- which(is.na(moderatorGroups)); casesToDelete
alldata <- alldata[-casesToDelete]
moderatorGroups <- moderatorGroups[-casesToDelete]
}
}
if (!(is.null(moderatorValues))) {
toReturn <- list(alldata=alldata, groups=groups, moderatorGroups=moderatorGroups, casesToDelete=casesToDelete)
} else {
toReturn <- list(alldata=alldata, groups=groups)
}
return(toReturn)
}
|
glm_v <- function(...) {
fit <- glm(...)
print(tabglm(fit))
return(NULL)
}
|
pltltn<- function(object){
if (!inherits(object, "Bvs"))
stop("calling summary.Bvs(<fake-Bvs-x>) ...")
if (object$method != "gibbs")
stop("This corrected estimates are for Gibbs sampling objects.")
if (object$priorprobs!="ScottBerger"){
stop("This function was conceived to be used in combination with Scott-Berger prior\n")
}
cat("Info: Use this function only for problems with p>>n (not just p>n)\n")
kgamma<- rowSums(object$modelslogBF[,1:object$p])
isMr<- kgamma < object$n-length(object$lmnull$coefficients)
inclprobMr<- colMeans(object$modelslogBF[isMr,1:object$p])
postprobdimMr<- table(kgamma[isMr])/sum(isMr)
names(postprobdimMr)<- as.numeric(names(postprobdimMr))+length(object$lmnull$coefficients)
qSR<- (object$p-object$n)/(object$n+1)
pS<- qSR/(qSR+object$C)
cat(paste("Estimate of the posterior probability of the\n model space with singular models is:", round(pS,3),"\n"))
postprobdim<- postprobdimMr*(1-pS)
inclprob<- inclprobMr*(1-pS) + 0.5*pS
result<- list()
result$pS<- pS
result$postprobdim<- postprobdim
result$inclprob<- inclprob
return(result)
}
|
lcarsBox <- function(..., title = NULL, subtitle = NULL, corners = c(1, 4),
sides = c(1, 3, 4),
left_inputs = NULL, right_inputs = NULL,
color = "atomic-tangerine", side_color = color,
title_color = color, subtitle_color = color,
title_right = TRUE, subtitle_right = TRUE, clip = TRUE,
width_left = 150, width_right = 150, width = "100%"){
width <- shiny::validateCssUnit(width)
width_left <- as.numeric(width_left)
width_right <- as.numeric(width_right)
wrn <- "Side panel widths must each be <= 150 pixels to ensure proper corner scaling."
if(width_left > 150){
warning(wrn)
width_left <- 150
}
if(width_right > 150){
warning(wrn)
width_right <- 150
}
if(is.null(width)) width <- "100%"
if(is.null(corners)){
corners <- 0
} else {
if(any(!corners %in% 1:4)) stop("`corners` must be values in 1:4 or NULL.")
}
if(is.null(sides)){
sides <- 0
} else {
if(any(!sides %in% 1:4)) stop("`sides` must be values in 1:4 or NULL.")
}
color <- c(rep(color, length = 4), rep(side_color, length = 4))
x <- .lcars_color_check(c(color, title_color[1], subtitle_color[1]))
topclass <- .box_top_class(corners, title, title_right)
botclass <- .box_bot_class(corners, subtitle, subtitle_right)
left_input <- !is.null(left_inputs)
right_input <- !is.null(right_inputs)
centerclass <- .box_center_class(sides, left_input, right_input)
centerstyle <- .box_center_style(centerclass, width_left, width_right)
left_bar <- !is.null(sides) && 4 %in% sides
right_bar <- !is.null(sides) && 2 %in% sides
title_div <- div(class = "lcars-box-title", title,
style = paste0("color:", x[9], ";"))
subtitle_div <- div(class = "lcars-box-subtitle", subtitle,
style = paste0("color:", x[10], ";"))
div(class = "lcars-box",
style = paste0("grid-template-areas: ", topclass, " ", centerclass, " ",
botclass, ";", "width:", width, ";"),
if(grepl("none", topclass)){
if(is.null(title)){
if(1 %in% sides) lcarsHeader(NULL, x[5], x[9])
} else {
lcarsHeader(title, if(1 %in% sides) x[5] else "
title_right = title_right)
}
} else {
div(class = topclass,
style = paste0("--corner-width-left: ", 2 * width_left,
"px; --corner-width-right: ", 2* width_right, "px;"),
.box_tl_div(corners, x[1], width_left),
if(!is.null(title) & !title_right) title_div,
div(class = "lcars-rect-top",
style = paste0("background-color:",
if(1 %in% sides) x[5] else "
if(!is.null(title) & title_right) title_div,
.box_tr_div(corners, x[2], width_right)
)
},
div(class = centerclass,
style = centerstyle,
if(left_bar | left_input){
div(class = "lcars-box-buttons-left",
style = if(left_bar){
"grid-template-rows: auto minmax(60px, 1fr); grid-template-areas: 'lcars-button-col' 'lcars-rect-side';"
} else {
"grid-template-rows: auto; grid-template-areas: 'lcars-button-col';"
},
if(left_input) left_inputs,
if(left_bar) div(class = "lcars-rect-side",
style = paste0("background-color:", x[8], ";"))
)
},
div(class = "lcars-box-main text",
style = if(!clip) "margin: -45px 0 -45px 0;", ...),
if(right_bar | right_input){
div(class = "lcars-box-buttons-right",
style = if(right_bar){
"grid-template-rows: auto minmax(60px, 1fr); grid-template-areas: 'lcars-button-col' 'lcars-rect-side';"
} else {
"grid-template-rows: auto; grid-template-areas: 'lcars-button-col';"
},
if(right_input) right_inputs,
if(right_bar) div(class = "lcars-rect-side",
style = paste0("background-color:", x[6], ";"))
)
}
),
if(grepl("none", botclass)){
if(is.null(subtitle)){
if(3 %in% sides) lcarsHeader(NULL, x[7], x[10])
} else {
lcarsHeader(subtitle, if(3 %in% sides) x[7] else "
title_right = subtitle_right)
}
} else {
div(class = botclass,
style = paste0("--corner-width-left: ", 2 * width_left,
"px; --corner-width-right: ", 2* width_right, "px;"),
.box_bl_div(corners, x[4], width_left),
if(!is.null(subtitle) & !subtitle_right) subtitle_div,
div(class = "lcars-rect-bot",
style = paste0("background-color:",
if(3 %in% sides) x[7] else "
if(!is.null(subtitle) & subtitle_right) subtitle_div,
.box_br_div(corners, x[3], width_right)
)
}
)
}
.box_center_class <- function(sides, left, right){
if((all(c(2, 4) %in% sides)) | (left & right) | (2 %in% sides & left) | (4 %in% sides & right)){
x <- "lcars-box-center"
} else if(4 %in% sides | left){
x <- "lcars-box-centerleft"
} else if(2 %in% sides | right){
x <- "lcars-box-centerright"
} else {
x <- "lcars-box-centernone"
}
x
}
.box_center_style <- function(x, wl, wr){
if(x == "lcars-box-centernone") return("")
switch(x,
"lcars-box-center" = paste0("grid-template-columns: ", wl, "px auto ", wr, "px;"),
"lcars-box-centerleft" = paste0("grid-template-columns: ", wl, "px auto;"),
"lcars-box-centerright" = paste0("grid-template-columns: auto ", wr, "px;"))
}
.box_top_class <- function(corners, title, right){
if(all(1:2 %in% corners)){
x <- "lcars-box-top"
} else if(1 %in% corners){
x <- "lcars-box-topleft"
} else if(2 %in% corners){
x <- "lcars-box-topright"
} else {
x <- "lcars-box-topnone"
}
if(is.null(title)){
x <- paste0(x, 2)
} else if(!right){
x <- paste0(x, "-ljust")
}
x
}
.box_tl_div <- function(corners, color, w){
w <- 2 * w
r <- 300 / w
if(1 %in% corners){
div(class = "lcars-box-top-elbow-left",
shiny::HTML(paste0('<svg style = "fill:', color, ';height:90px;width:', w, 'px;">
<use xlink:href="svg/sprites.svg
</svg>'))
)
} else {
div(class = "lcars-box-top-pill-left",
shiny::HTML('<svg style = "fill:', color, ';height:30px;width:45px;">
<use xlink:href="svg/sprites.svg
</svg>')
)
}
}
.box_tr_div <- function(corners, color, w){
w <- 2 * w
r <- 300 / w
if(2 %in% corners){
div(class = "lcars-box-top-elbow-right",
shiny::HTML(paste0('<svg style = "fill:', color, ';height:90px;width:', w, 'px;">
<use xlink:href="svg/sprites.svg
</svg>'))
)
} else {
div(class = "lcars-box-top-pill-right",
shiny::HTML('<svg style = "fill:', color, ';height:30px;width:45px;">
<use xlink:href="svg/sprites.svg
</svg>')
)
}
}
.box_bot_class <- function(corners, title, right){
if(all(3:4 %in% corners)){
x <- "lcars-box-bot"
} else if(4 %in% corners){
x <- "lcars-box-botleft"
} else if(3 %in% corners){
x <- "lcars-box-botright"
} else {
x <- "lcars-box-botnone"
}
if(!is.null(title)){
x <- paste0(x, 2)
if(!right) x <- paste0(x, "-ljust")
}
x
}
.box_bl_div <- function(corners, color, w){
w <- 2 * w
r <- 300 / w
if(4 %in% corners){
div(class = "lcars-box-bot-elbow-left",
shiny::HTML(paste0('<svg style = "fill:', color, ';height:90px;width:', w, 'px;">
<use xlink:href="svg/sprites.svg
'" transform="translate(0 ', -(r - 1) * 45, ') scale(1, ', r, ')"></use>
</svg>'))
)
} else {
div(class = "lcars-box-bot-pill-left",
shiny::HTML('<svg style = "fill:', color, ';height:30px;width:45px;">
<use xlink:href="svg/sprites.svg
</svg>')
)
}
}
.box_br_div <- function(corners, color, w){
w <- 2 * w
r <- 300 / w
if(3 %in% corners){
div(class = "lcars-box-bot-elbow-right",
shiny::HTML(paste0('<svg style = "fill:', color, ';height:90px;width:', w, 'px;">
<use xlink:href="svg/sprites.svg
'" transform="rotate(180, 150, 45) translate(', 300 - w, ' ', -(r - 1) * 45, ') scale(1, ', r, ')"></use>
</svg>'))
)
} else {
div(class = "lcars-box-bot-pill-right",
shiny::HTML('<svg style = "fill:', color, ';height:30px;width:45px;">
<use xlink:href="svg/sprites.svg
</svg>')
)
}
}
|
SL.loess <- function(Y, X, newX, family, obsWeights, span = 0.75, l.family = "gaussian", ...) {
if(family$family == "gaussian") {
fit.loess <- loess(as.formula(paste("Y~", names(X))), data = X, family = l.family, span = span, control = loess.control(surface = "direct"), weights = obsWeights)
}
if(family$family == "binomial") {
stop('family = binomial() not currently implemented for SL.loess')
}
pred <- predict(fit.loess, newdata = newX)
fit <- list(object = fit.loess)
out <- list(pred = pred,fit = fit)
class(out$fit) <- c("SL.loess")
return(out)
}
predict.SL.loess <- function(object, newdata, ...) {
pred <- predict(object = object$object, newdata = newdata)
return(pred)
}
|
context("explore")
set.seed(400)
m <- machine_learn(pima_diabetes[1:200, ], patient_id, outcome = diabetes,
tune = FALSE, n_folds = 2)
multi <- machine_learn(na.omit(pima_diabetes[1:200, ]), patient_id, outcome = weight_class,
tune = FALSE, models = "glm")
variabs <-
attr(m, "recipe")$var_info %>%
dplyr::filter(role == "predictor") %>%
split(., .$type) %>%
purrr::map(dplyr::pull, variable)
sm <- explore(m)
plot_sm <- plot(sm, print = FALSE)
test_that("test_presence", {
expect_error(test_presence(c("weight_class", "insulin", "age"), variabs), NA)
against <- list(a = c("one", "thing", "or"), b = "another")
expect_error(test_presence(c("one", "another"), against), NA)
expect_error(test_presence("one", against), NA)
expect_error(test_presence("another", against), NA)
expect_error(test_presence(c("one", "thing"), against), NA)
expect_error(test_presence("a", against), "aren't predictors")
})
test_that("choose_variables default", {
cv <- list(
c1 = choose_variables(m, vary = 1, variables = variabs),
c5 = choose_variables(m, vary = 5, variables = variabs),
c99 = choose_variables(m, vary = 99, variables = variabs)
)
purrr::map_lgl(cv, ~ all(.x %in% names(pima_diabetes))) %>%
all() %>%
expect_true()
expect_length(cv$c1, 1)
expect_length(cv$c5, 5)
expect_length(cv$c99, length(unlist(variabs)))
})
test_that("choose_variables glm", {
expect_warning(g3 <- choose_variables(m["glmnet"], 3, variabs), "glm")
expect_length(g3, 3)
expect_true(all(g3 %in% names(pima_diabetes)))
expect_warning({
pima_diabetes[1:200, ] %>%
prep_data(patient_id, outcome = diabetes, scale = TRUE) %>%
flash_models(diabetes, models = "glm", n_folds = 2) %>%
explore()
},
NA)
})
test_that("choose_values nums only", {
cv <- choose_values(m, vary = c("skinfold", "age"), variables = variabs,
numerics = 5, characters = Inf,
training_data = pima_diabetes[1:50, ])
expect_setequal(names(cv), c("skinfold", "age"))
expect_equal(names(cv[[1]]), names(cv[[2]]))
expect_true(all(stringr::str_sub(names(cv[[1]]), -1, -1) == "%"))
})
test_that("choose_values noms only", {
cv <- choose_values(m, vary = "weight_class", variables = variabs, numerics = 5,
characters = Inf, training_data = pima_diabetes[1:50, ])
expect_equal(names(cv), "weight_class")
expect_setequal(cv$weight_class, unique(pima_diabetes$weight_class[1:50]))
})
test_that("choose_values both", {
cv <- choose_values(m, vary = c("weight_class", "age"), variables = variabs,
numerics = 5, characters = Inf,
training_data = pima_diabetes[1:50, ])
expect_setequal(names(cv), c("weight_class", "age"))
expect_true(is.numeric(cv$age))
expect_true(is.character(cv$weight_class))
})
test_that("choose_values limit characters", {
cv <- choose_values(m, vary = c("weight_class", "age"), variables = variabs, numerics = 5,
characters = 3, training_data = pima_diabetes[1:50, ])
pima_diabetes %>%
dplyr::count(weight_class) %>%
dplyr::top_n(3, n) %>%
pull(weight_class) %>%
expect_setequal(cv$weight_class, .)
})
test_that("choose_values numerics is integer", {
cv <- choose_values(m, vary = c("weight_class", "age"), variables = variabs,
numerics = 3, characters = Inf, training_data = pima_diabetes[1:50, ])
expect_setequal(names(cv), c("weight_class", "age"))
expect_length(cv$age, 3)
expect_setequal(names(cv$age), c("5%", "50%", "95%"))
})
test_that("choose_values numerics is quantiles", {
cv <- choose_values(m, vary = "plasma_glucose", variables = variabs,
numerics = c(.33, .67), characters = Inf,
training_data = pima_diabetes[1:50, ])
expect_equal(names(cv), "plasma_glucose")
expect_length(cv$plasma_glucose, 2)
expect_setequal(names(cv$plasma_glucose), c("33%", "67%"))
})
test_that("choose_static_values nums only", {
sv <- choose_static_values(m,
static_variables = list(nominal = character(), numeric = c("insulin", "age")),
hold = list(numerics = median, characters = Mode),
training_data = pima_diabetes[1:50, ])
expect_true(is.list(sv))
expect_setequal(names(sv), c("insulin", "age"))
purrr::walk(sv, expect_length, 1)
})
test_that("choose_static_values noms only", {
sv <- choose_static_values(m,
static_variables = list(nominal = "weight_class", numeric = character()),
hold = list(numerics = median, characters = Mode),
training_data = pima_diabetes[1:50, ])
expect_true(is.list(sv))
expect_setequal(names(sv), "weight_class")
purrr::walk(sv, expect_length, 1)
})
test_that("choose_static_values both", {
sv <- choose_static_values(m,
static_variables = list(nominal = "weight_class", numeric = c("insulin", "age")),
hold = list(numerics = median, characters = Mode),
training_data = pima_diabetes[1:50, ])
expect_true(is.list(sv))
expect_setequal(names(sv), c("insulin", "age", "weight_class"))
purrr::walk(sv, expect_length, 1)
})
test_that("choose_static_values hold from training data", {
sv <- choose_static_values(m,
static_variables = list(nominal = "weight_class", numeric = c("insulin", "age")),
hold = pima_diabetes[3, ],
training_data = pima_diabetes[1:50, ])
expect_true(is.list(sv))
expect_setequal(names(sv), c("insulin", "age", "weight_class"))
purrr::walk(sv, expect_length, 1)
})
test_that("choose_static_values hold is custom values", {
sv <- choose_static_values(m,
static_variables = list(nominal = "weight_class", numeric = c("insulin", "age")),
hold = list(pregnancies = 0, plasma_glucose = 99, weight_class = "obese",
insulin = 3, age = 32),
training_data = pima_diabetes[1:50, ])
expect_true(is.list(sv))
expect_setequal(names(sv), c("insulin", "age", "weight_class"))
purrr::walk(sv, expect_length, 1)
})
test_that("explore returns a tibble with custom class", {
expect_s3_class(sm, "tbl_df")
expect_s3_class(sm, "explore_df")
})
test_that("explore can use any algorithm", {
suppressWarnings({
purrr::map_lgl(seq_along(m), ~ is.tbl(explore(m[.x]))) %>%
all() %>%
expect_true()
})
})
test_that("vary varies the correct number of variables", {
explore(m, vary = 1) %>%
dplyr::select(-predicted_diabetes) %>%
purrr::map_lgl(~ dplyr::n_distinct(.x) > 1) %>%
sum() %>%
expect_equal(1)
explore(m, vary = 5) %>%
dplyr::select(-predicted_diabetes) %>%
purrr::map_lgl(~ dplyr::n_distinct(.x) > 1) %>%
sum() %>%
expect_equal(5)
})
test_that("list of values to vary works right", {
values_to_use <- list(
plasma_glucose = c(50, 100, 150),
weight_class = c("underweight", "normal", NA)
)
preds <- explore(m, vary = values_to_use)
expect_s3_class(preds, "explore_df")
expect_setequal(preds$plasma_glucose, values_to_use$plasma_glucose)
expect_setequal(preds$weight_class, values_to_use$weight_class)
})
test_that("explore hold custom functions (mean instead of median for numerics)", {
sm_def <- explore(m, vary = c("weight_class", "skinfold"))
sm2 <- explore(m, vary = c("weight_class", "skinfold"),
hold = list(numerics = mean, characters = Mode))
same <- purrr::map2(sm_def, sm2, ~ isTRUE(all.equal(.x, .y)))
expect_true(same$weight_class)
expect_false(same$plasma_glucose)
expect_false(same$predicted_diabetes)
})
test_that("explore hold row from test data", {
p51 <- explore(m, hold = pima_diabetes[51, ], vary = c("weight_class"))
varying <- purrr::map_lgl(p51, ~ dplyr::n_distinct(.x) > 1)
expect_setequal(names(varying)[varying], c("predicted_diabetes", "weight_class"))
actual <- p51[, !varying] %>%
dplyr::distinct() %>%
as.numeric()
expected <- as.numeric(pima_diabetes[51, which(names(pima_diabetes) %in% names(varying)[!varying])])
expect_equal(actual, expected)
})
test_that("explore hold custom list", {
ch <- explore(m,
vary = dplyr::setdiff(names(pima_diabetes), c("patient_id", "diabetes", "age", "skinfold")),
hold = list(age = 21, skinfold = 18))
varying <- purrr::map_lgl(ch, ~ dplyr::n_distinct(.x) > 1)
expect_setequal(names(varying)[!varying], c("age", "skinfold"))
expect_equal(unique(ch$age), 21)
expect_equal(unique(ch$skinfold), 18)
})
test_that("explore returns right number of character values", {
expect_equal(dplyr::n_distinct(explore(m, vary = "weight_class", characters = 2)$weight_class), 2)
expect_equal(dplyr::n_distinct(explore(m, characters = 4)$weight_class), 4)
expect_equal(dplyr::n_distinct(sm$weight_class), dplyr::n_distinct(pima_diabetes$weight_class[1:50]))
})
test_that("explore returns the right number of numeric values", {
expect_equal(dplyr::n_distinct(explore(m, vary = "plasma_glucose", numerics = 2)$plasma_glucose), 2)
expect_equal(dplyr::n_distinct(explore(m, numerics = 9)$plasma_glucose), 9)
expect_equal(dplyr::n_distinct(explore(m, numerics = c(.1, .3, .8))$plasma_glucose), 3)
})
test_that("explore errors as expected", {
expect_error(explore(pima_diabetes), "model_list")
expect_error(explore(structure(m, recipe = NULL)), "prep_data")
expect_error(explore(m, vary = c("age", "not_a_var")), "not_a_var")
expect_error(explore(m, hold = list(numerics = mean)), "hold")
expect_error(explore(m, hold = list(characters = Mode)), "hold")
expect_error(explore(m, hold = list(characters = letters)), "hold")
expect_error(explore(m, hold = list(numerics = mean, characters = Mode)), NA)
expect_error(explore(m, hold = list(median, Mode)), "named")
expect_error(explore(m, hold = list(age = 50)), "hold")
})
test_that("printing a explored df doesn't print training performance info", {
sim_print <- capture_output(sim_mess <- capture_messages(print(sm)))
sim_output <- paste(sim_print, sim_mess)
expect_false(stringr::str_detect(sim_print, "Performance"))
})
test_that("plot.explore_df is registered", {
stringr::str_detect(methods("plot"), "explore_df") %>%
any() %>%
expect_true()
})
test_that("plot.explore_df returns a ggplot", {
expect_s3_class(plot_sm, "gg")
})
test_that("plot.cf args work", {
default_plot <- plot(sm, print = FALSE, jitter_y = FALSE)
suppressWarnings({
expect_false(isTRUE(all.equal(
plot(sm, print = FALSE, jitter_y = FALSE, n_use = 2),
plot(sm, print = FALSE, jitter_y = FALSE, n_use = 2, aggregate_fun = mean))))
})
expect_message(plot(sm, print = FALSE, n_use = 2), "aggregate")
altered_plots <- list(
plot(sm, print = FALSE, jitter_y = FALSE, reorder_categories = FALSE),
plot(sm, print = FALSE, jitter_y = TRUE),
plot(sm, print = FALSE, jitter_y = FALSE, x_var = weight_class),
plot(sm, print = FALSE, jitter_y = FALSE, color_var = weight_class),
plot(sm, print = FALSE, jitter_y = FALSE, font_size = 8),
plot(sm, print = FALSE, jitter_y = FALSE, strip_font_size = .5),
plot(sm, print = FALSE, jitter_y = FALSE, line_width = 1),
plot(sm, print = FALSE, jitter_y = FALSE, line_alpha = .5),
plot(sm, print = FALSE, jitter_y = FALSE, rotate_x = TRUE)
)
purrr::map_lgl(altered_plots, ~ isTRUE(all.equal(.x, default_plot))) %>%
any() %>%
expect_false()
use2 <- plot(sm, print = FALSE, jitter_y = FALSE, n_use = 2)
expect_equal(nrow(ggplot2::ggplot_build(use2)$layout$layout), 1)
use1 <- plot(sm, print = FALSE, jitter_y = FALSE, n_use = 1)
expect_false(isTRUE(all.equal(use1, use2)))
use3 <- plot(sm, print = FALSE, jitter_y = FALSE, n_use = 3)
expect_false(isTRUE(all.equal(use3, use2)))
})
vars <- tibble::tibble(variable = letters[1:4],
numeric = c(FALSE, TRUE, TRUE, FALSE),
nlev = 5)
test_that("map_variables without mappings specified", {
map_variables(vars, x_var = rlang::quo(), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal(c("color", "x", "facet", "facet"))
vars[c(2, 1, 3, 4), ] %>%
map_variables(x_var = rlang::quo(), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal(c("x", "color", "facet", "facet"))
map_variables(vars[1, ], x_var = rlang::quo(), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal("x")
map_variables(vars[2, ], x_var = rlang::quo(), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal("x")
vars %>%
dplyr::filter(numeric) %>%
map_variables(x_var = rlang::quo(), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal(c("x", "color"))
vars %>%
dplyr::filter(!numeric) %>%
map_variables(x_var = rlang::quo(), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal(c("x", "color"))
})
test_that("map_variables with mappings specified", {
vars %>%
map_variables(x_var = rlang::quo(a), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal(c("x", "color", "facet", "facet"))
vars %>%
map_variables(x_var = rlang::quo(d), color_var = rlang::quo()) %>%
dplyr::pull(map_to) %>%
expect_equal(c("color", "facet", "facet", "x"))
vars %>%
map_variables(x_var = rlang::quo(), color_var = rlang::quo(b)) %>%
dplyr::pull(map_to) %>%
expect_equal(c("facet", "color", "x", "facet"))
vars %>%
map_variables(x_var = rlang::quo(d), color_var = rlang::quo(b)) %>%
dplyr::pull(map_to) %>%
expect_equal(c("facet", "color", "facet", "x"))
vars %>%
dplyr::filter(!numeric) %>%
map_variables(x_var = rlang::quo(), color_var = rlang::quo(a)) %>%
dplyr::pull(map_to) %>%
expect_equal(c("color", "x"))
expect_error(map_variables(vars[1, ], color_var = rlang::quo(a)), "color")
})
test_that("map_variables errors informatively", {
expect_error(map_variables(vars, rlang::quo("something else"), rlang::quo()), "x_var")
expect_error(map_variables(vars, rlang::quo(), rlang::quo("something else")), "color_var")
})
test_that("n_use > 4 errors informatively", {
expect_error(plot(sm, print = FALSE, n_use = 5), "n_use")
})
test_that("explore can handle once-logical features", {
n <- 20
d <- tibble::tibble(x = sample(c(FALSE, TRUE), n, TRUE),
other = rnorm(n),
another = sample(c("dog", "cat"), n, TRUE),
y = sample(c("Y", "N"), n, TRUE))
m <- machine_learn(d, outcome = y, tune = FALSE, models = "xgb", n_folds = 2)
expect_error(expl <- explore(m), NA)
expect_s3_class(expl, "explore_df")
})
test_that("explore uses scaled features appropriately", {
n <- 100
d <- data.frame(x1 = sort(rnorm(n, 10, 100)),
x2 = sort(rpois(n, 5)),
x3 = runif(n, -10, 10),
x4 = sample(letters, n, TRUE),
y = sort(rnorm(n)))
pd <- prep_data(d, outcome = y, center = TRUE, scale = TRUE)
m <- flash_models(pd, outcome = y, models = "xgb", n_folds = 3)
var1 <-
explore(m) %>%
dplyr::pull(predicted_y) %>%
stats::var()
pd2 <- prep_data(d, outcome = y)
m2 <- flash_models(pd2, outcome = y, models = "xgb", n_folds = 3)
var2 <-
explore(m2) %>%
dplyr::pull(predicted_y) %>%
stats::var()
expect_equal(var1, var2, tolerance = min(var1, var2))
})
test_that("multiclass errors", {
expect_error(explore(multi), "multiclass")
})
test_that("test removed data throws error", {
save_models(m)
reloaded_m <- load_models("models.RDS")
expect_error(explore(reloaded_m), "Explore requires that data is ")
file.remove("models.RDS")
})
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(MixMatrix)
library(MixMatrix)
set.seed(20180221)
A <- rmatrixt(30,mean=matrix(0,nrow=3,ncol=4), df = 10)
B <- rmatrixt(30,mean=matrix(1,nrow=3,ncol=4), df = 10)
C <- array(c(A,B), dim=c(3,4,60))
prior <- c(.5,.5)
init = list(centers = array(c(rep(0,12),rep(1,12)), dim = c(3,4,2)),
U = array(c(diag(3), diag(3)), dim = c(3,3,2)),
V = array(c(diag(4), diag(4)), dim = c(4,4,2))
)
res<-matrixmixture(C, init = init, prior = prior, nu = 10,
model = "t", tolerance = 1e-2)
print(res$centers)
print(res$pi)
logLik(res)
AIC(logLik(res))
plot(res)
init_matrixmixture(C, prior = c(.5,.5), centermethod = 'kmeans')
init_matrixmixture(C, K = 2, centermethod = 'random')
sessionInfo()
labs = knitr::all_labels()
labs = labs[!labs %in% c("setup", "toc", "getlabels", "allcode")]
|
AdaBoost_I <- function(train, test, pruned=TRUE, confidence=0.25, instancesPerLeaf=2, numClassifiers=10, algorithm="ADABOOST.NC", trainMethod="NORESAMPLING", seed=-1){
alg <- RKEEL::R6_AdaBoost_I$new()
alg$setParameters(train, test, pruned, confidence, instancesPerLeaf, numClassifiers, algorithm, trainMethod, seed)
return (alg)
}
R6_AdaBoost_I <- R6::R6Class("R6_AdaBoost_I",
inherit = ClassificationAlgorithm,
public = list(
pruned = TRUE,
confidence = 0.25,
instancesPerLeaf = 2,
numClassifiers = 10,
algorithm = "ADABOOST.NC",
trainMethod = "NORESAMPLING",
seed = -1,
setParameters = function(train, test, pruned=TRUE, confidence=0.25,
instancesPerLeaf=2, numClassifiers=10,
algorithm="ADABOOST", trainMethod="NORESAMPLING",
seed=-1){
super$setParameters(train, test)
self$pruned <- pruned
self$confidence <- confidence
self$instancesPerLeaf <- 2
self$numClassifiers <- numClassifiers
if((tolower(algorithm) == "adaboost")){
self$algorithm <- algorithm
}
else{
self$algorithm <- "ADABOOST"
}
if((tolower(trainMethod) == "noresampling") || (tolower(trainMethod) == "resampling")){
self$trainMethod <- toupper(trainMethod)
}
else{
self$trainMethod <- "NORESAMPLING"
}
if(seed == -1) {
self$seed <- sample(1:1000000, 1)
}
else {
self$seed <- seed
}
}
),
private = list(
jarName = "Ensembles-I.jar",
algorithmName = "AdaBoost-I",
algorithmString = "AdaBoost algorithm",
getParametersText = function(){
text <- ""
text <- paste0(text, "seed = ", self$seed, "\n")
text <- paste0(text, "pruned = ", self$pruned, "\n")
text <- paste0(text, "confidence = ", self$confidence, "\n")
text <- paste0(text, "isntancesPerLeaf = ", self$instancesPerLeaf, "\n")
text <- paste0(text, "Number of Classifiers = ", self$numClassifiers, "\n")
text <- paste0(text, "Algorithm = ", self$algorithm, "\n")
text <- paste0(text, "Train Method = ", self$trainMethod, "\n")
return(text)
}
)
)
|
context("cleanup testthat reporter")
test_that("unit: test, mode: cleanup-fail", {
out <- list()
on.exit(if (!is.null(out$p)) out$p$kill(), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(proc_unit = "test"), {
test_that("foobar", {
out$p <<- processx::process$new(px(), c("sleep", "5"))
out$running <<- out$p$is_alive()
})
}
),
"did not clean up processes"
)
expect_true(out$running)
deadline <- Sys.time() + 2
while (out$p$is_alive() && Sys.time() < deadline) Sys.sleep(0.05)
expect_true(Sys.time() < deadline)
expect_false(out$p$is_alive())
})
test_that("unit: test, multiple processes", {
out <- list()
on.exit(if (!is.null(out$p1)) out$p1$kill(), add = TRUE)
on.exit(if (!is.null(out$p2)) out$p2$kill(), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(proc_unit = "test"), {
test_that("foobar", {
out$p1 <<- processx::process$new(px(), c("sleep", "5"))
out$p2 <<- processx::process$new(px(), c("sleep", "5"))
out$running <<- out$p1$is_alive() && out$p2$is_alive()
})
}
),
"px.*px"
)
expect_true(out$running)
expect_false(out$p1$is_alive())
expect_false(out$p2$is_alive())
})
test_that("on.exit() works", {
out <- list()
on.exit(if (!is.null(out$p)) out$p$kill(), add = TRUE)
expect_success(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(proc_unit = "test"), {
test_that("foobar", {
out$p <<- processx::process$new(px(), c("sleep", "5"))
on.exit(out$p$kill(), add = TRUE)
out$running <<- out$p$is_alive()
})
}
)
)
expect_true(out$running)
expect_false(out$p$is_alive())
})
test_that("only report", {
out <- list()
on.exit(if (!is.null(out$p)) out$p$kill(), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_unit = "test", proc_cleanup = FALSE, proc_fail = TRUE), {
test_that("foobar", {
out$p <<- processx::process$new(px(), c("sleep", "5"))
out$running <<- out$p$is_alive()
})
}
),
"did not clean up processes"
)
expect_true(out$running)
expect_true(out$p$is_alive())
out$p$kill()
})
test_that("only kill", {
out <- list()
on.exit(if (!is.null(out$p)) out$p$kill(), add = TRUE)
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_unit = "test", proc_cleanup = TRUE, proc_fail = FALSE,
conn_fail = FALSE), {
test_that("foobar", {
out$p <<- processx::process$new(px(), c("sleep", "5"))
out$running <<- out$p$is_alive()
})
test_that("foobar2", {
deadline <- Sys.time() + 3
while (out$p$is_alive() && Sys.time() < deadline) Sys.sleep(0.05)
out$running2 <<- out$p$is_alive()
})
}
)
expect_true(out$running)
expect_false(out$running2)
expect_false(out$p$is_alive())
})
test_that("unit: testsuite", {
out <- list()
on.exit(if (!is.null(out$p)) out$p$kill(), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_unit = "testsuite", rconn_fail = FALSE, file_fail = FALSE,
conn_fail = FALSE), {
test_that("foobar", {
out$p <<- processx::process$new(px(), c("sleep", "5"))
out$running <<- out$p$is_alive()
})
test_that("foobar2", {
out$running2 <<- out$p$is_alive()
})
}
),
"did not clean up processes"
)
expect_true(out$running)
expect_true(out$running2)
deadline <- Sys.time() + 3
while (out$p$is_alive() && Sys.time() < deadline) Sys.sleep(0.05)
expect_false(out$p$is_alive())
})
test_that("R connection cleanup, test, close, fail", {
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(proc_fail = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
})
}
),
"did not close R connections"
)
expect_true(out$open)
expect_error(isOpen(out$conn))
})
test_that("R connection cleanup, test, do not close, fail", {
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_fail = FALSE, rconn_cleanup = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
})
}
),
"did not close R connections"
)
expect_true(out$open)
expect_true(isOpen(out$conn))
expect_silent(close(out$conn))
})
test_that("R connection cleanup, test, close, do not fail", {
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_fail = FALSE, rconn_fail = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
})
}
)
expect_true(out$open)
expect_error(isOpen(out$conn))
})
test_that("R connections, unit: testsuite", {
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
rconn_unit = "testsuite", proc_fail = FALSE, file_fail = FALSE,
conn_fail = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
})
test_that("foobar2", {
out$open2 <<- isOpen(out$conn)
})
}
),
"did not close R connections"
)
expect_true(out$open)
expect_true(out$open2)
expect_error(isOpen(out$conn))
})
test_that("connections already open are ignored", {
tmp2 <- tempfile()
on.exit(unlink(tmp2), add = TRUE)
conn <- file(tmp2, open = "w")
on.exit(try(close(conn), silent = TRUE), add = TRUE)
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_success(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(proc_fail = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
close(out$conn)
})
}
)
)
expect_error(isOpen(out$conn))
expect_true(isOpen(conn))
expect_silent(close(conn))
})
test_that("File cleanup, test, fail", {
out <- list()
tmp <- tempfile()
cat("data\ndata2\n", file = tmp)
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_fail = FALSE, rconn_cleanup = FALSE, rconn_fail = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "r")
out$open <<- isOpen(out$conn)
})
}
),
"did not close open files"
)
expect_true(out$open)
expect_true(isOpen(out$conn))
close(out$conn)
})
test_that("File cleanup, unit: testsuite", {
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
file_unit = "testsuite", proc_fail = FALSE, rconn_fail = FALSE,
rconn_cleanup = FALSE, conn_fail = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
})
test_that("foobar2", {
out$open2 <<- isOpen(out$conn)
})
}
),
"did not close open files"
)
expect_true(out$open)
expect_true(out$open2)
expect_true(isOpen(out$conn))
close(out$conn)
})
test_that("files already open are ignored", {
tmp2 <- tempfile()
on.exit(unlink(tmp2), add = TRUE)
conn <- file(tmp2, open = "w")
on.exit(try(close(conn), silent = TRUE), add = TRUE)
out <- list()
tmp <- tempfile()
on.exit(unlink(tmp), add = TRUE)
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_success(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_fail = FALSE, rconn_fail = FALSE, rconn_cleanup = FALSE), {
test_that("foobar", {
out$conn <<- file(tmp, open = "w")
out$open <<- isOpen(out$conn)
close(out$conn)
})
}
)
)
expect_error(isOpen(out$conn))
expect_true(isOpen(conn))
expect_silent(close(conn))
})
offline <- is_offline()
if (!offline) {
conn <- curl::curl(httpbin_url(), open = "r")
close(conn)
}
test_that("Network cleanup, test, fail", {
if (offline) skip("Offline")
out <- list()
on.exit({ try(close(out$conn), silent = TRUE); gc() }, add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_fail = FALSE, rconn_cleanup = FALSE, rconn_fail = FALSE,
file_fail = FALSE), {
test_that("foobar", {
out$conn <<- curl::curl(httpbin_url(), open = "r")
out$open <<- isOpen(out$conn)
})
}
),
"did not close network"
)
expect_true(out$open)
expect_true(isOpen(out$conn))
close(out$conn)
})
test_that("Network cleanup, unit: testsuite", {
if (offline) skip("Offline")
out <- list()
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_failure(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
conn_unit = "testsuite", proc_fail = FALSE, rconn_fail = FALSE,
rconn_cleanup = FALSE, file_fail = FALSE), {
test_that("foobar", {
out$conn <<- curl::curl(httpbin_url(), open = "r")
out$open <<- isOpen(out$conn)
})
test_that("foobar2", {
out$open2 <<- isOpen(out$conn)
})
}
),
"did not close network connections"
)
expect_true(out$open)
expect_true(out$open2)
expect_true(isOpen(out$conn))
close(out$conn)
})
test_that("Network connections already open are ignored", {
if (offline) skip("Offline")
conn <- curl::curl(httpbin_url(), open = "r")
on.exit(try(close(conn), silent = TRUE), add = TRUE)
out <- list()
on.exit(try(close(out$conn), silent = TRUE), add = TRUE)
expect_success(
with_reporter(
CleanupReporter(testthat::SilentReporter)$new(
proc_fail = FALSE, rconn_fail = FALSE, rconn_cleanup = FALSE), {
test_that("foobar", {
out$conn <<- curl::curl(httpbin_url(), open = "r")
out$open <<- isOpen(out$conn)
close(out$conn)
})
}
)
)
expect_error(isOpen(out$conn))
expect_true(isOpen(conn))
expect_silent(close(conn))
})
|
strip_punc <- function(wpe) {
for(i in 1:length(wpe)){
if(!(tolower(wpe[i]) %in% vaderLexicon$V1)) {
leadingAndTrailing <- "(^\\W+)|(\\W+$)"
wpe[i] <- gsub(leadingAndTrailing, "", wpe[i])
}
}
return(wpe)
}
wordsPlusEmo <- function(text) {
wpe <- unlist(strsplit(text, "\\s+"))
stripped <- strip_punc(wpe)
return(stripped)
}
|
countRules <- function(x)
{
x <- strsplit(x, "\n")[[1]]
comNum <- ruleNum <- condNum <- rep(NA, length(x))
comIdx <- rIdx <- 0
for(i in seq(along = x))
{
tt <- parser(x[i])
if(names(tt)[1] == "rules")
{
comIdx <- comIdx + 1
rIdx <- 0
}
comNum[i] <-comIdx
if(names(tt)[1] == "conds")
{
rIdx <- rIdx + 1
cIdx <- 0
}
ruleNum[i] <-rIdx
if(names(tt)[1] == "type")
{
cIdx <- cIdx + 1
condNum[i] <- cIdx
}
}
numCom <- sum(grepl("^rules=", x))
rulesPerCom <- unlist(lapply(split(ruleNum, as.factor(comNum)), max))
rulesPerCom <- rulesPerCom[rulesPerCom > 0]
rulesPerCom
}
getSplits <- function(x)
{
x <- strsplit(x, "\n")[[1]]
comNum <- ruleNum <- condNum <- rep(NA, length(x))
comIdx <- rIdx <- 0
for(i in seq(along = x))
{
tt <- parser(x[i])
if(names(tt)[1] == "rules")
{
comIdx <- comIdx + 1
rIdx <- 0
}
comNum[i] <-comIdx
if(names(tt)[1] == "conds")
{
rIdx <- rIdx + 1
cIdx <- 0
}
ruleNum[i] <-rIdx
if(names(tt)[1] == "type")
{
cIdx <- cIdx + 1
condNum[i] <- cIdx
}
}
numCom <- sum(grepl("^rules=", x))
rulesPerCom <- unlist(lapply(split(ruleNum, as.factor(comNum)), max))
rulesPerCom <- rulesPerCom[rulesPerCom > 0]
if (! is.null(rulesPerCom) && numCom > 0)
names(rulesPerCom) <- paste("Com", 1:numCom)
isNewRule <- ifelse(grepl("^conds=", x), TRUE, FALSE)
splitVar <- rep("", length(x))
splitVal <- rep(NA, length(x))
splitCats <- rep("", length(x))
splitDir <- rep("", length(x))
isType2 <- grepl("^type=\"2\"", x)
if(any(isType2))
{
splitVar[isType2] <- type2(x[isType2])$var
splitVar[isType2] <- gsub("\"", "", splitVar[isType2])
splitDir[isType2] <- type2(x[isType2])$rslt
splitVal[isType2] <- type2(x[isType2])$val
}
isType3 <- grepl("^type=\"3\"", x)
if(any(isType3))
{
splitVar[isType3] <- type3(x[isType3])$var
splitCats[isType3] <- type3(x[isType3])$val
splitCats[isType3] <- gsub("[{}]", "", splitCats[isType3])
splitCats[isType3] <- gsub("\"", "", splitCats[isType3])
splitCats[isType3] <- gsub(" ", "", splitCats[isType3])
}
if(!any(isType2) & !any(isType3)) return(NULL)
splitData <- data.frame(committee = comNum,
rule = ruleNum,
variable = splitVar,
dir = splitDir,
value = as.numeric(splitVal),
category = splitCats)
splitData$type <- ""
if(any(isType2)) splitData$type[isType2] <- "type2"
if(any(isType3)) splitData$type[isType3] <- "type3"
splitData <- splitData[splitData$variable != "" ,]
splitData
}
printCubistRules <- function(x, dig = max(3, getOption("digits") - 5))
{
comNum <- ruleNum <- condNum <- rep(NA, length(x))
comIdx <- rIdx <- 0
for(i in seq(along = x))
{
tt <- parser(x[i])
if(names(tt)[1] == "rules")
{
comIdx <- comIdx + 1
rIdx <- 0
}
comNum[i] <-comIdx
if(names(tt)[1] == "conds")
{
rIdx <- rIdx + 1
cIdx <- 0
}
ruleNum[i] <-rIdx
if(names(tt)[1] == "type")
{
cIdx <- cIdx + 1
condNum[i] <- cIdx
}
}
numCom <- sum(grepl("^rules=", x))
rulesPerCom <- unlist(lapply(split(ruleNum, as.factor(comNum)), max))
rulesPerCom <- rulesPerCom[rulesPerCom > 0]
names(rulesPerCom) <- paste("Com", 1:numCom)
cat("Number of committees:", numCom, "\n")
cat("Number of rules per committees:",
paste(rulesPerCom, collapse = ", "), "\n\n")
isNewRule <- ifelse(grepl("^conds=", x), TRUE, FALSE)
isEqn <- ifelse(grepl("^coeff=", x), TRUE, FALSE)
cond <- rep("", length(x))
isType2 <- grepl("^type=\"2\"", x)
if(any(isType2)) cond[isType2] <- type2(x[isType2], dig = dig)$text
isType3 <- grepl("^type=\"3\"", x)
if(any(isType3)) cond[isType3] <- type3(x[isType3])$text
isEqn <- grepl("^coeff=", x)
eqtn <- rep("", length(x))
eqtn[isEqn] <- eqn(x[isEqn], dig = dig)
tmp <- x[isNewRule]
tmp <- parser(tmp)
ruleN <- rep(NA, length(x))
ruleN[isNewRule] <- as.numeric(unlist(lapply(tmp, function(x) x["cover"])))
for(i in seq(along = x))
{
if(isNewRule[i])
{
cat("Rule ", comNum[i], "/", ruleNum[i], ": (n=",
ruleN[i], ")\n", sep = "")
cat(" If\n")
} else {
if(cond[i] != "")
{
cat(" |", cond[i], "\n")
if(cond[i+1] == "")
{
cat(" Then\n")
cat(" prediction =", eqtn[i+1], "\n\n")
}
}
}
}
}
type3 <- function(x)
{
aInd <- regexpr("att=", x)
eInd <- regexpr("elts=", x)
var <- substring(x, aInd + 4, eInd - 2)
val <- substring(x, eInd + 5)
multVals <- grepl(",", val)
val <- gsub(",", ", ", val)
val <- ifelse(multVals, paste("{", val, "}", sep = ""), val)
txt <- ifelse(multVals, paste(var, "in", val), paste(var, "=", val))
list(var = var, val = val, text = txt)
}
type2 <- function(x, dig = 3)
{
x <- gsub("\"", "", x)
aInd <- regexpr("att=", x)
cInd <- regexpr("cut=", x)
rInd <- regexpr("result=", x)
vInd <- regexpr("val=", x)
var <- val <- rslt <- rep("", length(x))
missingRule <- cInd < 1 & vInd > 0
if(any(missingRule))
{
var[missingRule] <- substring(x[missingRule], aInd[missingRule] + 4, vInd[missingRule] - 2)
val[missingRule] <- "NA"
rslt[missingRule] <- "="
}
if(any(!missingRule))
{
var[!missingRule] <- substring(x[!missingRule], aInd[!missingRule] + 4, cInd[!missingRule] - 2)
val[!missingRule] <- substring(x[!missingRule], cInd[!missingRule] + 4, rInd[!missingRule] - 1)
val[!missingRule] <- format(as.numeric(val[!missingRule]), digits = dig)
rslt[!missingRule] <- substring(x[!missingRule], rInd[!missingRule] + 7)
}
list(var = var, val = as.numeric(val), rslt = rslt,
text = paste(var, rslt, val))
}
eqn <- function(x, dig = 10, text = TRUE, varNames = NULL)
{
x <- gsub("\"", "", x)
out <- vector(mode = "list", length = length(x))
for(j in seq(along = x))
{
starts <- gregexpr("(coeff=)|(att=)", x[j])[[1]]
p <- (length(starts) - 1)/2
vars <- vector(mode = "numeric", length = p + 1)
tmp <- vector(mode = "character", length = length(starts))
for(i in seq(along = starts))
{
if(i < length(starts))
{
txt <- substring(x[j], starts[i], starts[i + 1] - 2)
} else txt <- substring(x[j], starts[i])
tmp[i] <- gsub("(coeff=)|(att=)", "", txt)
}
valSeq <- seq(1, length(tmp), by = 2)
vals <- as.double(tmp[valSeq])
nms <- tmp[-valSeq]
if(text)
{
signs <- sign(vals)
vals <- abs(vals)
for(i in seq(along = vals))
{
if(i == 1)
{
txt <- ifelse(signs[1] == -1,
format(-vals[1], digits = dig),
format(vals[1], digits = dig))
} else {
tmp2 <- ifelse(signs[i] == -1,
paste("-", format(vals[i], digits = dig)),
paste("+", format(vals[i], digits = dig)))
txt <- paste(txt, tmp2, nms[i-1])
}
}
out[j] <- txt
} else {
nms <- c("(Intercept)", nms)
names(vals) <- nms
if(!is.null(varNames))
{
vars2 <- varNames[!(varNames %in% nms)]
vals2 <- rep(NA, length(vars2))
names(vals2) <- vars2
vals <- c(vals, vals2)
newNames <- c("(Intercept)", varNames)
vals <- vals[newNames]
}
out[[j]] <- vals
}
}
out
}
parser <- function(x)
{
x <- strsplit(x, " ")
x <- lapply(x,
function(y)
{
y <- strsplit(y, "=")
nms <- unlist(lapply(y, function(z) z[1]))
val <- unlist(lapply(y, function(z) z[2]))
names(val) <- nms
val
})
if(length(x) == 1) x <- x[[1]]
x
}
coef.cubist <- function(object, varNames = NULL, ...) {
x <- object$model
x <- strsplit(x, "\n")[[1]]
comNum <- ruleNum <- condNum <- rep(NA, length(x))
comIdx <- rIdx <- 0
for (i in seq(along = x)) {
tt <- parser(x[i])
if (names(tt)[1] == "rules") {
comIdx <- comIdx + 1
rIdx <- 0
}
comNum[i] <- comIdx
if (names(tt)[1] == "conds") {
rIdx <- rIdx + 1
cIdx <- 0
}
ruleNum[i] <- rIdx
if (names(tt)[1] == "type") {
cIdx <- cIdx + 1
condNum[i] <- cIdx
}
}
isEqn <- ifelse(grepl("^coeff=", x), TRUE, FALSE)
isEqn <- grepl("^coeff=", x)
coefs <-
eqn(x[isEqn],
dig = 0,
text = FALSE,
varNames = varNames)
p <- length(coefs)
dims <- unlist(lapply(coefs, length))
coefs <- do.call("c", coefs)
coms <- rep(comNum[isEqn], dims)
rls <- rep(ruleNum[isEqn], dims)
out <-
data.frame(
tmp = paste(coms, rls, sep = "."),
value = coefs,
var = names(coefs)
)
out <-
reshape(
out,
direction = "wide",
v.names = "value",
timevar = "var",
idvar = "tmp"
)
colnames(out) <- gsub("value.", "", colnames(out), fixed = TRUE)
tmp <- strsplit(as.character(out$tmp), ".", fixed = TRUE)
out$committee <- unlist(lapply(tmp, function(x) x[1]))
out$rule <- unlist(lapply(tmp, function(x) x[2]))
out$tmp <- NULL
out
}
|
mpower_integrity <- function(effect_size, study_size, k, i2, es_type, test_type, p, con_table){
test_type_options <- c("one-tailed", "two-tailed")
es_type_options <- c("d","r", "or")
if(missing(study_size))
stop("Need to specify expected sample size")
if(!(is.numeric(study_size)))
stop("study_size must be numeric")
if(length(study_size) > 1)
stop("study_size must be a single number")
if(study_size < 1)
stop("study_size must be greater than 0")
if(missing(k))
stop("Need to specify expected number of studies")
if(!(is.numeric(k)))
stop("k must be numeric")
if(length(k) > 1)
stop("k must be a single number")
if(k < 2)
stop("k must be greater than 1")
if(missing(i2))
stop("Need to specify heterogeneity(i2); Small = .25, moderatoe = .50, Large = .75")
if(i2 > .9999)
stop("i2 cannot be greater than 1")
if(i2 < 0)
stop("i2 cannot be less than 0")
if(missing(es_type))
stop("Need to specify effect size as 'd', 'r', or 'or'")
if(!(es_type %in% es_type_options))
stop("Need to specify effect size as 'd', 'r', or 'or'")
if(es_type == 'd'){
if(is.null(effect_size))
stop("Need to specify expected effect size")
if(!(is.numeric(effect_size)))
stop("effect_size must be numeric")
if(length(effect_size) > 1)
stop("effect_size must be a single number")
if(effect_size < 0)
stop("effect_size must be greater than zero")
if(effect_size > 10)
warning("Are you sure effect size is >10?")
}
if(es_type == 'r'){
if(is.null(effect_size))
stop("Need to specify expected effect size")
if(!(is.numeric(effect_size)))
stop("effect_size must be numeric")
if(length(effect_size) > 1)
stop("effect_size must be a single number")
if(effect_size > 1)
stop("Correlation cannot be above 1")
if(effect_size < 0)
stop("Correlation must be above 0")
}
if(es_type == 'or'){
if(!is.null(effect_size))
stop("Do not enter an effect size for Odds Ratio. Instead, Enter a 2x2 contingency table")
if(missing(con_table))
stop("For Odds Ratio, must enter contigency table (con_table)")
if(!missing(con_table)){
if(length(con_table) != 4)
stop("con_table must reflect a 2x2 contingency table with the form c(a,b,c,d). see documentation")
if(study_size != sum(con_table))
stop("Entered sample size should equal the sum of the contigency table")
}
}
if(!(test_type %in% test_type_options))
stop("Need to specify two-tailed or one-tailed")
}
|
test_that("Package readme in root directory can be built ", {
skip_on_cran()
pkg_path <- create_local_package()
expect_error(
build_readme(pkg_path),
"Can't find a 'README.Rmd'"
)
suppressMessages(use_readme_rmd())
suppressMessages(build_readme(pkg_path))
expect_true(file_exists(path(pkg_path, "README.md")))
expect_false(file_exists(path(pkg_path, "README.html")))
})
test_that("Package readme in inst/ can be built ", {
skip_on_cran()
pkg_path <- create_local_package()
suppressMessages(use_readme_rmd())
dir_create(pkg_path, "inst")
file_copy(
path(pkg_path, "README.Rmd"),
path(pkg_path, "inst", "README.Rmd")
)
expect_error(
build_readme(pkg_path),
"Can't have both"
)
file_delete(path(pkg_path, "README.Rmd"))
suppressMessages(build_readme(pkg_path))
expect_true(file_exists(path(pkg_path, "inst", "README.md")))
expect_false(file_exists(path(pkg_path, "README.Rmd")))
expect_false(file_exists(path(pkg_path, "README.md")))
expect_false(file_exists(path(pkg_path, "inst", "README.html")))
})
|
test_that("gammaln() matchest log(gamma())", {
for (i in 1:100){
expect_equal(gammaln(i), log(gamma(i)))
}
for (i in 1:100){
expect_true(gammaln(i*10) > 0)
}
})
|
localIntegration = function(x, y, R1, R2=R1) {
if(ncol(x)!=ncol(y)) stop("Dimensions of x and y must agree.")
if(ncol(x)>3) stop("Dimensions must be less than 3.")
Nx = nrow(x)
Px = nrow(y)
if(all(Nx!=0,Px!=0)) {
int = local.int.cpp(posx=x, posy=y, R1=R1, R2=R2)
intX = int$x
intY = int$y
} else {
intX = rep(0, length=Nx)
intY = rep(0, length=Px)
}
return(list(x=intX, y=intY))
}
brownian1D = function(object, sd, N=NULL, ...) {
if(N==0) return(object)
if(any(is.null(N), N>length(object), N<0)) N = length(object)
object[seq_len(N)] = object[seq_len(N)] + rnorm(N, mean=0, sd=sd)
return(object)
}
brownian2D = function(object, sd, N=NULL, ...) {
if(N==0) return(object)
if(any(is.null(N), N>length(object), N<0)) N = nrow(object)
angulo = runif(N)
dist = rnorm(N, mean=0, sd=sd)
object[seq_len(N), ] = object[seq_len(N), ] + dist*cbind(cos(pi*angulo),sin(pi*angulo))
return(object)
}
brownian3D = function(object, sd, N=NULL, ...) {
if(N==0) return(object)
if(any(is.null(N), N>length(object), N<0)) N = nrow(object)
angulo1 = runif(N)
angulo2 = runif(N)
dist = rnorm(N, mean=0, sd=sd)
object[seq_len(N), , ] = object[seq_len(N), , ] +
dist*cbind(sin(pi*angulo2)*cos(pi*angulo1),
sin(pi*angulo2)*sin(pi*angulo1),
cos(pi*angulo2))
return(object)
}
.checkRates = function(rates, n) {
if(length(rates)==1) rates = rep(rates, length=n)
if(length(rates)!=n) stop("Rates and population size do not match.")
rates = pmin(pmax(rates, 0),1)
if(any(is.na(rates))) warning("NA rates are being taken as zero.")
rates[is.na(rates)] = 0
return(rates)
}
.getVector = function(x, size) {
if(is.null(size)) return(x)
if(size>length(x)) return(x)
return(x[seq_len(size)])
}
.getMatrix = function(x, size) {
if(is.null(size)) return(x)
if(size>nrow(x)) return(x)
return(x[seq_len(size), , drop=FALSE])
}
updateMatrixSize = function(x, n, max) {
ndim = dim(x)
ndim[1] = min(max(5*ndim[1], 2*n), max)
out = array(dim=ndim)
out[seq_len(dim(x)[1]), ] = x
return(out)
}
.summary = function(x, alpha, nmax) {
nmax = min(nmax, ncol(x))
output = list()
output$mean = rowMeans(x, na.rm=TRUE)
output$median = apply(x, 1, median, na.rm=TRUE)
output$ll = apply(x, 1, quantile, prob=(1-alpha)/2, na.rm=TRUE)
output$ul = apply(x, 1, quantile, prob=1-(1-alpha)/2, na.rm=TRUE)
output$rep = x[, sample(ncol(x), nmax)]
output$xlim = c(0, nrow(x))
output$ylim = quantile(x, prob=c((1-alpha)/4, 1-(1-alpha)/4), na.rm=TRUE)
return(output)
}
|
xgx_scale_y_log10 <- function(breaks = xgx_breaks_log10,
minor_breaks = NULL,
labels = xgx_labels_log10,
...) {
if (is.null(minor_breaks)) {
minor_breaks <- function(x) xgx_minor_breaks_log10(x)
}
ret <- try(list(ggplot2::scale_y_log10(..., breaks = breaks,
minor_breaks = minor_breaks,
labels = labels)),
silent = TRUE)
if (inherits(ret, "try-error")) {
return(ggplot2::scale_y_log10(...))
} else {
return(ret)
}
}
|
runMACS <- function(
obj,
output.prefix,
path.to.snaptools,
path.to.macs,
gsize,
tmp.folder,
buffer.size=500,
macs.options="--nomodel --shift 37 --ext 73 --qval 1e-2 -B --SPMR --call-summits",
num.cores=1,
keep.minimal=TRUE
){
cat("Epoch: checking input parameters ... \n", file = stderr())
if(missing(obj)){
stop("obj is missing")
}else{
if(!is.snap(obj)){
stop("obj is not a snap object");
}
if((x=nrow(obj))==0L){
stop("obj is empty");
}
if((x=length(obj@barcode))==0L){
stop("obj@barcode is empty");
}
if((x=length(obj@file))==0L){
stop("obj@file is empty");
}
}
fileList = as.list(unique(obj@file));
if(any(do.call(c, lapply(fileList, function(x){file.exists(x)})) == FALSE)){
idx = which(do.call(c, lapply(fileList, function(x){file.exists(x)})) == FALSE)
print("error: these files does not exist")
print(fileList[idx])
stop()
}
if(any(do.call(c, lapply(fileList, function(x){isSnapFile(x)})) == FALSE)){
idx = which(do.call(c, lapply(fileList, function(x){isSnapFile(x)})) == FALSE)
print("error: these files are not snap file")
print(fileList[idx])
stop()
}
if(any(do.call(c, lapply(fileList, function(x){ "FM" %in% h5ls(x, recursive=1)$name })) == FALSE)){
idx = which(do.call(c, lapply(fileList, function(x){ "FM" %in% h5ls(x, recursive=1)$name })) == FALSE)
print("error: the following nsap files do not contain FM session")
print(fileList[idx])
stop()
}
if(missing(output.prefix)){
stop("output.prefix is missing");
}
if(missing(path.to.snaptools)){
stop("path.to.snaptools is missing");
}else{
if(!file.exists(path.to.snaptools)){
stop("path.to.snaptools does not exist");
}
flag = tryCatch({
file_test('-x', path.to.snaptools);
},
error=function(cond){
return(FALSE)
})
if(flag == FALSE){
stop("path.to.snaptools is not an excutable file");
}
}
if(missing(path.to.macs)){
stop("path.to.macs is missing");
}else{
if(!file.exists(path.to.macs)){
stop("path.to.macs does not exist");
}
flag = tryCatch({
file_test('-x', path.to.macs);
},
error=function(cond){
return(FALSE)
})
if(flag == FALSE){
stop("path.to.macs is not an excutable file");
}
}
if(missing(gsize)){
stop("gsize is missing");
}
if(missing(tmp.folder)){
stop("tmp.folder is missing")
}else{
if(!dir.exists(tmp.folder)){
stop("tmp.folder does not exist");
}
}
barcode.files = lapply(fileList, function(file){
tempfile(tmpdir = tmp.folder, fileext = ".barcode.txt");
})
bed.files = lapply(fileList, function(file){
tempfile(tmpdir = tmp.folder, fileext = ".bed.gz");
})
cat("Epoch: extracting fragments from each snap files ...\n", file = stderr())
flag.list = lapply(seq(fileList), function(i){
file.name = fileList[[i]];
idx = which(obj@file == file.name);
barcode.use = obj@barcode[idx]
write.table(barcode.use, file = barcode.files[[i]], append = FALSE, quote = FALSE, sep = "\t",
eol = "\n", na = "NA", dec = ".", row.names = FALSE,
col.names = FALSE, qmethod = c("escape", "double"),
fileEncoding = "")
})
flag.list = mclapply(seq(fileList), function(i){
flag = system2(command=path.to.snaptools,
args=c("dump-fragment",
"--snap-file", fileList[[i]],
"--output-file", bed.files[[i]],
"--barcode-file", barcode.files[[i]],
"--buffer-size", buffer.size
)
)
}, mc.cores=num.cores);
combined.bed = tempfile(tmpdir = tmp.folder, fileext = ".bed.gz");
flag = system2(command="cat",
args=c(paste(bed.files, collapse = ' '),
">", combined.bed
)
)
flag = system2(command=path.to.macs,
args=c("callpeak",
"-t", combined.bed,
"-f", "BED",
"-g", gsize,
macs.options,
"-n", output.prefix
)
)
if (flag != 0) {
stop("'MACS' call failed");
}
if(keep.minimal){
system(paste("rm ", output.prefix, "_control_lambda.bdg", sep=""));
system(paste("rm ", output.prefix, "_peaks.xls", sep=""));
system(paste("rm ", output.prefix, "_summits.bed", sep=""));
}
return(read.table(paste(output.prefix, "_peaks.narrowPeak", sep="")));
}
runMACSForAll <- function(
obj,
output.prefix,
path.to.snaptools,
path.to.macs,
gsize,
tmp.folder,
num.cores=1,
min.cells=100,
buffer.size=500,
macs.options="--nomodel --shift 37 --ext 73 --qval 1e-2 -B --SPMR --call-summits",
keep.minimal=TRUE
){
cat("Epoch: checking input parameters ... \n", file = stderr())
if(missing(obj)){
stop("obj is missing")
}else{
if(!is.snap(obj)){
stop("obj is not a snap object");
}
if((x=nrow(obj))==0L){
stop("obj is empty");
}
if((x=length(obj@barcode))==0L){
stop("obj@barcode is empty");
}
if((x=length(obj@file))==0L){
stop("obj@file is empty");
}
nclusters = length(levels(obj@cluster));
}
fileList = as.list(unique(obj@file));
if(any(do.call(c, lapply(fileList, function(x){file.exists(x)})) == FALSE)){
idx = which(do.call(c, lapply(fileList, function(x){file.exists(x)})) == FALSE)
print("error: these files does not exist")
print(fileList[idx])
stop()
}
if(any(do.call(c, lapply(fileList, function(x){isSnapFile(x)})) == FALSE)){
idx = which(do.call(c, lapply(fileList, function(x){isSnapFile(x)})) == FALSE)
print("error: these files are not snap file")
print(fileList[idx])
stop()
}
if(any(do.call(c, lapply(fileList, function(x){ "FM" %in% h5ls(x, recursive=1)$name })) == FALSE)){
idx = which(do.call(c, lapply(fileList, function(x){ "FM" %in% h5ls(x, recursive=1)$name })) == FALSE)
print("error: the following nsap files do not contain FM session")
print(fileList[idx])
stop()
}
if(nclusters == 0L){
stop("obj does not have cluster, runCluster first")
}
if(missing(output.prefix)){
stop("output.prefix is missing");
}
if(missing(path.to.snaptools)){
stop("path.to.snaptools is missing");
}else{
if(!file.exists(path.to.snaptools)){
stop("path.to.snaptools does not exist");
}
flag = tryCatch({
file_test('-x', path.to.snaptools);
},
error=function(cond){
return(FALSE)
})
if(flag == FALSE){
stop("path.to.snaptools is not an excutable file");
}
}
if(missing(path.to.macs)){
stop("path.to.macs is missing");
}else{
if(!file.exists(path.to.macs)){
stop("path.to.macs does not exist");
}
flag = tryCatch({
file_test('-x', path.to.macs);
},
error=function(cond){
return(FALSE)
})
if(flag == FALSE){
stop("path.to.macs is not an excutable file");
}
}
if(missing(gsize)){
stop("gsize is missing");
}
if(missing(tmp.folder)){
stop("tmp.folder is missing")
}else{
if(!dir.exists(tmp.folder)){
stop("tmp.folder does not exist");
}
}
peak.ls <- parallel::mclapply(as.list(levels(obj@cluster)), function(x){
num.cells = length(which(obj@cluster == x));
if(num.cells < min.cells){
return(GenomicRanges::GRanges())
}
peaks.df <- runMACS(
obj=obj[which(obj@cluster==x),],
output.prefix=paste(output.prefix, x, sep="."),
path.to.snaptools=path.to.snaptools,
path.to.macs=path.to.macs,
gsize=gsize,
buffer.size=buffer.size,
macs.options=macs.options,
tmp.folder=tmp.folder,
keep.minimal=keep.minimal,
num.cores=1
);
if((x=nrow(peaks.df)) > 0L){
peaks.gr = GenomicRanges::GRanges(peaks.df[,1], IRanges(peaks.df[,2], peaks.df[,3]));
}else{
peaks.gr = GenomicRanges::GRanges();
}
}, mc.cores=num.cores)
peaks.gr = GenomicRanges::reduce(do.call(c, peak.ls));
return(peaks.gr);
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
load("models_IRT.RData")
library(lcmm)
library(ggplot2)
library(ggpubr)
library(splines)
library(gridExtra)
library(dplyr)
str(simdataHADS)
demo <- simdataHADS %>% group_by(ID) %>% arrange(time) %>%
filter(row_number()==1)
summary(demo)
tempSim <- simdataHADS %>% group_by(ID) %>% arrange(time) %>% mutate(Visit=ifelse(time==time_entry,"Entry","Follow-up"))
p <- ggplot(tempSim, aes(x=time,fill=Visit,color=Visit)) + geom_histogram(binwidth=1,aes(y=..density..)) +
labs(x="Months on the waiting list")
p + scale_color_grey(start = 0.1,
end = 0.5)+scale_fill_grey(start = 0.1,
end = 0.5) +
theme_classic()
quantile(simdataHADS$time,probs=(0:10)/10)
summary(modIRT)
datnew <- data.frame(time = seq(0,75,by=1))
datnew$grp <- 0
pIRT0 <- predictL(modIRT,datnew,var.time="time",confint = T)
datnew$grp <- 1
pIRT1 <- predictL(modIRT,datnew,var.time="time",confint = T)
plot(pIRT0,col=1,lwd=2,ylim=c(-1.5,1.5),legend=NULL,main="",ylab="latent depressive symptomatology",xlab="months since entry on the waiting list",type="l",bty="l",shades=T)
plot(pIRT1,add=T,col=4,lwd=2,shades=T)
legend(x="topleft",legend=c("dialysed","preemptive"),lty=c(1,1),col=c(1,4),lwd=2,bty="n")
beta <- modIRT$best
t <- 0:72
Z <- cbind(rep(1,length(t)),ns(t,knots=c(7,15),Boundary.knots = c(0,60)))
chol <- matrix(0,ncol=4,nrow=4)
chol[upper.tri(chol, diag = T)] <- c(1,beta[7:15])
library(mvtnorm)
Lambda0 <- rmvnorm(10000,mean = Z%*%c(0,beta[1:3]),Z%*%t(chol)%*%chol%*%t(Z))
Lambda1 <- rmvnorm(10000,mean = Z%*%beta[4:7],Z%*%t(chol)%*%chol%*%t(Z))
Lambda <- data.frame(Lambda = as.vector(rbind(Lambda0,Lambda1)))
phist <- ggplot(Lambda,aes(x=Lambda))+ geom_density(color="grey", fill="grey") + theme_bw() +
xlab("underlying depressive symptomatology") +xlim(-7,7)
phist
quantile(Lambda$Lambda,p=c(0.025,0.975))
nlevel <- 4
nitems <- 7
levels <- rep(nlevel,nitems)
npm <- length(modIRT$best)
seuils <- modIRT$best[(npm-(nlevel-1)*(nitems)+1):(npm)]
err <- abs(modIRT$best[(npm-(nlevel-1)*(nitems)-(nitems-1)):(npm-(nlevel-1)*(nitems))])
seuils
err
Vseuils <- VarCov(modIRT)[(npm-(nlevel-1)*(nitems)+1):(npm),(npm-(nlevel-1)*(nitems)+1):(npm)]
Verr <- VarCov(modIRT)[(npm-(nlevel-1)*(nitems)-(nitems-1)):(npm-(nlevel-1)*(nitems)),(npm-(nlevel-1)*(nitems)-(nitems-1)):(npm-(nlevel-1)*(nitems))]
location <- function(min,max,param,Vparam){
loc <- param[1]
se <- sqrt(Vparam[1,1])
param2 <- rep(0,length(param))
param2[1] <- 1
if ((max-min)>1) {
for (l in 1:(max-min-1)) {
param2[l+1] <- 2*param[l+1]
loc[l+1] <- loc[l] + param[1+l]^2
se[l+1] <- sqrt(t(param2) %*%Vparam %*%param2)
}
}
return(c(loc,se))
}
ItemLoc <- sapply(1:nitems,function(k){location(min=0,max=nlevel-1,param=seuils[((nlevel-1)*(k-1)+1):((nlevel-1)*k)],Vparam=Vseuils[((nlevel-1)*(k-1)+1):((nlevel-1)*k),((nlevel-1)*(k-1)+1):((nlevel-1)*k)])})
colnames(ItemLoc) <- paste("Item",(1:nitems)*2)
ItemLoc <- ItemLoc[c(1,4,2,5,3,6),]
rownames(ItemLoc) <- rep(c("Threshold","SE"),nlevel-1)
discrimination <- 1/abs(err)
sediscr <- diag(err^(-2))%*%Verr%*%diag(err^(-2))
t(rbind(ItemLoc,discrimination,Se=sqrt(diag(sediscr))))
info_modIRT <- ItemInfo(modIRT, lprocess=seq(-6,6,0.1))
meaning <- c("Enjoy","Laugh","Cheerful" ,"Slow" ,"Appearance" ,"Looking Forward" ,"Leisure")
items <- paste("hads", seq(2,14,2), sep="_")
par(mfrow=c(2,4), mar=c(3,2,2,1), mgp=c(2,0.5,0))
for(k in 1:7)
{
plot(info_modIRT, which="LevelProb", outcome=items[k],
main=paste("Item",2*k,"-",meaning[k]), lwd=2, legend=NULL)
}
plot(0,axes=FALSE, xlab="", ylab="", col="white")
legend("center", legend=paste("Level",0:3), col=1:4, lwd=2, box.lty=0)
p <- NULL
for (k in 1:7){
ICC <- info_modIRT$LevelInfo[which(info_modIRT$LevelInfo[,1]==items[k]),]
p[[k]] <- (ggplot(ICC)
+ geom_line(aes(x = Lprocess, y = Prob, group = Level,color=Level), show.legend = F,alpha = 1,size=1.2)
+ theme_bw()
+ labs(title=paste("Item",2*k,"-",meaning[k]))
+ xlab("construct")
+ ylim(0,1)
+ ylab("Probability of item level"))
}
p[[8]] <- (ggplot(ICC)
+ geom_line(aes(x = Lprocess, y = Prob, group = Level,color=Level),alpha = 1,size=1.2)
+ theme_bw()
)
legend <- get_legend(p[[8]])
grid.arrange(p[[1]],p[[2]],p[[3]],p[[4]],p[[5]],p[[6]],p[[7]],as_ggplot(legend),ncol=4)
expe <- predictYcond(modIRT,lprocess = seq(-6,6,by=0.1))
plot(expe, xlab="underlying depressive symptomatology", main="Item Expectation Curves",
legend=paste("Item",(1:nitems)*2), lwd=2)
j <- table(expe$pred$Yname)[1]
expe$pred$item <- as.factor(c(rep(2,j),rep(4,j),rep(6,j),rep(8,j),rep(10,j),rep(12,j),rep(14,j)))
p <- (ggplot(expe$pred)
+ geom_line(aes(x = Lprocess, y = Ypred, group=item,color=item),alpha = 1,size=1.2)
+ theme_bw()
+ xlab("underlying depressive symptomatology")
+ ylim(0,3)
+ ylab("Item Expectation"))
p
par(mfrow=c(2,4), mar=c(3,2,2,1), mgp=c(2,0.5,0))
for(k in 1:7)
{
plot(info_modIRT, which="LevelInfo", outcome=items[k],
main=paste("Item",2*k,"-",meaning[k]), lwd=2, legend=NULL, ylim=c(0,1.3))
}
plot(0,axes=FALSE, xlab="", ylab="", col="white")
legend("center", legend=paste("Level",0:3), col=1:4, lwd=2, box.lty=0)
plot(info_modIRT, which="ItemInfo", lwd=2, legend.loc="topleft")
par(mfrow=c(2,4), mar=c(3,2,2,1), mgp=c(2,0.5,0))
for(k in 1:7){
plot(ns0,outcome = k,shades = T,ylim=c(0,3),bty="l",legend=NULL,main=paste("Item",2*k,"-",meaning[k]),ylab="Item level",xlab="months on the waiting list")
plot(ns1,outcome=k,shades=T,add=T,col=2)
}
sumDIF <- summary(modIRT_DIFg)
sumDIF[,2]
WaldMult(modIRT_DIFg,pos=c(8:13))
sum <- summary(modIRT_DIFg)[10,]
c(sum[1],sum[1]- qnorm(0.975)*sum[2],sum[1]+ qnorm(0.975)*sum[2])
summary(modIRT_DIFt)
b <- coef(modIRT_DIFt)
v <- vcov(modIRT_DIFt)
A <- rbind(c(rep(0,7), rep(-1,6), rep(0,49)),
c(rep(0,7+6), rep(-1,6), rep(0,49-6)),
c(rep(0,7+12), rep(-1,6), rep(0,49-12)))
w <- t(A%*%b) %*% solve(A%*%v%*%t(A)) %*% A%*%b
DIF14 <- 1-pchisq(w, df=nrow(A))
DIF <- cbind(seq(2,14,by=2),c(sapply(1:6,function(k){WaldMult(modIRT_DIFt,pos=c(7+k,(7+6+k),(7+2*6+k)))[2]}),DIF14))
colnames(DIF) <- c("item","pvalue")
DIF
par(mfrow=c(3,3), mar=c(3,2,2,1), mgp=c(2,0.5,0))
for(k in 1:7){
plot(ns0,outcome = k,shades = T,ylim=c(0,3),bty="l",legend=NULL,main=paste("Item",2*k,"-",meaning[k]),ylab="Item level",xlab="months on the waiting list",color=1,lwd=2,xlim=c(0,50))
plot(ns0DIFt,outcome=k,shades=T,lty=2,add=T,col=1,lwd=2)
plot(ns1,outcome=k,shades=T,add=T,col=4,lwd=2)
plot(ns1DIFt,outcome=k,shades=T,add=T,col=4,lty=2,lwd=2)
legend("top",legend=paste("(RS overall test: p = ",round(DIF[k,2],digits = 3),")",sep=""),bty="n")
}
plot(0,xaxt='n',yaxt='n',bty='n',pch='',ylab='',xlab='', main ='')
legend(x="top",legend=c("dialysed","pre-emptive"),lty=c(1,1),col=c(1,4),lwd=2,bty="n")
legend(x="bottom",legend=c("without RS","with RS"),lty=c(1,2),col=c("gray","gray"),lwd=2,bty="n")
|
multResp<-
function (...) {
nameargs <- function(dots) {
nm <- names(dots)
fixup <- if (is.null(nm))
seq(along = dots)
else nm == ""
dep <- sapply(dots[fixup], function(x) deparse(x, width.cutoff = 500)[1])
if (is.null(nm))
nm <- dep
else {
nm[fixup] <- dep
}
nm
}
dots<-as.list(substitute(list(...)))[-1]
n=1
if(sys.nframe()>1)
for(i in 1:(sys.nframe()-1)){
if(sys.call(-i)[[1]]=="eval"){
n <- i
break
}
}
mt<-NULL
for (i in seq(along=dots)) {
mt<-cbind(mt,as.matrix(eval.parent(dots[i][[1]],n)))
}
colnames(mt)<-nameargs(dots)
mt
}
|
encounter <- function(object,include=NULL,exclude=NULL,debias=FALSE,...)
{
UD <- object
check.projections(UD)
if(is.null(include) && is.null(exclude)) { exclude <- diag(1,length(UD)) }
if(is.null(include)) { include <- 1 - exclude }
axes <- UD[[1]]$axes
AXES <- length(axes)
CTMM <- lapply(UD,function(U){U@CTMM})
STUFF <- encounter.ctmm(CTMM,include=include,exclude=exclude,debias=debias)
CTMM <- STUFF$CTMM
BIAS <- STUFF$BIAS
bias <- STUFF$bias
DOF.area <- rep(DOF.area(CTMM),AXES)
names(DOF.area) <- axes
for(i in 1:length(object))
{
UD[[i]]$PMF <- UD[[i]]$PDF * prod(UD[[i]]$dr)
if(debias) { UD[[i]]$PMF <- debias.volume(UD[[i]]$PMF,BIAS[i])$PMF }
}
GRID <- grid.union(object)
DIM <- c(length(GRID$r$x),length(GRID$r$y))
PMF <- matrix(0,DIM[1],DIM[2])
for(i in 1:(length(UD)-1))
{
for(j in (i+1):length(UD))
{
SUB <- grid.intersection(list(GRID,UD[[i]],UD[[j]]))
if(length(SUB[[1]]$x) && length(SUB[[1]]$y))
{
PROD <- UD[[i]]$PMF[SUB[[2]]$x,SUB[[2]]$y] * UD[[j]]$PMF[SUB[[3]]$x,SUB[[3]]$y]
if(debias)
{
gamma <- sum(PROD)
PROD <- PROD / gamma
PROD <- debias.volume(PROD,bias[i,j])$PMF
PROD <- PROD * gamma
}
PMF[SUB[[1]]$x,SUB[[1]]$y] <- PMF[SUB[[1]]$x,SUB[[1]]$y] + include[i,j] * PROD
}
}
}
dV <- prod(UD[[1]]$dr)
GAMMA <- sum(PMF)
PMF <- PMF / GAMMA
object <- GRID
object$PDF <- PMF / dV
object$CDF <- pmf2cdf(PMF)
object$axes <- axes
IN <- 0
H <- matrix(0,AXES,AXES)
for(i in 1:(length(UD)-1))
{
for(j in (i+1):length(UD))
{
IN <- IN + include[i,j]
H <- H + include[i,j] * PDsolve( PDsolve(UD[[i]]$H) + PDsolve(UD[[i]]$H) )
}
}
H <- H/IN
dimnames(H) <- list(axes,axes)
object$H <- H
object$DOF.area <- DOF.area
info <- mean.info(UD)
object <- new.UD(object,info=info,type='encounter',CTMM=CTMM)
return(object)
}
encounter.ctmm <- function(CTMM,include=NULL,exclude=NULL,debias=FALSE,...)
{
axes <- CTMM[[1]]$axes
AXES <- length(axes)
isotropic <- sapply(CTMM,function(C){C$isotropic})
DIM <- ifelse(isotropic,1,AXES)
WC <- 1 + DIM
MULT <- ifelse(isotropic,AXES,1)
WC <- WC/MULT
CLAMP <- 1
DOF <- sapply(CTMM,DOF.area)
BIAS <- 1/(1+WC/clamp(DOF,CLAMP,Inf))
isotropic <- all(isotropic)
P <- lapply(CTMM,function(M){PDsolve(M$sigma)})
dof <- matrix(0,length(DOF),length(DOF))
bias <- matrix(1,length(DOF),length(DOF))
for(i in 1:length(DOF))
{
for(j in 1:length(DOF))
{
Pi <- tr(P[[i]])
Pj <- tr(P[[j]])
Pij <- Pi + Pj
dof[i,j] <- Pij^2 / ( Pi^2/DOF[i] + Pj^2/DOF[j] )
wc <- (Pi/Pij)*WC[i] + (Pj/Pij)*WC[j]
bias[i,j] <- 1 + wc/clamp(dof[i,j],2*CLAMP,Inf)
}
}
fn <- function(CTMM)
{
IN <- 0
M1 <- array(0,AXES)
M2 <- matrix(0,AXES,AXES)
P <- lapply(CTMM,function(M){PDsolve(M$sigma)})
for(i in 1:(length(CTMM)-1))
{
for(j in (i+1):length(CTMM))
{
Pi <- P[[i]]
Pj <- P[[j]]
if(debias)
{
Pi <- Pi * BIAS[i]
Pj <- Pj * BIAS[j]
}
Pij <- Pi + Pj
sigma <- PDsolve(Pij)
mu <- sigma %*% (Pi %*% CTMM[[i]]$mu[1,] + Pj %*% CTMM[[j]]$mu[1,])
mu <- c(mu)
include[i,j] <- include[i,j] / sqrt( det(CTMM[[i]]$sigma) * det(CTMM[[j]]$sigma) * det(Pij) )
if(debias) { sigma <- sigma / bias[i,j] }
IN <- IN + include[i,j]
M1 <- M1 + include[i,j] * mu
M2 <- M2 + include[i,j] * (sigma + outer(mu))
}
}
M1 <- M1/IN
M2 <- M2/IN
mu <- M1
sigma <- M2 - outer(M1)
sigma <- covm(sigma)@par
if(isotropic) { sigma <- sigma[1] }
return(c(mu,sigma))
}
STUFF <- gauss.comp(fn,CTMM,COV=TRUE)
I <- 1:AXES
mu <- STUFF$MLE[I]
names(mu) <- axes
COV.mu <- STUFF$COV[I,I,drop=FALSE]
dimnames(COV.mu) <- list(axes,axes)
I <- (AXES+1):length(STUFF$MLE)
sigma <- STUFF$MLE[I]
sigma <- covm(sigma,axes=axes,isotropic=isotropic)
COV <- STUFF$COV[I,I,drop=FALSE]
NAMES <- names(sigma@par)[1:length(I)]
dimnames(COV) <- list(NAMES,NAMES)
info <- mean.info(CTMM)
CTMM <- ctmm(mu=mu,sigma=sigma,COV.mu=COV.mu,COV=COV,axes=axes,isotropic=isotropic,info=info)
return(list(CTMM=CTMM,BIAS=BIAS,bias=bias))
}
|
setup.parameters <-
function(model,parameters=list(),nocc=NULL,check=FALSE,number.of.groups=1)
{
fdir=system.file(package="RMark")
fdir=file.path(fdir,"parameters.txt")
parameter_definitions=read.delim(fdir,header=TRUE,
colClasses=c("character","character",rep("numeric",3),rep("character",4),
"logical","character","logical","numeric",rep("logical",3),"numeric","logical","logical","character","logical"))
parameter_definitions=parameter_definitions[parameter_definitions$model==model,]
par.list=parameter_definitions$parname
if(check)return(par.list)
pars=vector("list",length(par.list))
names(pars)=par.list
for (i in 1:length(par.list))
{
if(par.list[i]%in%names(parameters))
pars[[i]]=parameters[[par.list[i]]]
}
for(i in 1:length(par.list))
{
for(j in 3:ncol(parameter_definitions))
if(!is.na(parameter_definitions[i,j]) & parameter_definitions[i,j]!="" & !names(parameter_definitions)[j]%in%names(parameters[[par.list[i]]]))
pars[[par.list[i]]][names(parameter_definitions)[j]]=list(parameter_definitions[i,j])
if(pars[[par.list[i]]]$formula!=" " && is.character(pars[[par.list[i]]]$formula))
pars[[par.list[i]]]$formula=as.formula(pars[[par.list[i]]]$formula)
if(is.null(pars[[par.list[i]]]$num))pars[[par.list[i]]]$num=NA
if(!is.na(pars[[par.list[i]]]$num)&&pars[[par.list[i]]]$num==1)pars[[par.list[i]]]$num=-(nocc-1)
if(!is.null(pars[[par.list[i]]]$share) && pars[[par.list[i]]]$share && is.null(pars[[par.list[i]]]$pair)) pars[[par.list[i]]]$share=NULL
}
return(pars)
}
|
mcmc.list2init <- function(dat) {
need_packages("coda")
allname <- strsplit(colnames(dat[[1]]),"[",fixed = TRUE)
firstname <- sapply(allname,function(x){x[1]})
dims <- lapply(allname,function(x){
y <- sub(pattern = "]",replacement = "",x[2])
y <- as.numeric(strsplit(y,",",fixed=TRUE)[[1]])
return(y)
})
ind <- t(sapply(dims,function(x){
if(length(x)==2){
return(x)
} else { return(c(NA,NA))}
}))
uname <- unique(firstname)
ic <- list()
n <- nrow(dat[[1]])
nc <- coda::nchain(dat)
for(c in seq_len(nc)) ic[[c]] <- list()
for(v in seq_along(uname)){
cols <- which(firstname == uname[v])
if(length(cols) == 1){
for(c in seq_len(nc)){
ic[[c]][[v]] <- dat[[c]][nr,cols]
names(ic[[c]])[v] <- uname[v]
}
} else {
dim <- length(dims[[cols[1]]])
if(dim == 1){
for(c in seq_len(nc)){
ic[[c]][[v]] <- dat[[c]][nr,cols]
names(ic[[c]])[v] <- uname[v]
}
} else if (dim == 2){
for(c in seq_len(nc)){
ic[[c]][[v]] <- matrix(seq_along(cols),max(ind[cols,1]),max(ind[cols,2]))
ic[[c]][[v]][ind[cols]] <- dat[[c]][nr,cols]
names(ic[[c]])[v] <- uname[v]
}
} else {
PEcAn.logger::logger.severe("dimension not supported",dim,uname[v])
}
}
}
return(ic)
}
|
GetTopography <- function(lon.west, lon.east, lat.north, lat.south, resolution = 3.5,
cache = TRUE, file.dir = tempdir(), verbose = interactive()) {
checks <- makeAssertCollection()
assertNumber(lon.west, finite = TRUE, lower = 0, upper = 360, add = checks)
assertNumber(lon.east, finite = TRUE, lower = 0, upper = 360, add = checks)
assertNumber(lat.north, finite = TRUE, lower = -90, upper = 90, add = checks)
assertNumber(lat.south, finite = TRUE, lower = -90, upper = 90, add = checks)
assertNumeric(resolution, lower = 1/60, finite = TRUE, max.len = 2, add = checks)
assertFlag(cache, add = checks)
assertFlag(verbose, add = checks)
reportAssertions(checks)
if (isTRUE(cache)) {
assertAccess(file.dir, add = checks)
}
reportAssertions(checks)
if (lat.north < lat.south) stopf("'lat.north' can't be smaller than 'lat.south'.")
if (lon.west > lon.east) stopf("'lon.east' can't be smaller than '.lon.west'.")
d <- 1/60
if (length(resolution) == 1) resolution[2] <- resolution[1]
if (lon.west < 180 & lon.east > 180) {
field.left <- GetTopography(lon.west, 180, lat.north, lat.south,
resolution, cache, file.dir, verbose)
field.right <- GetTopography(180 + d, lon.east, lat.north, lat.south,
resolution, cache, file.dir, verbose)
field <- rbind(field.left, field.right)
} else {
lon.west <- ConvertLongitude(lon.west, from = 360)
lon.east <- ConvertLongitude(lon.east, from = 360)
if (cache == TRUE) {
file.name <- paste0(digest::sha1(paste(lon.west, lon.east, lat.north, lat.south,
resolution[1], resolution[2], sep = "_")),
".txt")
file <- file.path(file.dir, file.name)
files <- list.files(file.dir, full.names = TRUE)
}
if (cache == TRUE && file %in% files) {
if (verbose == TRUE) messagef("Fetching cached field.")
field <- data.table::fread(file)[, -1]
} else {
url <- .BuildETOPORequest(lon.west, lon.east, lat.north, lat.south,
resolution[1], resolution[2])
temp_file <- tempfile(fileext = ".tif")
field <- try(utils::download.file(url, temp_file, quiet = TRUE), silent = TRUE)
if (is.error(field)) stopf("Failed to fetch file.")
check_packages(c("raster", "rgdal"), "GetTopography")
field <- data.table::as.data.table(raster::rasterToPoints(raster::raster(temp_file)))
colnames(field) <- c("lon", "lat", "h")
}
field[, lon := ConvertLongitude(lon, from = 180)]
if (cache == TRUE) write.csv(field, file = file)
}
return(field[])
}
.BuildETOPORequest <- function(lon.west, lon.east, lat.north, lat.south, resx, resy) {
width <- (lon.east - lon.west )/resx
height <- (lat.north - lat.south)/resy
bbox <- paste(lon.west, lat.south, lon.east, lat.north, sep = "," )
url <- paste0(
"https://gis.ngdc.noaa.gov/arcgis/rest/services/DEM_mosaics/ETOPO1_ice_surface/ImageServer/exportImage",
"?bbox=", bbox,
"&bboxSR=4326",
"&size=", paste(width, height, sep = ","),
"&imageSR=4326&format=tiff&pixelType=S16&interpolation=+RSP_NearestNeighbor&compression=LZW&f=image")
url
}
|
test_that("numeric by numeric", {
x1=crosstable(mtcars3, where(is.numeric.and.not.surv), by=disp)
expect_equal(dim(x1), c(7,4))
expect_equal(sum(is.na(x1)), 0)
x2=crosstable(mtcars3, where(is.numeric.and.not.surv), by=disp, test=T)
expect_equal(dim(x2), c(7,5))
expect_equal(sum(is.na(x2)), 0)
crosstable(mtcars3, carb, by=disp, cor_method = "kendall")
crosstable(mtcars3, where(is.numeric.and.not.surv), by=disp, cor_method = "pearson")
crosstable(mtcars3, where(is.numeric.and.not.surv), by=disp, cor_method = "kendall")
crosstable(mtcars3, where(is.numeric.and.not.surv), by=disp, cor_method = "spearman")
expect_warning(crosstable(mtcars2, disp, by=hp, funs=mean),
class="crosstable_funs_by_warning")
})
test_that("by factor if numeric <= 3 levels", {
x10 = crosstable(mtcars2, cyl, by=vs, total="both", margin="all")
x10 %>% as_flextable()
x10 = as.data.frame(x10)
expect_identical(x10[3,5], "14 (43.75% / 100.00% / 77.78%)")
expect_equal(dim(x10), c(4,6))
expect_equal(sum(is.na(x10)), 0)
})
test_that("Functions work", {
x = crosstable(mtcars3, c(disp, hp, am), by=vs, funs=c(meanCI),
funs_arg = list(level=0.99))
x %>% as_flextable()
expect_equal(dim(x), c(4,6))
expect_equal(sum(is.na(x)), 0)
})
test_that("Function arguments work", {
x = crosstable(mtcars3, c(disp, hp, am), by=vs, funs=c(meansd, quantile),
funs_arg = list(dig=3, probs=c(0.25,0.75)),
total=T, showNA="always")
ft = as_flextable(x)
x = as.data.frame(x)
expect_snapshot(x)
expect_snapshot(ft)
})
test_that("One function", {
bar=function(x, dig=1, ...) c("MinMax" = minmax(x, dig=dig, ...), "N_NA" = nna(x))
bar2=function(x, dig=1, ...) c(minmax(x, dig=dig, ...), "N_NA"=nna(x))
bar3=function(x, dig=1, ...) c(minmax(x, dig=dig, ...), nna(x))
cross_list = list(
crosstable(iris2, c(Sepal.Length), funs=mean),
crosstable(iris2, c(Sepal.Length), funs="mean"),
crosstable(iris2, c(Sepal.Length), funs=c("My mean" = mean)),
crosstable(iris2, c(Sepal.Length), funs=cross_summary),
crosstable(iris2, c(Sepal.Length), funs=c(" " = cross_summary)),
crosstable(iris2, c(Sepal.Length), funs=list(" " = cross_summary)),
crosstable(iris2, c(Sepal.Length), funs=c("first"=function(xx) xx[1])),
crosstable(iris2, c(Sepal.Length), funs=c("first"=~.x[1]))
) %>% map(as.data.frame)
expect_snapshot(cross_list, error=FALSE)
expect_warning(crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=function(y) mean(y, na.rm=TRUE)),
class="crosstable_unnamed_anonymous_warning")
expect_warning(crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=~mean(.x, na.rm=TRUE)),
class="crosstable_unnamed_lambda_warning")
})
test_that("One function by", {
bar=function(x, dig=1, ...) c("MinMax" = minmax(x, dig=dig, ...), "N_NA" = nna(x))
bar2=function(x, dig=1, ...) c(minmax(x, dig=dig, ...), "N_NA"=nna(x))
bar3=function(x, dig=1, ...) c(minmax(x, dig=dig, ...), nna(x))
cross_list = list(
crosstable(iris2, c(Sepal.Length), by=Species, funs=mean),
crosstable(iris2, c(Sepal.Length), by=Species, funs="mean"),
crosstable(iris2, c(Sepal.Length), by=Species, funs=c("My mean" = mean)),
crosstable(iris2, c(Sepal.Length), by=Species, funs=cross_summary),
crosstable(iris2, c(Sepal.Length), by=Species, funs=c(" " = cross_summary)),
crosstable(iris2, c(Sepal.Length), by=Species, funs=list(" " = cross_summary)),
crosstable(iris2, c(Sepal.Length), by=Species, funs=c("first"=function(xx) xx[1])),
crosstable(iris2, c(Sepal.Length), by=Species, funs=c("first"=~.x[1]))
) %>% map(as.data.frame)
expect_snapshot(cross_list, error=FALSE)
expect_warning(crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=function(y) mean(y, na.rm=TRUE)),
class="crosstable_unnamed_anonymous_warning")
expect_warning(crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=~mean(.x, na.rm=TRUE)),
class="crosstable_unnamed_lambda_warning")
})
test_that("Multiple functions", {
x1 = crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=c(var, "meannnn"=mean))
expect_setequal(x1$variable, c("var", "meannnn"))
x2 = crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=c(
"moy_lambda"=~mean(.x, na.rm=TRUE),
"moy_fn"=function(.x) mean(.x, na.rm=TRUE),
var,
"cross_summary1" = cross_summary
))
expect_setequal(x2$variable,
c("moy_lambda", "moy_fn", "var",
paste("cross_summary1", names(cross_summary(1))))
)
x3 = crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=c(
~mean(.x, na.rm=TRUE),
function(.x){
.x=.x+1
mean(.x, na.rm=TRUE)
},
var,
"moyenne"=mean
)) %>%
expect_warning2(class="crosstable_unnamed_anonymous_warning") %>%
expect_warning2(class="crosstable_unnamed_lambda_warning")
expect_setequal(attr(x3, "obj")$variable,
c("~mean(.x, na.rm = TRUE)",
"function(.x){.x = .x + 1...}",
"var", "moyenne"))
x4 = crosstable(iris2, c(Sepal.Length, Sepal.Width),
funs=c(
~mean(.x, na.rm=TRUE),
function(.x){mean(.x, na.rm=TRUE)},
var,
mean
)) %>%
expect_warning2(class="crosstable_unnamed_anonymous_warning") %>%
expect_warning2(class="crosstable_unnamed_lambda_warning")
expect_setequal(attr(x4, "obj")$variable,
c("~mean(.x, na.rm = TRUE)",
"function(.x){mean(.x, na.rm = TRUE)}",
"var", "mean"))
})
test_that("Special summary functions", {
ct = crosstable(mtcars2, hp_date, date_format="%d/%m/%Y") %>% as.data.frame()
expect_equal(ct[1,4], "22/02/2010 - 02/12/2010")
x = mtcars2 %>% dplyr::transmute(mpg=mpg/100000)
rlang::local_options(crosstable_only_round=NULL)
ct = crosstable(x, funs_arg=list(dig=2, zero_digits=5)) %>% as.data.frame()
expect_equal(ct[1,4], "0.000104 / 0.000339")
rlang::local_options(crosstable_only_round=TRUE)
ct = crosstable(x, funs_arg=list(dig=2, zero_digits=5)) %>% as.data.frame()
expect_equal(ct[1,4], "0 / 0")
})
|
embeds_ui <- function(){
fluidPage(
title = "coronavirus",
tags$head(
tags$link(rel="stylesheet", type="text/css", href="www/style.css"),
tags$link(rel="stylesheet", type="text/css", href="www/embeds.css"),
sever::use_sever(),
waiter::use_waiter(include_js = FALSE),
HTML(
"
<script async src='https://www.googletagmanager.com/gtag/js?id=UA-74544116-1'></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-74544116-1');
</script>"
)
),
echarts4r::echarts4rOutput("chart", height = "100vh"),
waiter::waiter_show_on_load(loader, color = "
waiter::waiter_hide_on_render("chart")
)
}
|
make_tcga_group <- function(exp){
k1 = stringr::str_starts(colnames(exp),"TCGA")
if(!any(k1))stop("no TCGA samples detected,please check it")
k2 = suppressWarnings(as.numeric(stringr::str_sub(colnames(exp),14,15))<10)
group_list = ifelse(k1&k2,"tumor","normal")
group_list = factor(group_list,levels = c("normal","tumor"))
return(group_list)
}
trans_exp = function(exp,mrna_only = FALSE,lncrna_only = FALSE,gtex = FALSE){
k00 = any(str_detect(colnames(exp),"TCGA"))
if(!k00)warning("this expression set probably not from TCGA,please ensure it")
k0 = any(str_detect(colnames(exp),"GTEX"))
kd = any(str_detect(rownames(exp),"\\."))
if((!(k0|gtex))){
lanno = lnc_anno
manno = mRNA_anno
}else if(k00){
lanno = lnc_annov23
manno = mRNA_annov23
}
if(!kd){
lanno$gene_id = str_remove(lanno$gene_id,"\\.\\d*")
manno$gene_id = str_remove(manno$gene_id,"\\.\\d*")
}
n1 = sum(rownames(exp) %in% manno$gene_id)
k1 = length(n1)/nrow(exp)< 0.25 & length(n1)<5000
n2 = sum(rownames(exp) %in% lanno$gene_id)
k2 = length(n2)/nrow(exp)< 0.25 & length(n2)<5000
mRNA_exp = exp[rownames(exp) %in% manno$gene_id,]
tmp = data.frame(gene_id = rownames(exp))
x = dplyr::inner_join(tmp,manno,by = "gene_id")
mRNA_exp = mRNA_exp[!duplicated(x$gene_name),]
x = x[!duplicated(x$gene_name),]
rownames(mRNA_exp) = x$gene_name
lnc_exp = exp[rownames(exp) %in% lanno$gene_id,]
tmp = data.frame(gene_id = rownames(exp))
x = dplyr::inner_join(tmp,lanno,by = "gene_id")
lnc_exp = lnc_exp[!duplicated(x$gene_name),]
x = x[!duplicated(x$gene_name),]
rownames(lnc_exp) = x$gene_name
message(paste0(nrow(mRNA_exp),
" of genes successfully mapping to mRNA,",
nrow(lnc_exp),
" of genes successfully mapping to lncRNA"))
if(mrna_only){
return(mRNA_exp)
}else if(lncrna_only){
return(lnc_exp)
}else{
expa = rbind(mRNA_exp,lnc_exp)
k = !duplicated(rownames(expa))
expa = expa[k,]
return(expa)
message(paste0(sum(!k),
" of duplicaterd genes removed"))
}
}
utils::globalVariables(c("lnc_anno","mRNA_anno","lnc_annov23","mRNA_annov23"))
trans_array = function(exp,ids,from = "probe_id",
to = "symbol"){
a = intersect(rownames(exp),ids[,from])
message(paste0(length(a) ," of ",nrow(exp)," rownames matched"))
ids = ids[!duplicated(ids[,to]),]
exp = exp[rownames(exp) %in% ids[,from],]
ids = ids[ids[,from]%in% rownames(exp),]
exp = exp[ids[,from],]
rownames(exp)=ids[,to]
message(paste0(nrow(exp)," rownames transformed after duplicate rows removed"))
return(exp)
}
sam_filter = function(exp){
exp = exp[,order(colnames(exp))]
n1 = ncol(exp)
group = make_tcga_group(exp)
exptumor = exp[,group == "tumor"]
expnormol = exp[,group == "normal"]
exptumor = exptumor[,!duplicated(str_sub(colnames(exptumor),1,12))]
expnormol = expnormol[,!duplicated(str_sub(colnames(expnormol),1,12))]
exp = cbind(exptumor,expnormol)
message(paste("filtered",n1-ncol(exp),"samples."))
return(exp)
}
match_exp_cl = function(exp,cl,id_column = "id",sample_centric = TRUE){
colnames(cl)[colnames(cl)==id_column] = "id"
cl = cl[cl$id %in% substr(colnames(exp),1,12),]
exp = exp[,substr(colnames(exp),1,12) %in% cl$id]
patient <- substr(colnames(exp),1,12)
if(nrow(cl)==0) stop("your exp or cl doesn't match,please check them.")
da = data.frame(sample_id = colnames(exp),
id = patient)
cl = merge(da,cl,by ="id",all.y = TRUE)
cl = cl[match(colnames(exp),cl$sample_id),]
if(!sample_centric) {
Group = make_tcga_group(exp)
exp = exp[,Group=="tumor"]
cl = cl[Group=="tumor",]
cl = cl[order(colnames(exp)),]
exp = exp[,sort(colnames(exp))]
exp = exp[,!duplicated(cl$id)]
cl = cl[!duplicated(cl$id),]
}
k = identical(colnames(exp),cl$sample_id)
if(k)message("match successfully")
rownames(cl) = cl$sample_id
compiler::setCompilerOptions(suppressAll = TRUE)
return(list(exp_matched = exp,
cl_matched = cl))
print("New version of tinyarray canceled global assigning inside the package,
please obtain exp_matched and cl_matched by split this list result.")
}
|
.Random.seed <-
c(403L, 10L, -1980412102L, -1218464891L, -1220695969L, -584492314L,
-52584080L, -844273005L, -1505995983L, -33680928L, 1738106494L,
-899543799L, 214884155L, 580187914L, -96409876L, 1637995375L,
-746216283L, 171284060L, 2082430514L, 479755565L, -263214105L,
213207822L, 353955048L, 2032256747L, -613881975L, -585395432L,
315401798L, -537512287L, 688216371L, 2011920546L, 1536243604L,
260232727L, -21233139L, -306800860L, -400370934L, -97313163L,
-1604493873L, -523270442L, -1275164032L, -2039089981L, -1955630495L,
-201504048L, -666866642L, 637485529L, 1482595819L, -656279462L,
2113813020L, 446339871L, -1228845195L, -1373923828L, -13905950L,
1397273789L, -1854737609L, 940530654L, -306308840L, -1249088389L,
906809881L, 690688680L, 587020374L, 1931089105L, 1667199107L,
2146304786L, 929568420L, -1255767449L, -1917822019L, -2107599564L,
-111235430L, -1094206235L, 1696349823L, 470034438L, -1134408816L,
-1256729037L, -1919629871L, -913549440L, 1722714718L, -81579607L,
1635000411L, 1575680106L, 548477196L, 1933325135L, 2093084677L,
897355452L, -779270254L, 170177677L, 525398727L, 1860199342L,
-1596539384L, 1254814219L, 2146820841L, 1095404984L, -940447130L,
299013889L, -2056150637L, -2110358974L, -1682829836L, -1463011337L,
-2067354643L, 1413235844L, -559031638L, 322637845L, -618637137L,
1743582902L, 646874336L, -1513895901L, 1009686337L, -2129536464L,
-2030516146L, 941045945L, 1638853835L, -943066758L, 164031612L,
-1298544449L, 1341095317L, -525845076L, -951314558L, -2106852003L,
1878340695L, 322720574L, 323255160L, -1045415845L, -560955463L,
-1004651000L, -121738058L, 546143217L, 1761822243L, 201193074L,
-112775996L, 1461103239L, 1427612253L, 1526539348L, 567619194L,
-561574459L, -984633569L, -914842970L, -1501225936L, 959807187L,
-1992237839L, 885405728L, -1972199746L, 827751113L, -781905797L,
2143080010L, 1442839212L, 1532243375L, 623713637L, -1418671332L,
921644914L, -434846739L, -408812505L, -2112955314L, 1939251368L,
571412139L, -571905079L, 1412892632L, -1145090426L, -1415800991L,
162564851L, 1914246498L, 169206740L, -2016278825L, -1990628147L,
-117543836L, 47456842L, 725723061L, 1081506575L, 1624262678L,
992481984L, -1083825021L, -1742778207L, -1317562736L, -727251602L,
-1833241831L, -1090160725L, -88271462L, -1778618020L, 1398704223L,
-944306123L, -1612821556L, -1393131742L, 1834344829L, -1983739273L,
-579742818L, 484336216L, -977417285L, 97025369L, 1613657832L,
123750166L, -97646447L, -872020669L, 1763229778L, -590142748L,
1058239783L, -1631793795L, 8176756L, -453243302L, 1533115045L,
1230094527L, 1892303686L, 1597739472L, 405091315L, 1665665809L,
-1200424128L, 2131690270L, 1086999529L, -935657189L, 1166326570L,
-1556841396L, 713045007L, 1505902405L, 1318623484L, 1061660498L,
324757709L, -1637599097L, -1386370194L, -1972323000L, -1614304949L,
-1080886103L, 728568L, 455951654L, -1372047807L, 938360787L,
-389343870L, -1641383500L, -381713097L, -1763389395L, -709616316L,
-1150117270L, 1601139925L, -1561558417L, -1660824004L, 587125908L,
-319265662L, 294170560L, -1949723332L, 42231440L, -1974748126L,
1186449416L, 1315566732L, 1936148508L, 1522353298L, -1900512128L,
-1709392876L, -1927146712L, -159593414L, -392495920L, 1506593900L,
-1633143116L, -588914670L, -1550663712L, 463041484L, -231983648L,
-1391100894L, 1530623272L, 74178828L, 790781500L, 1007834354L,
-234219280L, 1290897220L, -994951080L, -373245382L, 1758423280L,
-1091980612L, 1437782548L, -999273278L, 717645408L, -1435323012L,
200690896L, -1057252318L, 778750120L, -470418036L, -426038852L,
280696882L, 211319616L, 1257424564L, -1183780536L, -1316281670L,
1022318352L, -476428052L, -1890396076L, -267555054L, -1958411872L,
-2053140532L, 1122391904L, 130790594L, -1813848536L, 1398655404L,
-164113604L, 186643314L, -525641936L, 311863332L, 1996832312L,
-265530662L, 280815504L, -1327158020L, 1961072020L, 1563382594L,
-1879373312L, -1846712260L, 1208232528L, -1796587358L, 1276007240L,
1021338124L, 426095324L, 1218291794L, -149869440L, 2055368532L,
-458965016L, 1170930426L, -1542324400L, -1259105236L, -668847756L,
392885906L, -1159062944L, -128657268L, -169440928L, 1249257698L,
-845912920L, -1091232052L, -690705924L, -1737247822L, 2089548784L,
-1430607420L, 699755864L, -1034528390L, -573695568L, -631430724L,
-419656108L, -1899710014L, -1211348192L, 1300650940L, 872804432L,
1865294818L, 1833338728L, -1936695476L, -1653502212L, 1621446386L,
1359449344L, 251470964L, 933162504L, 1449672122L, 908019152L,
-1523879956L, 1560562580L, 1309716690L, -616678304L, 30700876L,
1693485856L, -269567358L, 181690856L, -457104404L, -506341828L,
887422578L, -1110510736L, -1448260316L, -1701389768L, 1991299482L,
-1035319856L, 339928508L, 740460180L, -1006452094L, 2002687424L,
-647991492L, -1533185392L, -743987422L, -441166328L, -1394867444L,
-573138020L, -894254062L, -256699520L, 1684933396L, -1904184024L,
1210454074L, 480179152L, 1031297644L, 289750068L, -768862062L,
1844527456L, 211823948L, -892367392L, -429050974L, -186872920L,
-1711059828L, 589693884L, 315489394L, -1276323856L, 505025604L,
1227962456L, -1519198150L, 1074376816L, 470799932L, -1538533612L,
68119234L, -1249946912L, 725142652L, 1910734032L, -505312350L,
357084712L, -882116340L, 1475041212L, -1293981390L, 711254208L,
-1755479500L, -2111698232L, -631932230L, 1717765264L, -2083735828L,
-1401135532L, -637712750L, 152753952L, 1639942092L, 1494491360L,
178847426L, -1011514328L, 587680684L, 1304566460L, -2142680590L,
-553249232L, -499759196L, -1894936136L, -1009388710L, -1159613296L,
-48923780L, -1839040748L, 639765826L, -2031337728L, 709669820L,
-1094742192L, 1012586786L, 160145992L, 1130409996L, -1654737828L,
-123371054L, -1597219328L, -1159483052L, -942018328L, 1704677626L,
-1717958960L, 238735660L, -55996172L, -1688031854L, 79260000L,
-342972404L, 1912627936L, -246564254L, -1624419672L, 218180172L,
1167531900L, 453444914L, 2019636848L, -1778592956L, 2092050392L,
-1941416070L, 719480368L, -291579972L, -630983084L, -89841598L,
375996906L, 1660611208L, 1297742897L, 1332203171L, 1573332644L,
466003794L, 1934429863L, 1694970609L, -1693328842L, 1073231572L,
-263890331L, -1341884305L, 1319836328L, -2119604218L, 861177139L,
-2072737387L, -1930881550L, -379639232L, 2141438889L, -497148389L,
-1249658900L, -1936449542L, 162186287L, 1693201465L, -1814124978L,
1148032668L, -1582748659L, -548704137L, -305153920L, -1667088674L,
1793070507L, 1942611629L, 540457754L, 1612112856L, 565690433L,
514256627L, 1404424468L, 587490466L, 1738080695L, 586630529L,
1568887686L, -1057087036L, -1585559307L, 1305364831L, -1219837000L,
-371186026L, 1582477475L, 468466277L, 1833987970L, -815127312L,
639597721L, -558787445L, 1225694588L, 961571754L, -804394017L,
-1639480983L, -1194201730L, -1249153684L, -2146880067L, -1529301369L,
-546893200L, 1283930382L, 563570235L, 151680285L, 115089354L,
648112360L, -1071141935L, -1882632765L, 894338756L, 1009634674L,
9314375L, 452879377L, -311687786L, 837933300L, -1544547707L,
-245179441L, -432942392L, -954387610L, -930838125L, -1136622859L,
935123666L, -376601312L, -1538396919L, -439797189L, 2038230924L,
-1254871526L, -1848256881L, -1454640679L, 1357891182L, -413325828L,
1916411757L, 151259415L, 355476704L, 416910014L, 1488750731L,
-508840179L, 895227706L, -1590677640L, 334775585L, -16984621L,
-1501924108L, 764415362L, -1359513577L, 426933985L, 758655014L,
-672649948L, -677390891L, 661051775L, -967866344L, 900691766L,
-1864543805L, 503046149L, 1417298850L, 1682116496L, -1752061127L,
-870678549L, -1142955812L, 1934221578L, 586035199L, 281379401L,
1363863518L, -420223092L, -914622627L, -969969817L, 1946932368L,
-630457682L, -364325029L, -1286232259L, -625896022L, 303012424L,
1819884145L, 1266228195L, 2087667428L, -1451287022L, 1090152935L,
-29129295L, 993608694L, -1539953132L, 1678455077L, -1344710097L,
-353411096L, -257652538L, -1285763725L, 1314264533L, -2132567630L,
682530688L, 1308625769L, 1882374107L, -1657411796L, -1428616902L,
1690630127L, -1290485127L, 871908622L, 802467036L, -346356915L,
-1957164361L, -230004672L, 1315932446L, 459330539L, 737714029L,
-610052646L, -149182568L, -525670911L, -1633925197L, -261081388L,
1784172514L, 291156599L, 512519105L, 1659574598L, 1393684513L
)
|
add_cell_coloring <- dynutils::inherit_default_params(
add_milestone_coloring,
function(
cell_positions,
color_cells = c("auto", "none", "grouping", "feature", "milestone", "pseudotime"),
trajectory,
grouping = NULL,
groups = NULL,
feature_oi = NULL,
expression_source = "expression",
pseudotime = NULL,
color_milestones = NULL,
milestones = NULL,
milestone_percentages = NULL
) {
color_cells <- match.arg(color_cells)
if (color_cells == "auto") {
if (!is.null(grouping)) {
message("Coloring by grouping")
color_cells <- "grouping"
} else if (!is.null(feature_oi)) {
message("Coloring by expression")
color_cells <- "feature"
} else if (!is.null(milestones) | !is.null(milestone_percentages)) {
message("Coloring by milestone")
color_cells <- "milestone"
} else if (!is.null(pseudotime)) {
message("Coloring by pseudotime")
color_cells <- "pseudotime"
} else {
color_cells <- "grey"
}
}
if (color_cells == "grouping") {
grouping <- get_grouping(trajectory, grouping)
} else if (color_cells == "feature") {
expression <- get_expression(trajectory, expression_source)
check_feature(expression, feature_oi)
} else if (color_cells == "milestone") {
if (is.null(milestone_percentages)) {
message("Using milestone_percentages from trajectory")
milestone_percentages <- trajectory$milestone_percentages
}
} else if (color_cells == "pseudotime") {
pseudotime <- check_pseudotime(trajectory, pseudotime)
cell_positions$pseudotime <- pseudotime[cell_positions$cell_id]
}
if (color_cells == "grouping") {
groups <- check_groups(grouping, groups)
cell_positions$color <- grouping[match(cell_positions$cell_id, names(grouping))]
color_scale <- scale_color_manual(color_cells, values = set_names(groups$color, groups$group_id), guide = guide_legend(ncol = 5))
fill_scale <- scale_fill_manual(color_cells, values = set_names(groups$color, groups$group_id), guide = guide_legend(ncol = 5))
} else if (color_cells == "feature") {
cell_positions$color <- expression[cell_positions$cell_id, feature_oi]
color_scale <- scale_color_distiller(paste0(feature_oi, " expression"), palette = "RdYlBu")
fill_scale <- scale_fill_distiller(paste0(feature_oi, " expression"), palette = "RdYlBu")
} else if (is_colour_vector(color_cells)) {
cell_positions$color <- "trajectories_are_awesome"
color_scale <- scale_color_manual(NULL, values = c("trajectories_are_awesome" = color_cells), guide = "none")
fill_scale <- scale_fill_manual(NULL, values = c("trajectories_are_awesome" = color_cells), guide = "none")
} else if (color_cells == "milestone") {
if (is.null(milestones)) {
assert_that(
milestone_percentages$milestone_id %in% trajectory$milestone_ids,
msg = "Not all milestones were found in milestones tibble. Supply milestones tibble if supplying milestone_percentages separately."
)
milestones <- tibble(milestone_id = trajectory$milestone_ids)
}
if (!"color" %in% names(milestones)) {
milestones <- milestones %>% add_milestone_coloring(color_milestones)
}
milestone_colors <- set_names(milestones$color, milestones$milestone_id) %>% col2rgb %>% t
cell_colors <-
milestone_percentages %>%
group_by(.data$cell_id) %>%
summarise(color = mix_colors(.data$milestone_id, .data$percentage, milestone_colors))
cell_positions <- left_join(cell_positions, cell_colors, "cell_id")
color_scale <- scale_color_identity(NULL, guide = "none")
fill_scale <- scale_fill_identity(NULL, guide = "none")
} else if (color_cells == "pseudotime") {
cell_positions$color <- cell_positions$pseudotime
color_scale <- ggplot2::scale_color_viridis_c("pseudotime")
fill_scale <- ggplot2::scale_fill_viridis_c("pseudotime")
} else if (color_cells == "none") {
cell_positions$color <- "black"
color_scale <- scale_color_identity()
fill_scale <- scale_fill_identity()
}
lst(cell_positions, color_scale, fill_scale, color_cells)
}
)
|
library(BART)
data(leukemia)
leukemia$TD=ceiling(leukemia$TD/30)
leukemia$TB=ceiling(leukemia$TB/30)
leukemia$TA=ceiling(leukemia$TA/30)
leukemia$TC=ceiling(leukemia$TC/30)
leukemia$TP=ceiling(leukemia$TP/30)
leukemia$X7=ceiling(leukemia$X7/30)
N=137
events=unique(sort(c(leukemia$TD, leukemia$TB)))
K=length(events)
T=events[K]
pick=c(1, 3, 5, 7, 8, 9, 10, 11, 12, 14, 20)
x.train3=as.matrix(leukemia[ , -c(2, 4, 6)])
P=ncol(x.train3)
L=32
x.test3=matrix(nrow=L*N, ncol=P)
dimnames(x.test3)=dimnames(x.train3)
k=1
for(R in 0:1)
for(A in 0:1)
for(C in 0:1)
for(P in 0:1)
for(X2 in c(23, 32)) {
h=(k-1)*N+1:N
x.test3[h, ]=x.train3
x.test3[h, 'TB']=R*8+(1-R)*T
x.test3[h, 'R']=R
x.test3[h, 'TA']=A*1+(1-A)*T
x.test3[h, 'A']=A
x.test3[h, 'TC']=C*5+(1-C)*T
x.test3[h, 'C']=C
x.test3[h, 'TP']=P*1+(1-P)*T
x.test3[h, 'P']=P
x.test3[h, 'X2']=X2
k=k+1
}
post3=mc.surv.bart(x.train=x.train3, times=leukemia$TD, delta=leukemia$D,
events=events, ztimes=c(2, 4, 6, 8), zdelta=c(3, 5, 7, 9),
sparse=TRUE, mc.cores=8, seed=99)
state3=surv.pre.bart(leukemia$TD, leukemia$D, x.train3, x.test3,
events=events,
ztimes=c(2, 4, 6, 8), zdelta=c(3, 5, 7, 9))
x.train2=x.train3[ , -(2:3)]
x.test2=x.test3[ , -(2:3)]
post2=mc.surv.bart(x.train=x.train2, times=leukemia$TB, delta=leukemia$R,
events=events, ztimes=c(2, 4, 6), zdelta=c(3, 5, 7),
sparse=TRUE, mc.cores=8, seed=99)
state2=surv.pre.bart(leukemia$TB, leukemia$R, x.train2, x.test2,
events=events, ztimes=c(2, 4, 6), zdelta=c(3, 5, 7))
par(mfrow=c(2, 2))
for(l in 1:L) {
h=(l-1)*N*K+1:(N*K)
for(G in 1:5) {
if(G==1) {
state3$tx.test[h, 'G']=1
state3$tx.test[h, 'X8']=0
} else if(G %in% 2:3) {
state3$tx.test[h, 'G']=2
state3$tx.test[h, 'X8']=G-2
} else if(G %in% 4:5) {
state3$tx.test[h, 'G']=3
state3$tx.test[h, 'X8']=G-4
}
state2$tx.test[h, 'G']=state3$tx.test[h, 'G']
state2$tx.test[h, 'X8']=state3$tx.test[h, 'X8']
pred3=predict(post3, state3$tx.test[h, ], mc.cores=8)
pred2=predict(post2, state2$tx.test[h, ], mc.cores=8)
i=(l-1)*N+1
R=x.test3[i, 'R']
string=paste0(' R=', R, ' A=', x.test3[i, 'A'],
' C=', x.test3[i, 'C'], ' P=', x.test3[i, 'P'],
' X2=', x.test3[i, 'X2'])
state0.mean=double(K)
state1.mean=double(K)
for(j in 1:K) {
k=seq(j, N*K, by=K)
state0.mean[j]=mean(apply(pred3$surv.test[ , k], 1, mean))
state1.mean[j]=mean(apply(pred2$surv.test[ , k]*
pred3$surv.test[ , k], 1, mean))
}
if(R==1) state1.mean[8:K]=0
if(G==1)
plot(c(0, pred3$times), c(1, state0.mean), type='s', lwd=2, lty=G,
ylim=0:1, xlab='t (months)', ylab='P(t, state)', main=string)
else
lines(c(0, pred3$times), c(1, state0.mean), type='s', lwd=2, lty=G)
lines(c(0, pred3$times), c(1, state1.mean), lty=G,
type='s', lwd=2, col=2)
lines(c(0, pred3$times), c(0, state0.mean-state1.mean), lty=G,
type='s', lwd=2, col=4)
if((l%%4)==0) {
legend('topright', col=c(1, 2, 4), lty=1, lwd=2,
legend=c('alive', 'remission', 'relapsed'))
}
else if((l%%2)==0) {
legend('topright', lty=1:5, lwd=2,
legend=c('G=1 X8=0', 'G=2 X8=0', 'G=2 X8=1',
'G=3 X8=0', 'G=3 X8=1'))
}
}
}
dev.off()
|
split_plot <- function(wp = NULL, sp = NULL, reps = NULL, type = 2, l = 1, plotNumber = 101,
seed = NULL, locationNames = NULL, factorLabels = TRUE,
data = NULL) {
if (is.null(seed) || is.character(seed) || is.factor(seed)) seed <- runif(1, min = -50000, max = 50000)
set.seed(seed)
if (all(c(1,2) != type)) {
stop("Input type is unknown. Please, choose one: 1 or 2, for CRD or RCBD, respectively.")
}
args0 <- c(wp, sp, reps, l)
args1 <- list(wp, sp, reps, l)
if (is.null(data)) {
if(all(!is.null(args0))) {
if(all(is.numeric(args0)) && all(lengths(args1) == 1)) {
WholePlots <- 1:wp
SubPlots <- 1:sp
}else if(is.character(wp)) {
if (length(wp) > 1) {
if (is.numeric(sp)) {
if (length(sp) == 1) {
WholePlots <- wp
wp <- length(WholePlots)
SubPlots <- 1:sp
}else {
stop("Input sp should be a integer number.")
}
}else if (is.character(sp) || is.numeric(sp)) {
if (length(sp) > 1) {
WholePlots <- wp
wp <- length(WholePlots)
SubPlots <- sp
sp <- length(SubPlots)
}else {
stop("The number of sub plots should be more than one.")
}
}
}else {
stop("The numerb of whole plots should be more than one.")
}
}
}else {
stop("Input wp, sp, reps and l must be differents of NULL.")
}
}else {
if(!is.data.frame(data)) stop("Data must be a data frame.")
data <- as.data.frame(data[,1:2])
colnames(data) <- c("WholePlot", "SubPlot")
WholePlots <- as.vector(na.omit(data$WholePlot))
SubPlots <- as.vector(na.omit(data$SubPlot))
WholePlots.f <- factor(WholePlots, as.character(unique(WholePlots)))
SubPlots.f <- factor(SubPlots, as.character(unique(SubPlots)))
wp <- length(levels(WholePlots.f))
sp <- length(levels(SubPlots.f))
WholePlots <- as.character(WholePlots.f)
SubPlots <- as.character(SubPlots.f)
if(!factorLabels) {
WholePlots <- as.character(1:wp)
SubPlots <- as.character((wp + 1):(wp + sp))
}
}
b <- reps
if (!is.null(plotNumber)) {
if (any(!is.numeric(plotNumber)) || any(plotNumber < 1) || any(plotNumber %% 1 != 0) ||
any(diff(plotNumber) < 0)) {
shiny::validate("Input plotNumber must be an integer greater than 0 and sorted.")
}
}else {
plotNumber <- seq(1001, 1000*(l+1), 1000)
warning("Since plotNumber was NULL, it was set up to its default value for each location.")
}
plot.number <- plotNumber
if (type == 1) crd <- TRUE else crd <- FALSE
pred_plots <- plot_number_splits(plot.number = plot.number, reps = b, l = l, t = wp, crd = crd)
plot.random <- pred_plots$plots
p.number.loc <- pred_plots$plots_loc
if (crd) {
loc.list <- vector(mode = "list", length = l)
for (v in 1:l) {
spd.layout <- matrix(data = 0, nrow = wp * b, ncol = 4)
spd.layout[,1] <- plot.random[,v]
spd.layout[,2] <- rep(1:b, each = wp)
spd.layout[,3] <- rep(WholePlots, each = b)
spd.layout <- spd.layout[order(spd.layout[,1]),]
rownames(spd.layout) <- 1:(wp * b)
colnames(spd.layout) <- c("PLOT", "REP", "Whole-plot", "Sub-plot")
loc.list[[v]] <- spd.layout
}
spd.layout <- paste_by_row(loc.list)
plots.n <- as.numeric(spd.layout[,1])
wp.reps <- as.numeric(spd.layout[,2])
wp.random <- as.vector(spd.layout[,3])
type <- "CRD"
}else {
plot.numbers <- as.vector(unlist(p.number.loc))
wp.random <- replicate(b * l, sample(WholePlots, replace = FALSE))
spd.layout <- matrix(data = 0, nrow = (b * wp) * l, ncol = 4)
colnames(spd.layout) <- c("PLOT", "REP", "Whole-plot", "Sub-plot")
spd.layout[,1] <- plot.numbers
spd.layout[,2] <- rep(1:b, each = wp)
spd.layout[,3] <- as.vector(wp.random)
plots.n <- as.numeric(spd.layout[,1])
type <- "RCBD"
}
sp.random <- replicate((b * wp) * l, sample(SubPlots, replace = FALSE))
k <- (b * wp) * l
for(i in 1:k) {
spd.layout[i,4] <- paste(sp.random[,i], collapse = " ")
}
loc.spd.layout <- vector(mode = "list", length = l)
y <- seq(1, k, b * wp)
z <- seq(b * wp, k, b * wp)
i <- 1;j <- 1
for(sites in 1:l) {
loc.spd.layout[[sites]] <- spd.layout[y[i]:z[j],]
i <- i + 1
j <- j + 1
}
spd.layout <- as.data.frame(spd.layout)
rownames(spd.layout) <- 1:nrow(spd.layout)
wp.d <- rep(as.vector(wp.random), each = sp)
sp.d <- as.vector(sp.random)
if (!is.null(locationNames) && length(locationNames) == l) {
LOCATION <- rep(locationNames, each = (sp * wp) * b)
}else if (is.null(locationNames) || length(locationNames) != l) {
LOCATION <- rep(1:l, each = (sp * wp) * b)
}
if (crd) {
PLOT <- rep(plots.n, each = sp)
REPS <- rep(wp.reps, each = sp)
spd.output <- data.frame(list(LOCATION = LOCATION, PLOT = PLOT, REP = REPS,
wp = wp.d, sp = sp.d, TREATMENT = NA))
colnames(spd.output) <- c("LOCATION", "PLOT", "REP", "WHOLE-PLOT", "SUB-PLOT", "TRT_COMB")
}else {
PLOT <- rep(plots.n, each = sp)
Block <- rep(rep(1:b, each = wp * sp), times = l)
spd.output <- data.frame(list(LOCATION = LOCATION, PLOT = PLOT, BLOCK = Block,
wp = wp.d, sp = sp.d, TREATMENT = NA))
colnames(spd.output) <- c("LOCATION", "PLOT", "REP", "WHOLE-PLOT", "SUB-PLOT", "TRT_COMB")
}
z <- 1:nrow(spd.output)
for (j in z) {
spd.output[j, ncol(spd.output)] <- paste(spd.output[j, 4:5], collapse = "|")
}
spd_output <- cbind(ID = 1:nrow(spd.output), spd.output)
info.design = list(WholePlots = WholePlots, SubPlots = SubPlots, locationNumber = l,
locationNames = locationNames,
plotNumbers = plot.number,
typeDesign = type,
seed = seed,
idDesign = 5)
output <- list(infoDesign = info.design, layoutlocations = loc.spd.layout,
fieldBook = spd_output)
class(output) <- "FielDHub"
return(invisible(output))
}
|
library(conflicted)
suppressMessages(conflict_prefer("filter", "dplyr"))
suppressPackageStartupMessages(library(tidyverse))
suppressMessages(library(gsubfn))
suppressMessages(library(readxl))
library(sqldf)
CCNI <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Codeine & Comb, non-injectable",
col_names = c("what", "count"), skip = 1)
DD <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Drug Dependence",
col_names = c("what", "count"), skip = 1)
MOI <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Morphine-Opium, Injectable",
col_names = c("what", "count"), skip = 1)
MONI <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Morphine-Opium, Non Injectable",
col_names = c("what", "count"), skip = 1)
ORA <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Opioid Rev agts",
col_names = c("what", "count"), skip = 1)
SNI <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Synth Narcotic, Injectable",
col_names = c("what", "count"), skip = 1)
SNNI <- read_xlsx(here::here("inst/extdata/IQVIA","Copy of OVERALL_CATEGORIES-4.xlsx"),
sheet = "Synth Narcotic, Non-Injectable",
col_names = c("what", "count"), skip = 1)
everything <- tibble(what = unique(c(CCNI$what, DD$what, MOI$what, MONI$what, ORA$what, SNI$what, SNNI$what)))
iqvia <- read_rds("inst/extdata/IQVIA/iqvia_raw.rds")
parse_iqvia <- DOPE::parse(iqvia$what) %>%
tibble() %>%
distinct()
fill_lookup <- function(x){
if(x %in% c("cd", "dhc", "codeine", "endocet", "hycd", "hydrocodone","hysingla",
"ibudone", "lorcet", "lortab", "nalocet", "norco", "oxaydo",
"oxycodone", "oxycontin", "percocet", "primlev", "roxicodone",
"roxybond", "trezix", "vicodin", "vicoprofen", "xtampza",
"zohydro", "xodol")){
df <- tibble(class = "narcotics (opioids)",
category = "codeine combinations, non-injectable",
synonym = x)
}
else if(x %in% c("acamprosate", "antabuse",
"bunavail" , "buprenex",
"bup/nx", "buprenorphine",
"butrans", "disulfiram",
"naltrexone", "probuphine" ,
"sublocade", "suboxone",
"vivitrol", "zubsolv")){
df <- tibble(class = "treatment drug",
category = "treatment drug",
synonym = x)
}
else if(x %in% c("apap", "fiorinal", "ascomp", "butalb", "asa", "ibuprofen",
"fioricet", "tylenol", "ibuprof")){
df <- tibble(class = "analgesic",
category = "pain relief",
synonym = x)
}
else if(x %in% c("dilaudid", "fentanyl", "hydromorphone", "infumorph", "morphine",
"nalbuphine")){
df <- tibble(class = "narcotics (opioids)",
category = "morphine-opium, injectable",
synonym = x)
}
else if(x %in% c("abstral", "actiq", "arymo", "belbuca", "duragesic",
"embeda", "exalgo","fentora","kadian","lazanda","morphabond",
"opana", "opium","oxymorphone","subsys", "ms")){
df <- tibble(class = "narcotics (opioids)",
category = "morphine-opium, non-injectable",
synonym = x)
}
else if(x %in% c("evzio", "naloxone", "narcan")){
df <- tibble(class = "reversal agent",
category = "reversal agent",
synonym = x)
}
else if(x %in% c("butorphanol", "demerol", "meperidine", "methadone")){
df <- tibble(class = "narcotics (opioids)",
category = "synthetic narcotic, injectable",
synonym = x)
}
else if(x %in% c("conzip", "dolophine", "levorphanol", "methadose",
"nucynta", "pentazocine", "naloxo", "tramadol", "ultracet",
"ultram")){
df <- tibble(class = "narcotics (opioids)",
category = "synthetic narcotic, non-injectable",
synonym = x)
}
else if(x %in% c("caf")){
df <- tibble(class = "diuretic",
category = "caffeine",
synonym = x)
}else{
df <- tibble(class = "WHAT",
category = "WHAT",
synonym = x)
}
df
}
iqvia <- map_dfr(parse_iqvia$., fill_lookup)
usethis::use_data(iqvia, overwrite = TRUE)
|
context("files")
fname <- paste(sample(unlist(strsplit("somecrazyfile", ""))), collapse = "")
test_that("file not found is friendly", {
skip_on_cran()
expect_error(tidync(fname))
})
test_that("files and bad files are handled", {
skip_on_cran()
l3b_file <- system.file("extdata/oceandata/S2008001.L3b_DAY_RRS.nc",
package = "tidync", mustWork = TRUE)
expect_error(suppressWarnings(tidync(l3b_file)),
"no variables or dimensions")
expect_warning(try(tidync(l3b_file), silent = TRUE),
"no dimensions found")
expect_warning(try(tidync(l3b_file), silent = TRUE),
"no variables found")
expect_warning(try(tidync(l3b_file), silent = TRUE),
"no variables recognizable")
f <- "S20080012008031.L3m_MO_CHL_chlor_a_9km.nc"
l3file <- system.file("extdata/oceandata", f,
package= "tidync", mustWork = TRUE)
expect_warning(try(tidync(l3file[c(1, 1)])),
"only one source allowed, first supplied chosen")
tfile <- tempfile()
nothingfile <- RNetCDF::create.nc(tfile)
RNetCDF::close.nc(nothingfile)
expect_warning(ouch <- try(tidync::tidync(tfile), silent = TRUE),
"no dimensions found")
tnc <- tidync(l3file)
tnc$grid <- tnc$grid[0, ]
expect_output(print(tnc))
})
test_that("verbs have a character method", {
skip_on_cran()
f <- "S20080012008031.L3m_MO_CHL_chlor_a_9km.nc"
l3file <- system.file("extdata/oceandata", f,
package= "tidync", mustWork = TRUE)
hyper_tibble(l3file, lon = lon < -140, lat = lat > 85) %>%
expect_s3_class("tbl_df")
hyper_filter(l3file, lon = lon < -140, lat = lat > 85) %>%
expect_s3_class("tidync")
expect_warning(hyper_slice(l3file,
lon = lon < -140,
lat = lat > 85,
select_var = "chlor_a")) %>%
expect_type("list")
expect_silent(hyper_array(l3file, lon = lon < -140, lat = lat > 85,
select_var = "chlor_a")) %>%
expect_type("list")
hyper_tbl_cube(l3file, lon = lon < -140, lat = lat > 85) %>%
expect_s3_class("tbl_cube")
})
test_that("RNetCDF fall back works", {
skip_on_cran()
ufile <- system.file("extdata", "unidata", "madis-hydro.nc",
package = "tidync", mustWork = TRUE)
nc_get(ufile, "invTime") %>% expect_is("array") %>%
expect_length(1176)
nc_get(ufile, "invTime", test = TRUE) %>% expect_is("array") %>%
expect_length(1176)
expect_output({
expect_error(nc_get(ufile, "notavariable"))
expect_error(nc_get(ufile, "notavariable", test = TRUE))
})
})
|
validEstimObject <- function(object){
par <- object@par;
if (length(par) ==4) ansp <- TRUE
else ansp <- "Parameter of length different of 4"
par0 <- object@par0;
if (length(par0) ==4) ansp0 <- TRUE
else ansp0 <- "Initial Parameter of length different of 4"
vcov <- object@vcov;
if (ncol(vcov) ==4 && nrow(vcov)==4) anscov <- TRUE
else anscov <- "covariance matrix of length different of 4x4"
confint <- object@confint;
if (ncol(confint) ==2 && nrow(confint)==4) ansconfint <- TRUE
else ansconfint <- "confidance intervall matrix of length different of 4x2"
if (ansp==TRUE && ansp0==TRUE && anscov==TRUE && ansconfint==TRUE) res <- TRUE
else if (is.character(ansp)) res <- ansp
else if (is.character(ansp0)) res <- ansp0
else if (is.character(anscov)) res <- anscov
else if (is.character(ansconfint)) res <- ansconfint
res
}
setClass(Class="Estim",
representation=representation(
par = "numeric",
par0 = "numeric",
vcov = "matrix",
confint = "matrix",
data = "numeric",
sampleSize = "numeric",
others = "list",
duration = "numeric",
failure = "numeric",
method = "character"),
validity=validEstimObject
)
setMethod("initialize","Estim",
function(.Object,par,par0,vcov,confint,
method,level,others,data,
duration,failure,...){
if (missing(par)) par <- numeric(4)
if (missing(par0)) par0 <- numeric(4)
if (missing(vcov)) vcov <- matrix(nrow=4,ncol=4)
if (missing(confint)) confint <- matrix(nrow=4,ncol=2)
if (missing(data)) data <- numeric(100)
sampleSize <- length(data)
if (missing(method)) method <- "Default"
if (missing(others)) others <- list()
if (missing(level)) level <- 0
if (missing(duration)) duration <- 0
if (missing(failure)) failure <- 0
NameParamsObjects(par)
NameParamsObjects(par0)
NameParamsObjects(vcov)
NameParamsObjects(confint);attr(confint,"level") <- level
callNextMethod(.Object,par=par,par0=par0,vcov=vcov,
confint=confint,data=data,sampleSize=sampleSize,
method=method,others=others,duration=duration,
failure=failure,...)
})
setMethod("show","Estim",
function(object){
cat("*** Class Estim, method Show *** \n")
cat("** Method ** \n")
print(object@method)
cat("** Parameters Estimation ** \n")
print(object@par)
cat("** Covariance Matrix Estimation ** \n")
print(object@vcov)
cat("** Confidence interval Estimation ** \n")
print(paste("Confidence level=",attributes(object@confint)$level))
print(paste("data length=",object@sampleSize))
print(object@confint)
cat("** Estimation time ** \n")
PrintDuration(object@duration)
cat("** Estimation status ** \n")
if(object@failure==0) cat("success")
else cat("failure")
cat("\n ******* End Show (Estim) ******* \n")
}
)
|
"plot.optPar" <-
function(
x,
main=NULL,
which=1,
...
){
if(is.null(main)) main <- deparse(substitute(x))
l<-length(x$best)
if(l==0)l<-1
if(which>l){
warning("The selected (",which,") best solution does not exist!\nOnly ", length(x$best)," best solution(s) exist(s).\nThe first best solution will be ploted.\n")
which<-1
}
plot.mat(x$M,clu=clu(x,which=which),IM=IM(x,which=which),main=main,...)
}
plot.opt.par<-plot.optPar
|
create.ETmain <- function (ecopath, smooth_type = NULL, sigmaLN_cst = NULL, pas = NULL, shift = NULL, smooth_param = NULL)
{
B <- apply(biomass <- Transpose(tab_smooth <- create.smooth(tab_input = ecopath, smooth_type, sigmaLN_cst, pas, shift, smooth_param), ecopath, "biomass"), 1, sum)
B_acc <- apply(biomass_acc <- sweep(biomass, 2, ecopath$accessibility, FUN = "*"), 1, sum)
P <- apply(flowP <- sweep(biomass, 2, ecopath$prod, FUN = "*"), 1, sum)
P_acc <- apply(flowP_acc <- sweep(flowP, 2, ecopath$accessibility, FUN = "*"), 1, sum)
Kin <- P/B
Kin_acc <- P_acc/B_acc
Y <- list()
somme_pecheries <- biomass
somme_pecheries[] <- 0
for (pecheries in colnames(ecopath)[grep("catch", colnames(ecopath))])
{
Y[[paste(pecheries)]] <- Transpose(tab_smooth, ecopath, pecheries)
somme_pecheries <- somme_pecheries + Y[[paste(pecheries)]]
}
Y_tot <- apply(somme_pecheries, 1, sum)
F_loss <- Y_tot/P
F_loss_acc <- Y_tot/P_acc
V <- as.numeric(rownames(biomass))[-1] - as.numeric(rownames(biomass))[-nrow(biomass)]
N_loss <- c(log(P[-length(P)]/P[-1])/V - F_loss[-length(F_loss)], NA)
N_loss[1]=log(P[1]/P[2]*V[2])-F_loss[1]
Fish_mort <- Y_tot/B
Fish_mort_acc <- Fish_mort/(B_acc/B)
Selec <- B_acc/B
Time <- cumsum(c(0, V/Kin[-length(Kin)]))
N_loss_acc <- c(log(P_acc[-length(P_acc)]/P_acc[-1])/V - F_loss_acc[-length(F_loss_acc)], NA)
N_loss_acc[1]=log(P_acc[1]/P_acc[2]*V[2])-F_loss_acc[1]
ET_Main <- cbind(B, B_acc, P, P_acc, Kin, Kin_acc, Y_tot, F_loss, F_loss_acc, N_loss, Fish_mort, Fish_mort_acc, Selec, Time, N_loss_acc)
retour<-list(ET_Main = as.data.frame(ET_Main), biomass = biomass, biomass_acc = biomass_acc, prod = flowP, prod_acc = flowP_acc, tab_smooth = tab_smooth,Y=Y)
class(retour)<-"ETmain"
return(retour)
}
|
DrawArrow <- function(x,y,r,angle=pi/4,cex,open=FALSE,lwd=1,lty=1,col="black")
{
r <- r%%(2*pi)
xrange <- abs(diff(par("usr")[1:2]))
yrange <- abs(diff(par("usr")[3:4]))
xmarrange <- sum(par("mai")[c(2,4)])
ymarrange <- sum(par("mai")[c(1,3)])
xin <- par("pin")[1]
yin <- par("pin")[2]
xLeft <- x + ((xin+xmarrange)/xin)*(7/(xin+xmarrange))*(xrange/2.16)*cex*par("csi")*sin(r-angle + pi)/17.5
yLeft <- y + ((yin+ymarrange)/yin)*(7/(yin+ymarrange))*(yrange/2.16)*cex*par("csi")*cos(r-angle + pi)/17.5
xRight <- x + ((xin+xmarrange)/xin)*(7/(xin+xmarrange))*(xrange/2.16)*cex*par("csi")*sin(r+angle + pi)/17.5
yRight <- y + ((yin+ymarrange)/yin)*(7/(yin+ymarrange))*(yrange/2.16)*cex*par("csi")*cos(r+angle + pi)/17.5
if (open)
{
lines(c(xLeft,x,xRight),c(yLeft,y,yRight),lwd=lwd,col=col,lty=lty)
} else {
polygon(c(xLeft,x,xRight),c(yLeft,y,yRight),lwd=lwd,col=col,border=NA)
}
}
ArrowMidPoint <- function(x,y,r,angle=pi/4,cex)
{
r <- r%%(2*pi)
xrange <- abs(diff(par("usr")[1:2]))
yrange <- abs(diff(par("usr")[3:4]))
xmarrange <- sum(par("mai")[c(2,4)])
ymarrange <- sum(par("mai")[c(1,3)])
xin <- par("pin")[1]
yin <- par("pin")[2]
xLeft <- x + ((xin+xmarrange)/xin)*(7/(xin+xmarrange))*(xrange/2.16)*cex*par("csi")*sin(r-angle + pi)/17.5
yLeft <- y + ((yin+ymarrange)/yin)*(7/(yin+ymarrange))*(yrange/2.16)*cex*par("csi")*cos(r-angle + pi)/17.5
xRight <- x + ((xin+xmarrange)/xin)*(7/(xin+xmarrange))*(xrange/2.16)*cex*par("csi")*sin(r+angle + pi)/17.5
yRight <- y + ((yin+ymarrange)/yin)*(7/(yin+ymarrange))*(yrange/2.16)*cex*par("csi")*cos(r+angle + pi)/17.5
mids <- c((xRight+xLeft)/2,(yRight+yLeft)/2)
return(mids)
}
ArrowRadIn <- function(angle=pi/4,cex)
{
r <- 0
xrange <- abs(diff(par("usr")[1:2]))
yrange <- abs(diff(par("usr")[3:4]))
xmarrange <- sum(par("mai")[c(2,4)])
ymarrange <- sum(par("mai")[c(1,3)])
xin <- par("pin")[1]
yin <- par("pin")[2]
xLeft <- ((xin+xmarrange)/xin)*(7/(xin+xmarrange))*(xrange/2.16)*cex*par("csi")*sin(r-angle + pi)/17.5
yLeft <- ((yin+ymarrange)/yin)*(7/(yin+ymarrange))*(yrange/2.16)*cex*par("csi")*cos(r-angle + pi)/17.5
xRight <- ((xin+xmarrange)/xin)*(7/(xin+xmarrange))*(xrange/2.16)*cex*par("csi")*sin(r+angle + pi)/17.5
yRight <- ((yin+ymarrange)/yin)*(7/(yin+ymarrange))*(yrange/2.16)*cex*par("csi")*cos(r+angle + pi)/17.5
mids <- c(usr2inX2((xRight+xLeft)/2),usr2inY2((yRight+yLeft)/2))
return(sqrt(sum(mids^2)))
}
|
alpha = 0.003
iter = 500
gradient = function(x) return((4*x^3) - (9*x^2))
set.seed(100)
x = floor(runif(1)*10)
x
x.All = vector("numeric",iter)
?vector
x.All
for(i in 1:iter){
x = x - alpha*gradient(x)
x.All[i] = x
print(x)
}
head(x.All); x
print(paste("The minimum of f(x) is ", x, sep = ""))
layout(1,1)
plot(x.All, type = "l")
|
iso8601chartime2POSIX = function(x,tz){
return(as.POSIXlt(x,format="%Y-%m-%dT%H:%M:%S%z",tz))
}
|
meigen0 <- function( meig, coords0, s_id0 = NULL ){
if( meig$other$model == "other" ){
stop( "meigen0 is not supported for user-specified spatial proximity matrix" )
}
if( !is.null( meig$other$s_id )[ 1 ] ){
if( is.null( s_id0 ) ) {
stop( "s_id0 must be provided" )
} else {
coords0_0 <-coords0
coords0_x<-tapply(coords0[,1],s_id0,mean)
coords0_y<-tapply(coords0[,2],s_id0,mean)
coords0 <-as.matrix(cbind(coords0_x, coords0_y))
s_id2 <-data.frame( s_id=rownames(coords0_x), s_id_num = 1:length(coords0_x) )
s_id_dat<-data.frame( s_id = s_id0, id = 1:length(s_id0))
s_id_dat2<-merge(s_id_dat, s_id2, by="s_id", all.x=TRUE)
s_id_dat2<-s_id_dat2[order(s_id_dat2$id),c("s_id", "s_id_num")]
}
}
if( meig$other$fast == 0 ){
if( !is.null( meig$other$s_id )[ 1 ] ){
sfk <-meig$other$sfk
evk <-meig$ev
coordk<-meig$other$coordk
Cmean <-meig$other$Cmeank
} else {
sfk <- meig$sf
evk <- meig$ev
coordk<- meig$other$coords
Cmean <- meig$other$Cmean
}
} else {
sfk <- meig$other$sfk
evk <- meig$other$evk
coordk <- meig$other$coordk
Cmean <- meig$other$Cmean
}
h <- meig$other$h
nm <- dim( coords0 )[ 1 ]
sfk <- sfk %*% diag( 1 / (evk+1) )
Dk <- rdist( coordk, coords0 )
if( meig$other$model == "exp" ){
sfk <- t( exp( -Dk / h ) - Cmean ) %*% sfk
} else if( meig$other$model == "gau" ){
sfk <- t( exp( - ( Dk / h ) ^ 2 ) - Cmean ) %*% sfk
} else if( meig$other$model == "sph" ){
sfk <- t( ifelse( Dk < h , 1 - 1.5 * ( Dk / h ) + 0.5 * ( Dk / h ) ^ 3, 0 ) - Cmean ) %*% sfk
}
if( !is.null( meig$other$s_id )[ 1 ] ){
sfk <- sfk[ s_id_dat2$s_id_num,]
}
return( list( sf = sfk, ev = meig$ev, ev_full = meig$ev_full ) )
}
|
message("TESTING: Object...")
library("R.oo")
obj <- Object()
print(obj)
obj <- Object(42L)
print(obj)
stopifnot(obj == 42L)
obj$a <- 1:99
print(obj)
fields <- getFields(obj)
print(fields)
hasA <- hasField(obj, "a")
print(hasA)
stopifnot(hasA)
value <- obj$a
str(value)
stopifnot(identical(value, 1:99))
obj$a <- 1:100
print(obj)
value <- obj[["a"]]
str(value)
stopifnot(identical(value, 1:100))
obj[["a"]] <- 1:101
print(obj)
value <- obj[["a"]]
str(value)
stopifnot(identical(value, 1:101))
size <- objectSize(obj)
print(size)
ref <- isReferable(obj)
print(ref)
stopifnot(isTRUE(ref))
time <- getInstantiationTime(obj)
print(time)
res <- attach(obj)
print(res)
stopifnot(exists("a", mode="integer"))
str(a)
res <- tryCatch(attach(obj), warning=function(w) w)
stopifnot(inherits(res, "warning"))
res <- detach(obj)
print(res)
res <- tryCatch(detach(obj), warning=function(w) w)
stopifnot(inherits(res, "warning"))
obj <- Object()
obj$a <- 1
obj$b <- 2
pathnameT <- tempfile()
save(obj, file=pathnameT)
obj2 <- Object$load(pathnameT)
stopifnot(all.equal(getFields(obj2), getFields(obj)))
for (key in getFields(obj)) {
stopifnot(identical(obj2[[key]], obj[[key]]))
}
file.remove(pathnameT)
obj2 <- newInstance(obj, 43L)
print(obj2)
stopifnot(obj2 == 43L)
hash <- hashCode(obj)
print(hash)
stopifnot(length(hash) == 1L)
neq <- equals(obj, 1)
print(neq)
stopifnot(!neq)
eq <- equals(obj, obj)
print(eq)
stopifnot(eq)
obj3 <- clone(obj)
print(obj3)
stopifnot(!identical(obj3, obj))
stopifnot(all.equal(obj3, obj))
message("TESTING: Object...DONE")
|
create_lambda <- function(obj, x_test, group = 0){
nrows <- ifelse(length(attr(obj, "colnames")) == 1, nrow(obj$beta), nrow(obj$beta[[1]]))
ncols <- ifelse(length(attr(obj, "colnames")) == 1, ncol(obj$beta), ncol(obj$beta[[1]]))
res <- matrix(0, nrow = nrows, ncol = ncols)
if (length(attr(obj, "colnames")) == 1) {
res <- obj$beta * x_test[attr(obj, "colnames")]
} else {
lapply(attr(obj, "colnames"), function(nam){
parent <- parent.frame(2)
parent$res <- parent$res + obj$beta[[paste0("beta_", nam)]] * x_test[nam]
})
}
if (!is.null(attr(obj, "group"))) {
res[ ,2:ncol(res)] <- res[ ,2:ncol(res)] + obj$f * obj$phi[, group + 1]
}
exp(res)
}
predict_obs <- function(x_row, obj, ndraws, cens) {
if (!is.null(attr(obj, "group"))) {
group <- x_row[length(x_row)]
} else {
group <- NA
}
lams <- create_lambda(obj, x_row, group)
time_points <- c(0, attr(obj, "S"))
if (max(obj$model$y) != max(attr(obj, "S"))) {
time_points <- c(time_points, max(obj$model$y))
}
U <- diff(time_points)
time_per <- 1:length(U)
par_surv <- matrix(0, nrow = ndraws, ncol = length(U))
selector <- rep(TRUE, ndraws)
for (j in time_per){
if (sum(selector) == 0) break
par_surv[selector, j] <- rexp(sum(selector), lams[selector, j + 1])
selector <- par_surv[,j] > U[j]
if (j < length(U)){
par_surv[selector, j] <- U[j]
} else if (cens == TRUE){
par_surv[selector, j] <- U[j]
}
}
y <- apply(par_surv, 1, sum)
return(y)
}
predict.shrinkDSM <- function(object, newdata, cens = TRUE, ...){
terms <- delete.response(object$model$terms)
m <- model.frame(terms, data = newdata, xlev = object$model$xlevels)
x_test <- model.matrix(terms, m)
if(!is.null(attr(object, "group"))) {
x_test <- cbind(x_test, newdata[, attr(object, "group")])
}
colnames(x_test)[colnames(x_test) == "(Intercept)"] <- "Intercept"
ndraws <- ifelse(length(attr(object, "colnames")) == 1, nrow(object$beta), nrow(object$beta[[1]]))
res <- apply(x_test, 1, function(x) predict_obs(x, object, ndraws, cens))
per_surv <- apply(res, 2, function(y) sum(y >= max(object$model$y))/length(y))
class(res) <- "shrinkDSM_pred"
attr(res, "censored") <- cens
attr(res, "xlim") <- c(min(object$model$y), max(object$model$y))
attr(res, "per_surv") <- per_surv
return(res)
}
plot.shrinkDSM_pred <- function(x, dens_args, legend = TRUE, ...){
assert(!bool_input_bad(legend), "legend has to be a single logical value")
xlim <- attr(x, "xlim")
standard_plot_args <- list(from = xlim[1], to = xlim[2])
if(!missing(dens_args)){
assert(is.list(dens_args), "dens_args has to be a list")
missing_args <- names(standard_plot_args)[!names(standard_plot_args) %in% names(dens_args)]
dens_args[missing_args] <- standard_plot_args[missing_args]
} else{
dens_args <- standard_plot_args
}
dens_args$x <- x[,1]
dens_estim <- list()
dens_estim[[1]] <- do.call(density, dens_args)
if (ncol(x) > 1){
for (i in 2:ncol(x)){
dens_args$x <- x[,i]
dens_estim[[i]] <- do.call(density, dens_args)
}
}
plot_args <- list(...)
standard_plot_args <- list(
ylim = c(0, max(sapply(dens_estim, function(x) max(x$y * 1.1)))),
main = "Predictive Density of Survival Time"
)
missing_args <- names(standard_plot_args)[!names(standard_plot_args) %in% names(plot_args)]
plot_args[missing_args] <- standard_plot_args[missing_args]
plot_args$x <- dens_estim[[1]]
do.call(plot, plot_args)
if (ncol(x) > 1){
for (i in 2:ncol(x)){
lines(dens_estim[[i]], col = i)
}
}
if(legend){
lty <- ifelse("lty" %in% names(plot_args), plot_args$lty, 1)
legend("topright",
legend = paste("Percent survived:", round(attr(x, "per_surv")*100, 2)),
col = 1:ncol(x), lty = lty, bty = "n")
}
}
|
require(timeSeries)
X <- cumulated(LPP2005REC)[, 1:3]
for (i in 1:3) X[, i] <- 100*X[, i]/as.vector(X[1,i])
Data <- alignDailySeries(X)
Index <- time(Data)
tS <- timeSeries(data=Data, charvec=format(Index))
tR <- returns(tS)
open <- function(x) as.vector(x)[1]
close <- function(x) rev(as.vector(x))[1]
high <- function(x) max(x)
low <- function(x) min(x)
spread <- function(x) max(x) - min(x)
by <- timeLastDayInMonth(time(tS))
mean.tR <- aggregate(tR[, "SPI"], by, mean)
sd.tR <- aggregate(tR[, "SPI"], by, sd)
plot(cbind(mean.tR, sd.tR), type="h")
by <- timeLastBizdayInMonth(time(tS), holidays = holidayZURICH())
mean.tR <- aggregate(tR[, "SPI"], by, mean)
sd.tR <- aggregate(tR[, "SPI"], by, sd)
plot(cbind(mean.tR, sd.tR), type="h")
by <- timeSequence(from=start(tD), to=end(tD), by = "week")
mean.tR <- aggregate(tR[, "SPI"], by, mean)
sd.tR <- aggregate(tR[, "SPI"], by, sd)
plot(cbind(mean.tR, sd.tR), type="h")
open <- function(x) as.vector(x)[1]
close <- function(x) rev(as.vector(x))[1]
high <- function(x) max(x)
low <- function(x) min(x)
SPI <- tS[, "SPI"]
by <- timeLastDayInMonth(time(tS))
OHLC <- cbind(
aggregate(SPI, by, open),
aggregate(SPI, by, high),
aggregate(SPI, by, low),
aggregate(SPI, by, close))
OHLC
spread <- function(x) max(x) - min(x)
pspread <- function(x) (max(x) - min(x)) / (0.5 * (max(x) + min(x)))
SPI <- tS[, "SPI"]
by <- timeLastDayInMonth(time(tS))
SPREAD <- cbind(
Points=aggregate(SPI, by, spread),
Percent=100*aggregate(SPI, by, pspread))
SPREAD <- round(SPREAD, 2)
SPREAD
ep <- xts::endpoints(x.xts, on='weeks', k=1)
by1 <- index(x.xts)[ep[-1]]
period1 <- xts::period.apply(x.xts, INDEX=ep, FUN=mean)
FUN <- mean
x <- x.xts
apply.daily(x, FUN)
apply.weekly(x, FUN)
apply.monthly(x, FUN)
apply.quarterly(x, FUN)
apply.yearly(x, FUN)
FUN <- mean
x <- unique(time(x.tS))
alignDaily(x, include.weekends=FALSE)
by1 <- unique(alignMonthly(x, include.weekends=FALSE))
x1 <- timeSeries::aggregate(x.tS, by1, FUN)
by2 <- unique(alignMonthly(x, include.weekends=TRUE))
x2 <- timeSeries::aggregate(x.tS, by2, FUN)
by1 <- unique(alignQuarterly(x, include.weekends=FALSE))
x1 <- timeSeries::aggregate(x.tS, by1, FUN)
by2 <- unique(alignQuarterly(x, include.weekends=TRUE))
x2 <- timeSeries::aggregate(x.tS, by2, FUN)
cbind(x1,x2)
xts::first(x.xts)
xts::last(x.xts)
first2 <- function(x) x[start(x), ]
last2 <- function(x) x[end(x), ]
first2(x.tS)
last2(x.tS)
INDEX <- seq(1, nrow(xts), by=21)
INDEX
.period.apply(tS, INDEX, FUN=max)
.period.max <- function(x, INDEX, FUN=max) .period.apply(x, INDEX, max)
.period.max(tS[, 1], INDEX)
.period.min <- function(x, INDEX) .period.apply(x, INDEX, min)
.period.min(tS[, 1], INDEX)
xts::period.apply(xts[, 1], INDEX, FUN=max)
xts::period.max(xts[, 1], INDEX)
xts::period.min(xts[, 1], INDEX)
xts::period.prod(xts[, 1], INDEX)
xts::period.sum(xts[, 1], INDEX)
is.timeBased <-
function (x)
{
if (!any(sapply(c(
"Date", "POSIXt", "chron", "dates", "times",
"timeDate", "yearmon", "yearqtr", "xtime"),
function(xx) inherits(x, xx))))
{
ans <- FALSE
} else {
ans <- TRUE
}
ans
}
timeBased <- function(x) { is.timeBased(x) }
alignDaily(x=time(tS), include.weekends=FALSE)
alignMonthly(x=time(tS), include.weekends=FALSE)
alignQuarterly(x=time(tS), include.weekends=FALSE)
tD <- Sys.timeDate() + 1:1000
timeDate::align(tD, by="10s")
timeDate::align(tD, by="60s")
timeDate::align(tD, by="10m")
td <- as.xts(Sys.time()) + 1:1000
xts::align.time(td, n=10)
xts::align.time(td, n=60)
xts::align.time(td, n=10*60)
xts::shift.time(td, n=10)
xts::shift.time(td, n=60)
xts::shift.time(td)
xts::to.minutes(x,k,name,...)
xts::to.minutes3(x,name,...)
xts::to.minutes5(x,name,...)
xts::to.minutes10(x,name,...)
xts::to.minutes15(x,name,...)
xts::to.minutes30(x,name,...)
xts::to.hourly(x,name,...)
xts::to.daily(x,drop.time=TRUE,name,...)
xts::to.weekly(x, drop.time=TRUE, name,...)
xts::to.monthly(x, indexAt='yearmon', drop.time=TRUE,name,...)
xts::to.quarterly(x, indexAt='yearqtr', drop.time=TRUE,name,...)
xts::to.yearly(x,drop.time=TRUE,name,...)
xts::to.period(
x,
period = 'months',
k = 1,
indexAt,
name=NULL,
OHLC = TRUE,
...)
Convert an object to a specified periodicity lower than the given data
object. For example, convert a daily series to a monthly series, or a
monthly series to a yearly one, or a one minute series to an hourly
series.
data(sample_matrix)
xts <- as.xts(sample_matrix)
to.weekly(xts)
to.monthly(xts)
to.quarterly(xts)
to.yearly(xts)
tS <- as.timeSeries(sample_matrix)
% -----------------------------------------------------------------------------
as.numeric(as.POSIXct(time(tS)))
getFinCenter(tS)
indexTZ(xts, )
tzone(xts, )
tzone(xts) <- "GMT"
.index(xts, )
indexClass(xts)
class(time(tS))
% -----------------------------------------------------------------------------
.index <- function(x) as.numeric(as.POSIXct(time(x)))
.indexDate <- function(x) .index(x)%/%86400L
.indexday <- function(x) .index(x)%/%86400L
.indexmday <- function(x) as.POSIXlt(.POSIXct(.index(x)))$mday
.indexwday <- function(x) as.POSIXlt(.POSIXct(.index(x)))$wday
.indexweek <- function(x)
.indexmon <- function(x)
.indexyday <- function(x)
.indexyear <- function(x)
.indexhour <- function(x)
.indexmin <- function(x)
.indexsec <- function(x)
atoms
timeSeries::rollMin(
x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
timeSeries::rollMax(
x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
timeSeries::rollMean(
x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
timeSeries::rollMedian(
x, k, na.pad = FALSE, align = c("center", "left", "right"), ...)
timeSeries::rollStats(
x, k, FUN = mean, na.pad = FALSE, align = c("center", "left", "right"), ...)
rollDailySeries(x, period="7d", FUN, ...)
rollMonthlySeries(x, period="12m", by="1m", FUN, ...)
rollMonthlyWindows(x, period="12m", by="1m")
apply
applySeries
|
knotsWCE <- function(x){x$knotsmat}
|
learnerArgsToControl = function(control, ...) {
args = list()
dots = match.call(expand.dots = FALSE)$...
for (i in seq_along(dots)) {
arg = dots[[i]]
is.missing = if (is.symbol(arg)) {
argname = as.character(arg)
eval(substitute(missing(symbol), list(symbol = arg)),
envir = parent.frame())
} else {
argname = names(dots)[i]
FALSE
}
if (!is.missing) {
value = tryCatch(eval(arg, envir = parent.frame()),
error = function(...) NULL)
if (!is.null(value)) {
args[[as.character(argname)]] = value
}
}
}
do.call(control, args)
}
|
ENAdata <- R6::R6Class("ENAdata", public = list(
initialize = function(
file,
units = NULL,
units.used = NULL,
units.by = NULL,
conversations.by = NULL,
codes = NULL,
model = NULL,
weight.by = "binary",
window.size.back = 1,
window.size.forward = 0,
mask = NULL,
include.meta = T,
...
) {
args <- list(...);
self$function.call <- sys.call(-1);
self$function.params <- list();
private$file <- file;
self$units <- units;
private$units.used <- units.used;
private$units.by <- units.by
private$conversations.by <- conversations.by;
self$codes <- codes;
if (is.data.frame(self$codes)) {
self$codes <- colnames(self$codes);
}
private$weight.by <- weight.by;
private$window.size <- list(
"back" = window.size.back,
"forward" = window.size.forward
);
for (p in c("units", "units.used", "units.by",
"conversations.by", "codes", "model", "weight.by",
"window.size.back", "window.size.forward", "mask",
"in.par", "grainSize", "include.meta")
) {
if (exists(x = p)) {
self$function.params[[p]] <- get(p)
}
else if (!is.null(args[[p]])) {
self$function.params[[p]] <- args[[p]]
}
}
self$model <- model
private$mask <- mask
return(self)
},
model = NULL,
raw = NULL,
adjacency.vectors = NULL,
adjacency.matrix = NULL,
accumulated.adjacency.vectors = NULL,
adjacency.vectors.raw = NULL,
units = NULL,
unit.names = NULL,
metadata = NULL,
trajectories = list(
units = NULL,
step = NULL
),
codes = NULL,
function.call = NULL,
function.params = NULL,
process = function() {
private$loadFile();
},
get = function(x = "data") {
return(private[[x]])
},
add.metadata = function(merge = F) {
meta_avail <- colnames(self$raw)[
-which(colnames(self$raw) %in%
c(self$codes, private$units.by, private$conversations.by))]
meta_avail <- meta_avail[which(meta_avail != "ENA_UNIT")]
meta_cols_to_use <- meta_avail[apply(self$raw[, lapply(.SD, uniqueN),
by = c(private$units.by),
.SDcols = meta_avail
][, c(meta_avail), with = F]
, 2, function(x) all(x == 1))
]
raw.meta <- self$raw[!duplicated(ENA_UNIT)][
ENA_UNIT %in% unique(
self$accumulated.adjacency.vectors$ENA_UNIT
),
c("ENA_UNIT", private$units.by, meta_cols_to_use),
with = F
]
df_to_return <- raw.meta[ENA_UNIT %in% self$unit.names,];
return(df_to_return)
}
),
private = list(
file = NULL,
window.size = NULL,
units.used = NULL,
units.by = NULL,
conversations.by = NULL,
weight.by = NULL,
trajectory.by = NULL,
mask = NULL,
loadFile = function() {
if(any(class(private$file) == "data.table")) {
df_DT <- private$file
} else {
if(any(class(private$file) == "data.frame")) {
df <- private$file
} else {
df <- read.csv(private$file)
}
df_DT <- data.table::as.data.table(df)
}
self$raw <- data.table::copy(df_DT)
self$raw$ENA_UNIT <- merge_columns_c(self$raw, private$units.by)
self <- accumulate.data(self)
self$units <- self$adjacency.vectors[, private$units.by, with = F]
if (!self$model %in% c("AccumulatedTrajectory", "SeparateTrajectory")) {
self$unit.names <- self$adjacency.vectors$ENA_UNIT
} else {
self$trajectories$units <- self$units
conversation <- self$adjacency.vectors[,
private$conversations.by,
with = F
]
self$trajectories$step <- conversation
self$units <- cbind(self$units, conversation)
self$unit.names <- paste(
self$adjacency.vectors$ENA_UNIT,
self$adjacency.vectors$TRAJ_UNIT,
sep = "."
)
}
self$adjacency.vectors.raw <- self$adjacency.vectors
adjCols <- colnames(self$adjacency.vectors)[
grep("adjacency.code", colnames(self$adjacency.vectors))
];
if (is.null(private$mask)) {
private$mask <- matrix(1,
nrow = length(self$codes),
ncol = length(self$codes),
dimnames = list(self$codes, self$codes))
}
self$adjacency.vectors[, c(adjCols)] <-
self$adjacency.vectors[, c(adjCols), with = F] *
rep(
private$mask[upper.tri(private$mask)],
rep(nrow(self$adjacency.vectors), length(adjCols))
)
if( self$function.params$include.meta == T) {
self$metadata <- self$add.metadata(merge = F);
} else {
self$metadata <- data.frame();
}
self$adjacency.vectors <- self$adjacency.vectors[,
grep("adjacency.code",
colnames(self$adjacency.vectors)),
with = F
]
return(self);
}
)
)
|
declareConsts = function() {
testData = list()
testData$N = 10^4
testData$d = 3
testData$mu = rep(0, 3)
testData$Sigma = matrix( c( 1, 0.3, 0.5, 0.3, 1, 0.2, 0.5, 0.2, 1 ), ncol = 3 )
testData$X = MASS::mvrnorm( testData$N, testData$mu, testData$Sigma )
testData$n = 100
testData$data = list( "X" = testData$X )
testData$params = list( "theta" = rnorm( 3, mean = 0, sd = 1 ) )
testData$optStepsize = 1e-5
testData$nIters = 1100
testData$nItersOpt = 1000
testData$burnIn = 100
return( testData )
}
logLik = function( params, data ) {
Sigma = matrix( c( 1, 0.3, 0.5, 0.3, 1, 0.2, 0.5, 0.2, 1 ), ncol = 3 )
Sigma = tf$constant( Sigma, dtype = tf$float32 )
baseDist = tf$distributions$MultivariateNormalFullCovariance( params$theta, Sigma )
return( tf$reduce_sum( baseDist$log_prob( data$X ) ) )
}
logPrior = function( params ) {
baseDist = tf$distributions$Normal( 0, 5 )
return( tf$reduce_sum( baseDist$log_prob( params$theta ) ) )
}
sgldTest = function( testData ) {
stepsize = list( "theta" = 1e-4 )
storage = sgld( logLik, testData$data, testData$params, stepsize, testData$n, logPrior = logPrior, nIters = testData$nIters, verbose = FALSE, seed = 13 )
thetaOut = storage$theta[-c(1:testData$burnIn),]
return( thetaOut )
}
sgldcvTest = function( testData ) {
stepsize = list( "theta" = 1e-4 )
storage = sgldcv( logLik, testData$data, testData$params, stepsize, testData$optStepsize, logPrior = logPrior, minibatchSize = testData$n, nIters = testData$nIters, nItersOpt = testData$nItersOpt, verbose = FALSE, seed = 13 )
thetaOut = storage$theta[-c(1:testData$burnIn),]
return( thetaOut )
}
sghmcTest = function( testData ) {
eta = list( "theta" = 1e-5 )
alpha = list( "theta" = 1e-1 )
L = 3
storage = sghmc( logLik, testData$data, testData$params, eta, logPrior = logPrior, minibatchSize = testData$n, alpha = alpha, L = L, nIters = testData$nIters, verbose = FALSE, seed = 13 )
thetaOut = storage$theta[-c(1:testData$burnIn),]
return( thetaOut )
}
sghmccvTest = function( testData ) {
eta = list( "theta" = 5e-5 )
alpha = list( "theta" = 1e-1 )
L = 3
storage = sghmccv( logLik, testData$data, testData$params, eta, testData$optStepsize, logPrior = logPrior, minibatchSize = testData$n, alpha = alpha, L = L, nIters = testData$nIters, nItersOpt = testData$nItersOpt, verbose = FALSE, seed = 13 )
thetaOut = storage$theta[-c(1:testData$burnIn),]
return( thetaOut )
}
sgnhtTest = function( testData ) {
eta = list( "theta" = 5e-6 )
a = list( "theta" = 1e-2 )
sgnht = list( "theta" = testData$mu )
storage = sgnht( logLik, testData$data, testData$params, eta, logPrior = logPrior, minibatchSize = testData$n, a = a, nIters = testData$nIters, verbose = FALSE, seed = 13 )
thetaOut = storage$theta[-c(1:testData$burnIn),]
return( thetaOut )
}
sgnhtcvTest = function( testData ) {
eta = list( "theta" = 1e-4 )
a = list( "theta" = 1e-2 )
storage = sgnhtcv( logLik, testData$data, testData$params, eta, testData$optStepsize, logPrior = logPrior, minibatchSize = testData$n, a = a, nIters = testData$nIters, nItersOpt = testData$nItersOpt, verbose = FALSE, seed = 13 )
thetaOut = storage$theta[-c(1:testData$burnIn),]
return( thetaOut )
}
test_that( "Check SGLD chain reasonable for 3d Gaussian", {
tryCatch({
tf$constant(c(1, 1))
}, error = function (e) skip("tensorflow not fully built, skipping..."))
testData = declareConsts()
thetaOut = sgldTest( testData )
for ( d in 1:testData$d ) {
expect_gte(min(thetaOut[,d]), -0.5)
expect_lte(max(thetaOut[,d]), 0.5)
expect_lte(mean(thetaOut[,d]^2), 0.1)
}
} )
test_that( "Check SGLDCV chain reasonable for 3d Gaussian", {
tryCatch({
tf$constant(c(1, 1))
}, error = function (e) skip("tensorflow not fully built, skipping..."))
testData = declareConsts()
thetaOut = sgldcvTest( testData )
for ( d in 1:testData$d ) {
expect_gte(min(thetaOut[,d]), -0.5)
expect_lte(max(thetaOut[,d]), 0.5)
expect_lte(mean(thetaOut[,d]^2), 0.1)
}
} )
test_that( "Check SGHMC chain reasonable for 3d Gaussian", {
tryCatch({
tf$constant(c(1, 1))
}, error = function (e) skip("tensorflow not fully built, skipping..."))
testData = declareConsts()
thetaOut = sghmcTest( testData )
for ( d in 1:testData$d ) {
expect_gte(min(thetaOut[,d]), -0.5)
expect_lte(max(thetaOut[,d]), 0.5)
expect_lte(mean(thetaOut[,d]^2), 0.1)
}
} )
test_that( "Check SGHMCCV chain reasonable for 3d Gaussian", {
tryCatch({
tf$constant(c(1, 1))
}, error = function (e) skip("tensorflow not fully built, skipping..."))
testData = declareConsts()
thetaOut = sghmccvTest( testData )
for ( d in 1:testData$d ) {
expect_gte(min(thetaOut[,d]), -0.5)
expect_lte(max(thetaOut[,d]), 0.5)
expect_lte(mean(thetaOut[,d]^2), 0.1)
}
} )
test_that( "Check SGNHT chain reasonable for 3d Gaussian", {
tryCatch({
tf$constant(c(1, 1))
}, error = function (e) skip("tensorflow not fully built, skipping..."))
testData = declareConsts()
thetaOut = sgnhtTest( testData )
for ( d in 1:testData$d ) {
expect_gte(min(thetaOut[,d]), -0.5)
expect_lte(max(thetaOut[,d]), 0.5)
expect_lte(mean(thetaOut[,d]^2), 0.1)
}
} )
test_that( "Check SGNHTCV chain reasonable for 3d Gaussian", {
tryCatch({
tf$constant(c(1, 1))
}, error = function (e) skip("tensorflow not fully built, skipping..."))
testData = declareConsts()
thetaOut = sgnhtcvTest( testData )
for ( d in 1:testData$d ) {
expect_gte(min(thetaOut[,d]), -0.5)
expect_lte(max(thetaOut[,d]), 0.5)
expect_lte(mean(thetaOut[,d]^2), 0.1)
}
} )
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.