code
stringlengths 1
13.8M
|
---|
summary.plmm <-
function(object,...){
var.comp<-object$var.comp
random<-deparse(object$call$random)
names(var.comp)<-c(random, "idiosyncratic")
result<-list(
coefficients=object$coefficients,
var.comp=var.comp,
h.nonpar=object$h.nonpar,
nonpar.df=object$model.df$nonpar,
iter=object$iter,
formula=object$formula,
call=object$call
)
class(result)<-"summary.plmm"
return(result)
}
|
estimateParameters.automap = function(object,...) {
params = getIntamapParams(object$params, ...)
debug.level = params$debug.level
dots = list(...)
observations = object$observations
depVar = as.character(object$formulaString[[2]])
if ("model" %in% names(params)) {
model = params$model
} else {
if (dim(coordinates(object$predictionLocations))[1] > 100000)
model = c("Sph", "Exp", "Gau") else model = c("Sph", "Exp", "Gau", "Ste")
}
if (params$doAnisotropy) {
object = estimateAnisotropy(object)
if (object$anisPar$doRotation && all(as.character(object$formulaString[[3]])=="1")){
objTemp = object
objTemp$observations=rotateAnisotropicData(objTemp$observations,objTemp$anisPar)
afv = autofitVariogram(objTemp$formulaString, objTemp$observations,
verbose = (debug.level >=2), model = model, ...)
vario = afv$var_model
ovar = var(observations[,depVar]@data)
if ((vario$model[2] == "Gau" | (vario$model[2] == "Ste" && vario$kappa[2] > 2))
&& vario$psill[1] <= ovar/1e5 ) vario$psill[1] = ovar/1e5
vario$anis1[2]=1/objTemp$anisPar$ratio
vario$ang1[2]=90-objTemp$anisPar$direction
if (vario$ang1[2] < 0) vario$ang1[2] = vario$ang1[2] + 180
object$variogramModel=vario
} else {
afv = autofitVariogram(object$formulaString,observations,verbose=(debug.level >=2),...)
object$variogramModel = afv$var_model
}
} else {
afv = autofitVariogram(object$formulaString,observations,verbose=(debug.level >=2),...)
object$variogramModel = afv$var_model
}
if (debug.level >=2) print(object$variogramModel)
object$sampleVariogram = afv$exp_var
return(object)
}
spatialPredict.automap = function(object, nsim = 0, ...) {
params = getIntamapParams(object$params, ...)
nmax = params$nmax
nmin = params$nmin
omax = params$omax
beta = params$beta
maxdist = params$maxdist
debug.level = params$debug.level
if (is.null(maxdist)) maxdist = Inf
if (! "variogramModel" %in% names(object)) object = estimateParameters(object,...)
nPred = nrow(coordinates(object$predictionLocations))
if ("nclus" %in% names(params) && nsim == 0 && nPred >= 5000 )
nclus = params$nclus else nclus = 1
if (nclus > 1) {
if (!suppressMessages(suppressWarnings(requireNamespace("doParallel"))))
stop("nclus is > 1, but package doParallel is not available")
cl <- makeCluster(nclus)
registerDoParallel(cl, nclus)
formulaString = object$formulaString
observations = object$observations
predictionLocations = object$predictionLocations
variogramModel = object$variogramModel
splt = sample(1:nclus, nPred, replace = TRUE)
splt = rep(1:nclus, each = ceiling(nPred/nclus), length.out = nPred)
newdlst = lapply(as.list(1:nclus), function(w) predictionLocations[splt == w,])
i = 1
pred <- foreach(i = 1:nclus, .combine = rbind) %dopar% {
gstat::krige(formulaString, observations,
newdlst[[i]], variogramModel, nsim=nsim, nmax = nmax, nmin = nmin, omax = omax,
maxdist = maxdist, beta = beta, debug.level = debug.level)
}
stopCluster(cl)
} else {
pred = krige(object$formulaString, object$observations,
object$predictionLocations, object$variogramModel, nmax = nmax,
nmin = nmin, omax = omax, maxdist = maxdist, beta = beta, debug.level = debug.level)
if (nsim >0) {
pred2 = krige(object$formulaString,object$observations,
object$predictionLocations, object$variogramModel, nsim=nsim, nmax = nmax,
nmin = nmin, omax = omax, maxdist = maxdist, beta = beta, debug.level = debug.level)
pred@data = cbind(pred2@data, pred@data)
}
}
object$predictions = pred
if ("MOK" %in% names(object$outputWhat) | "IWQSEL" %in% names(object$outputWhat))
object$predictions = unbiasedKrige(object, debug.level = debug.level,...)$predictions
object
}
estimateParameters.yamamoto = function(object,...) {
estimateParameters.automap(object,...)
}
spatialPredict.yamamoto = function(object, nsim = 0, ...) {
params = getIntamapParams(object$params, ...)
nmax = params$nmax
nmin = params$nmin
omax = params$omax
beta = params$beta
maxdist = params$maxdist
debug.level = params$debug.level
if (is.null(maxdist)) maxdist = Inf
formulaString = object$formulaString
if (!"variogramModel" %in% names(object)) {
afv = autofitVariogram(object$formulaString,object$observations,object$predictionLocations)
object$variogramModel = afv$var_model
object$sampleVariogram = afv$exp_var
}
predictions = yamamotoKrige(formulaString,object$observations,
object$predictionLocations,object$variogramModel, nsim=nsim, nmax = nmax, maxdist = maxdist, ...)
object$predictions = predictions
if ("MOK" %in% names(object$outputWhat) | "IWQSEL" %in% names(object$outputWhat))
object$predictions = unbiasedKrige(object,debug.level = debug.level,nsim = nsim, nmax = nmax,
nmin = nmin, omax = omax, maxdist = maxdist, beta = beta, ...)$predictions
object
}
|
multinomial <-
function(link="mlogit",base=1) {
linktemp <- substitute(link)
if (!is.character(linktemp)) {
linktemp <- deparse(linktemp)
if (linktemp == "link") {
warning("use of multinomial(link=link) is deprecated\n",
domain = NA)
linktemp <- eval(link)
if (!is.character(linktemp) || length(linktemp) !=1)
stop("'link' is invalid", domain = NA)
}
}
okLinks <- c("mlogit")
if (linktemp %in% okLinks) {
if(linktemp == "mlogit") stats <- mlogit() else stats <- make.link(linktemp)
} else {
if(is.character(link)) {
stats <- make.link(link)
linktemp <- link
} else {
if(inherits(link, "link-glm")) {
stats <- link
if (!is.null(stats$name))
linktemp <- stats$name
} else {
stop(gettextf("link \"%s\" not available for multinomial family; available links are %s",
linktemp, paste(sQuote(okLinks), collapse = ", ")),
domain = NA)
}
}
}
variance <- function(mu) {
n <- length(mu)
v <- diag(n)*outer(mu,1-mu) - (1-diag(n))*outer(mu,-mu)
}
validmu <- function(mu) {
all(mu > 0) && all(mu < 1)
}
dev.resids <- function(y,mu,wt) {
}
initialize <- expression()
structure(list(family = "multinomial", link = linktemp, linkfun = stats$linkfun,
linkinv = stats$linkinv, variance = variance, dev.resids = dev.resids,
mu.eta = stats$mu.eta, initialize = initialize, validmu = validmu, valideta = stats$valideta, base=base),
class = "family")
}
|
par(pty = "s")
z = c(-0.5, -1, 4, -3, 0.5)
v = c(-0.25, 0, 0, 0.4, 0.5)
x = c(-1,1)
plot(x,x, type = "n", xlab = "", ylab = "", axes = FALSE, bty = "n" )
verts = function(K, A, b){
nv = nrow(K)
B = matrix(0,nv,2)
for(i in 1:nv)
B[i,] = solve(A[K[i,],],b[K[i,]])
B
}
M = 1000
A = cbind(1, -c(z,M,M,0,0))
b = c(v,2*M,-2*M,-1.2,1.2)
K = list(
K1 = cbind(c(1,5,6),c(5,6,1)),
K2 = cbind(c(1,2,7),c(2,7,1)),
K3 = cbind(c(3,1,4,8),c(1,4,8,3)),
K4 = cbind(c(4,5,2,6),c(5,2,6,4)),
K5 = cbind(c(3,5,9),c(5,9,3)),
K6 = cbind(c(2,3,4),c(3,4,2)))
for(i in 1:6){
B = verts(K[[i]], A, b)
polygon(B[,2],B[,1], col = "skyblue")
}
Labels = list( expression(L[1]),
expression(L[2]),
expression(L[3]),
expression(L[4]),
expression(L[5]))
loc.Labels = list(x = c(-1.004424, -1.01302343, 0.17934171,
-0.08649861, 1.00436081),
y = c(0.3205637, 0.91636306, 1.00753127,
1.02314035, 0.89690312))
for(i in 1:5)
text(loc.Labels[[1]][i], loc.Labels[[2]][i], labels = Labels[[i]])
Labels = list( expression(P[1]),
expression(P[2]),
expression(P[3]),
expression(P[4]),
expression(P[6]),
expression(P[5]))
loc.Labels = list(x = c(-1.00289155, 1.02002596, 0.06291857,
-0.53817104, 0.54508011, 0.05471212),
y = c(0.11818783, -0.88815825, -0.92915311,
0.94752513, 0.98451957, 0.07552926))
loc.counts = list(x = c(-0.88573936, 0.82733333, 0.11516691,
-0.40868114, 0.09882879, 0.34031147),
y = c(0.12749720, -0.73885324, -0.64723638,
0.74507448, -0.03584664, 0.81743703))
for(i in 1:6){
text(loc.Labels[[1]][i], loc.Labels[[2]][i], labels = Labels[[i]])
text(loc.counts[[1]][i], loc.counts[[2]][i], labels = "3", col = 2)
}
loc.counts = list(x = c(0.2923439, -0.2889679, 0.06056319),
y = c(-0.36331944, 0.04096497, 0.4360896))
for(i in 1:3)
text(loc.counts[[1]][i], loc.counts[[2]][i], labels = "1", col = 2)
loc.counts = list(x = c(0.5650635, -0.5907933, 0.0510295,
-0.8496609, 0.5158996, 0.0536279, -0.09240575),
y = c(-0.7865217, -0.4373644, -0.2191364,
0.4922822, 0.1549019, 0.8226151, 0.2862798))
for(i in 1:7)
text(loc.counts[[1]][i], loc.counts[[2]][i], labels = "2", col = 2)
x = c(-0.95, -0.6, 0.3, -0.2, 0.4)
d = c(-0.07, 0.08, -.3, -0.3, 0.07)
y = v + z*x + d
for(i in 1:5) {
abline(c(v[i], z[i]), col = 1)
x0 = x[i]
y0 = y[i]
a = v[i]
b = z[i]
xhat = (y0*b - a*b + x0)/(1 + b^2)
yhat = a + b*xhat
arrows(xhat, yhat, x0, y0, length = .03, col = 1, lwd = 1.5)
}
|
library("knitr")
knitr::opts_chunk$set(fig.align="center", fig.width=6, fig.height=6)
options(width=90)
library(agridat)
library(desplot)
data(yates.oats)
if(is.element("x",names(yates.oats)))
yates.oats <- transform(yates.oats, col=x, row=y)
desplot(yates.oats, block ~ col+row,
col=nitro, text=gen, cex=1, out1=block,
out2=gen, out2.gpar=list(col = "gray50", lwd = 1, lty = 1))
library(agridat)
library(desplot)
data(ryder.groundnut)
gnut <- ryder.groundnut
m1 <- lm(dry ~ block + gen, gnut)
gnut$res <- resid(m1)
desplot(gnut, res ~ col + row, text=gen, cex=1,
main="ryder.groundnut residuals from RCB model")
|
getLastChildTaxon <- function(level = c("order","suborder","greatgroup")) {
lvls <- c("order","suborder","greatgroup")
level <- match.arg(level, lvls)
level.idx <- match(level, lvls)
ST_unique_list <- NULL
load(system.file("data/ST_unique_list.rda", package = "SoilTaxonomy")[1])
suborders <- taxon_to_taxon_code(ST_unique_list[[level]])
ggposition <- relative_taxon_code_position(taxon_to_taxon_code(ST_unique_list[[lvls[level.idx + 1]]]))
res <- lapply(suborders, function(so) {
x <- ggposition[grep(paste0("^", so), names(ggposition))]
names(x[which.max(x)])
})
codes <- taxon_to_taxon_code(as.character(res))
data.frame(
key = names(res),
taxon = taxon_code_to_taxon(as.character(res)),
code = as.character(res),
position = relative_taxon_code_position(codes),
row.names = NULL
)
}
|
waas <- function(.data,
env,
gen,
rep,
resp,
block = NULL,
mresp = NULL,
wresp = NULL,
prob = 0.05,
naxis = NULL,
ind_anova = FALSE,
verbose = TRUE) {
if(is.numeric(mresp)){
stop("Using a numeric vector in 'mresp' is deprecated as of metan 1.9.0. use 'h' or 'l' instead.\nOld code: 'mresp = c(100, 100, 0)'.\nNew code: 'mresp = c(\"h, h, l\")", call. = FALSE)
}
if(!missing(block)){
factors <- .data %>%
select({{env}},
{{gen}},
{{rep}},
{{block}}) %>%
mutate(across(everything(), as.factor))
} else{
factors <- .data %>%
select({{env}},
{{gen}},
{{rep}}) %>%
mutate(across(everything(), as.factor))
}
vars <- .data %>% select({{resp}}, -names(factors))
vars %<>% select_numeric_cols()
if(!missing(block)){
factors %<>% set_names("ENV", "GEN", "REP", "BLOCK")
} else{
factors %<>% set_names("ENV", "GEN", "REP")
}
nvar <- ncol(vars)
if (!is.null(naxis)) {
if (length(naxis) != nvar) {
warning("Invalid length in 'naxis'. Setting naxis = ", naxis[[1]],
" to all the ", nvar, " variables.", call. = FALSE)
naxis <- replicate(nvar, naxis[[1]])
}
}
if (is.null(mresp)) {
mresp <- replicate(nvar, 100)
minresp <- 100 - mresp
} else {
mresp <- unlist(strsplit(mresp, split="\\s*(\\s|,)\\s*")) %>% all_lower_case()
if(!any(mresp %in% c("h", "l", "H", "L"))){
if(!mresp[[1]] %in% c("h", "l")){
stop("Argument 'mresp' must have only h or l.", call. = FALSE)
} else{
warning("Argument 'mresp' must have only h or l. Setting mresp = ", mresp[[1]],
" to all the ", nvar, " variables.", call. = FALSE)
mresp <- replicate(nvar, mresp[[1]])
}
}
if (length(mresp) != nvar) {
warning("Invalid length in 'mresp'. Setting mresp = ", mresp[[1]],
" to all the ", nvar, " variables.", call. = FALSE)
mresp <- replicate(nvar, mresp[[1]])
}
mresp <- ifelse(mresp == "h", 100, 0)
minresp <- 100 - mresp
}
if (is.null(wresp)) {
PesoResp <- replicate(nvar, 50)
PesoWAASB <- 100 - PesoResp
} else {
PesoResp <- wresp
PesoWAASB <- 100 - PesoResp
if (length(wresp) != nvar) {
warning("Invalid length in 'wresp'. Setting wresp = ", wresp[[1]],
" to all the ", nvar, " variables.", call. = FALSE)
PesoResp <- replicate(nvar, wresp[[1]])
PesoWAASB <- 100 - PesoResp
}
if (min(wresp) < 0 | max(wresp) > 100) {
stop("The range of the numeric vector 'wresp' must be equal between 0 and 100.")
}
}
listres <- list()
vin <- 0
for (var in 1:nvar) {
data <- factors %>%
mutate(Y = vars[[var]])
check_labels(data)
if(has_na(data)){
data <- remove_rows_na(data)
has_text_in_num(data)
}
Nenv <- length(unique(data$ENV))
Ngen <- length(unique(data$GEN))
minimo <- min(Nenv, Ngen) - 1
vin <- vin + 1
if(ind_anova == TRUE){
individual <- data %>% anova_ind(ENV, GEN, REP, Y)
} else{
individual = NULL
}
if(missing(block)){
model <- performs_ammi(data, ENV, GEN, REP, Y, verbose = FALSE)[[1]]
} else{
model <- performs_ammi(data, ENV, GEN, REP, Y, block = BLOCK, verbose = FALSE)[[1]]
}
PC <- model$PCA
Escores <- model$model
MeansGxE <- model$MeansGxE
if (is.null(naxis)) {
SigPC1 <- nrow(PC[which(PC[, 6] < prob), ])
} else {
SigPC1 <- naxis[vin]
}
if (SigPC1 > minimo) {
stop("The number of axis to be used must be lesser than or equal to ",
minimo, " [min(GEN-1;ENV-1)]")
} else {
Pesos <- slice(model$PCA[7], 1:SigPC1)
WAAS <-
Escores %>%
select(contains("PC")) %>%
abs() %>%
t() %>%
as.data.frame() %>%
slice(1:SigPC1) %>%
mutate(Percent = Pesos$Proportion)
WAASAbs <- mutate(Escores, WAAS = sapply(WAAS[, -ncol(WAAS)], weighted.mean, w = WAAS$Percent))
if (nvar > 1) {
WAASAbs %<>%
group_by(type) %>%
mutate(PctResp = (mresp[vin] - minresp[vin])/(max(Y) - min(Y)) * (Y - max(Y)) + mresp[vin],
PctWAAS = (0 - 100)/(max(WAAS) - min(WAAS)) * (WAAS - max(WAAS)) + 0,
wRes = PesoResp[vin],
wWAAS = PesoWAASB[vin],
OrResp = rank(-Y),
OrWAAS = rank(WAAS),
OrPC1 = rank(abs(PC1)),
WAASY = ((PctResp * wRes) + (PctWAAS * wWAAS))/(wRes + wWAAS),
OrWAASY = rank(-WAASY)) %>%
ungroup()
} else {
WAASAbs %<>%
group_by(type) %>%
mutate(PctResp = (mresp - minresp)/(max(Y) - min(Y)) * (Y - max(Y)) + mresp,
PctWAAS = (0 - 100)/(max(WAAS) - min(WAAS)) * (WAAS - max(WAAS)) + 0,
wRes = PesoResp,
wWAAS = PesoWAASB,
OrResp = rank(-Y),
OrWAAS = rank(WAAS),
OrPC1 = rank(abs(PC1)),
WAASY = ((PctResp * wRes) + (PctWAAS * wWAAS))/(wRes + wWAAS),
OrWAASY = rank(-WAASY)) %>%
ungroup()
}
min_group <- Escores %>% group_by(type) %>% top_n(1, -Y) %>% select(type, Code, Y) %>% slice(1) %>% as.data.frame()
max_group <- Escores %>% group_by(type) %>% top_n(1, Y) %>% select(type, Code, Y) %>% slice(1) %>% as.data.frame()
min <- MeansGxE %>% top_n(1, -Y) %>% select(ENV, GEN, Y) %>% slice(1)
max <- MeansGxE %>% top_n(1, Y) %>% select(ENV, GEN, Y) %>% slice(1)
Details <-
rbind(ge_details(data, ENV, GEN, Y),
tribble(~Parameters, ~Y,
"wresp", PesoResp[vin],
"mresp", mresp[vin],
"Ngen", Ngen,
"Nenv", Nenv)) %>%
rename(Values = Y)
listres[[paste(names(vars[var]))]] <-
structure(list(individual = individual[[1]],
model = WAASAbs,
MeansGxE = MeansGxE,
PCA = as_tibble(PC, rownames = NA),
ANOVA = model$ANOVA,
Details = Details,
augment = as_tibble(model$augment, rownames = NA),
probint = model$probint),
class = "waas")
if (verbose == TRUE) {
cat("variable", paste(names(vars[var])),"\n")
cat("---------------------------------------------------------------------------\n")
cat("AMMI analysis table\n")
cat("---------------------------------------------------------------------------\n")
print(as.data.frame(model$ANOVA), digits = 3, row.names = FALSE)
cat("---------------------------------------------------------------------------\n\n")
}
}
}
if (verbose == TRUE) {
if (length(which(unlist(lapply(listres, function(x) {
x[["probint"]]
})) > prob)) > 0) {
cat("------------------------------------------------------------\n")
cat("Variables with nonsignificant GxE interaction\n")
cat(names(which(unlist(lapply(listres, function(x) {
x[["probint"]]
})) > prob)), "\n")
cat("------------------------------------------------------------\n")
} else {
cat("All variables with significant (p < 0.05) genotype-vs-environment interaction\n")
}
cat("Done!\n")
}
invisible(structure(listres, class = "waas"))
}
plot.waas <- function(x, ...) {
residual_plots(x, ...)
}
print.waas <- function(x, export = FALSE, file.name = NULL, digits = 4, ...) {
if (!class(x) == "waas") {
stop("The object must be of class 'waas'")
}
if (export == TRUE) {
file.name <- ifelse(is.null(file.name) == TRUE, "waas print", file.name)
sink(paste0(file.name, ".txt"))
}
opar <- options(pillar.sigfig = digits)
on.exit(options(opar))
for (i in 1:length(x)) {
var <- x[[i]]
cat("Variable", names(x)[i], "\n")
cat("---------------------------------------------------------------------------\n")
cat("Individual analysis of variance\n")
cat("---------------------------------------------------------------------------\n")
print(var$individual$individual, ...)
cat("---------------------------------------------------------------------------\n")
cat("AMMI analysis table\n")
cat("---------------------------------------------------------------------------\n")
print(var$ANOVA, ...)
cat("---------------------------------------------------------------------------\n")
cat("Weighted average of the absolute scores\n")
cat("---------------------------------------------------------------------------\n")
print(var$model, ...)
cat("---------------------------------------------------------------------------\n")
cat("Some information regarding the analysis\n")
cat("---------------------------------------------------------------------------\n")
print(var$Details, ...)
cat("\n\n\n")
}
if (export == TRUE) {
sink()
}
}
predict.waas <- function(object, naxis = 2, ...) {
cal <- match.call()
if (class(object) != "waas") {
stop("The objectin must be an objectin of the class 'waas'")
}
if (length(object) != length(naxis)) {
warning("Invalid length in 'naxis'. Setting 'mresp = ", naxis[[1]],
"' to all the ", length(object), " variables.", call. = FALSE)
naxis <- replicate(length(object), naxis[[1]])
}
listres <- list()
varin <- 1
for (var in 1:length(object)) {
objectin <- object[[var]]
MEDIAS <- objectin$MeansGxE %>% select(ENV, GEN, Y)
Nenv <- length(unique(MEDIAS$ENV))
Ngen <- length(unique(MEDIAS$GEN))
minimo <- min(Nenv, Ngen) - 1
if (naxis[var] > minimo) {
stop("The number of axis to be used must be lesser than or equal to min(GEN-1;ENV-1), in this case, ",
minimo, ".", call. = FALSE)
} else {
if (naxis[var] == 0) {
warning("Predicted values of AMMI0 model are in colum 'pred_ols'.", call. = FALSE)
}
ovmean <- mean(MEDIAS$Y)
x1 <- model.matrix(~factor(MEDIAS$ENV) - 1)
z1 <- model.matrix(~factor(MEDIAS$GEN) - 1)
modelo1 <- lm(Y ~ ENV + GEN, data = MEDIAS)
MEDIAS <- mutate(MEDIAS, res_ols = residuals(modelo1))
intmatrix <- t(matrix(MEDIAS$res_ols, Nenv, byrow = T))
s <- svd(intmatrix)
U <- s$u[, 1:naxis[var]]
LL <- s$d[1:naxis[var]]
V <- s$v[, 1:naxis[var]]
temp <-
MEDIAS %>%
add_cols(pred_ols = Y - res_ols,
res_ammi = ((z1 %*% U) * (x1 %*% V)) %*% LL,
pred_ammi = pred_ols + res_ammi)
listres[[paste(names(object[var]))]] <- temp
}
}
invisible(listres)
}
|
is.empty.hypergraph <-
function(h)
{
nrow(h$M)==0 || all(h$M==0)
}
|
ChaoPD <-
function(Ps, q = 1, PhyloTree, Normalize = TRUE, Prune = FALSE, CheckArguments = TRUE)
{
if (CheckArguments)
CheckentropartArguments()
if (inherits(PhyloTree, "phylog")) {
hTree <- stats::hclust(PhyloTree$Wdist^2/2, "average")
Tree <- ape::as.phylo.hclust(hTree)
Tree$edge.length <- 2*Tree$edge.length
} else {
if (inherits(PhyloTree, "hclust")) {
Tree <- ape::as.phylo.hclust(PhyloTree)
Tree$edge.length <- 2*Tree$edge.length
} else {
if (inherits(PhyloTree, "phylo")) {
Tree <- PhyloTree
} else {
if (inherits(PhyloTree, "PPtree")) {
Tree <- PhyloTree$phyTree
} else {
stop("Tree must be an object of class phylo, phylog, hclust or PPtree")
}
}
}
}
if (is.null(names(Ps)))
stop("Ps must be named to match the tree's species")
SpeciesNotFound <- setdiff(names(Ps), Tree$tip.label)
if (length(SpeciesNotFound) > 0) {
stop(paste("Species not found in the tree: ", SpeciesNotFound, collapse = "; "))
print(SpeciesNotFound)
}
SpeciesNotFound <- setdiff(Tree$tip.label, names(Ps))
if (length(SpeciesNotFound) > 0 ){
if (Prune) {
Tree <- ape::drop.tip(Tree, SpeciesNotFound)
} else {
ExtraPs <- rep(0, length(SpeciesNotFound))
names(ExtraPs) <- SpeciesNotFound
Ps <- c(Ps, ExtraPs)
}
}
Lengths <- Tree$edge.length
ltips <- lapply(Tree$edge[, 2], function(node) tips(Tree, node))
Branches <- unlist(lapply(ltips, function(VectorOfTips) sum(Ps[VectorOfTips])))
Tbar <- sum(Lengths*Branches)
Lengths <- Lengths/Tbar
Lengths <- Lengths[Branches != 0]
Branches <- Branches[Branches != 0]
if (q == 1) {
PD <- prod(Branches^(-Lengths*Branches))*ifelse(Normalize, 1, Tbar)
} else {
PD <- (sum(Lengths*Branches^q))^(1/(1-q))*ifelse(Normalize, 1, Tbar)
}
names(PD) <- "None"
return (PD)
}
|
plotKIN<- function(estObj, scaler = 1, alpha = 0.3, title = "", xlab = "x", ylab = "y"){
requireNamespace("maptools")
if(!inherits(estObj$estObj, "estObj"))
stop("estObj must be of class estObj created from estEllipse, estKIN, or estMCP functions!")
if(!inherits(scaler, "numeric"))
stop("scaler must be numeric!")
if(!inherits(alpha, "numeric"))
stop("alpha must be numeric!")
if(alpha > 1 | alpha < 0)
stop("alpha must be a numeric value between 0 and 1!")
if(!inherits(title, "character"))
stop("title must be a character!")
if( !inherits(xlab, "character"))
if(!inherits(xlab, "expression"))
stop("xlab must be a character or an expression!")
if(!inherits(ylab, "character"))
if(!inherits(ylab, "expression"))
stop("ylab must be a character or an expression!")
ord<- unique(estObj$estObj[[1]]@data$ConfInt)[order(unique(estObj$estObj[[1]]@data$ConfInt), decreasing = TRUE)]
xs<- numeric()
ys<- numeric()
df<- list()
for(i in 1:length(estObj$estObj)){
xs<- c(xs, sp::bbox(estObj$estObj[[i]])[1, ])
ys<- c(ys, sp::bbox(estObj$estObj[[i]])[2, ])
for(j in 1:length(ord)){
estObj$estObj[[i]]@data$PlotOrder[estObj$estObj[[i]]@data$ConfInt==ord[j]]<- j
}
gdf<- ggplot2::fortify(estObj$estObj[[i]], region = "PlotOrder")
gdf<- merge(gdf, estObj$estObj[[i]]@data, by.x = "id", by.y = "PlotOrder")
gdf$Group_ConfInt<- paste(gdf$Group, gdf$ConfInt, sep = "_")
df<- c(df, list(gdf))
}
pts<- list()
for(i in 1:length(estObj$estInput)){
pts<- c(pts, list(estObj$estInput[[i]]@data))
xs<- c(xs, estObj$estInput[[i]]@data[ , 3])
ys<- c(ys, estObj$estInput[[i]]@data[ , 4])
}
kin.plot<- ggplot2::ggplot() +
lapply(df, function(x) ggplot2::geom_polygon(data = x, alpha = alpha, ggplot2::aes_string(x = "long", y = "lat", fill = "Group_ConfInt", group = "group"))) +
ggplot2::scale_fill_manual(values=getColors(length(df), length(ord))) +
lapply(pts, function(x) ggplot2::geom_point(data = x, ggplot2::aes_string(x = names(x)[3], y = names(x)[4], colour = "Group", shape = "Group"))) +
ggplot2::scale_color_manual(values = getColors(length(df), 1)) +
ggplot2::coord_fixed(ratio = ((max(xs) + scaler) - (min(xs) - scaler))/((max(ys) + scaler) - (min(ys) - scaler)),
xlim = c((min(xs) - scaler), (max(xs) + scaler)),
ylim = c((min(ys) - scaler), (max(ys) + scaler))) +
ggplot2::scale_x_continuous(breaks = seq(from = round((min(xs) - scaler)), to = round((max(xs) + scaler)), by = scaler)) +
ggplot2::scale_y_continuous(breaks = seq(from = round((min(ys) - scaler)), to = round((max(ys) + scaler)), by = scaler)) +
ggplot2::labs(title = title, x = xlab, y = ylab) +
ggplot2::guides(colour = ggplot2::guide_legend(override.aes = list(alpha = alpha))) +
ggplot2::theme_bw() +
ggplot2::theme(panel.background = ggplot2::element_blank(),
panel.grid.major = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.border= ggplot2::element_rect(fill = NA, color = "black"),
plot.title = element_text(hjust = 0.5))
return(kin.plot)
}
|
plot.fast <- function (x, choix = "ind", axes = c(1, 2), xlim = NULL, ylim = NULL,
invisible = NULL, col.ind = "blue", col.var = "red", col.quali.sup = "darkred",
col.ind.sup = "darkblue", col.quanti.sup = "black", label = "all",
cex = 1, lab.grpe = TRUE, title = NULL, habillage = "none",
palette = NULL, new.plot = TRUE, ...)
{
res.mca <- x
if (!inherits(res.mca, "fast"))
stop("non convenient data")
if (is.null(palette))
palette(c("black", "red", "green3", "blue", "cyan", "magenta",
"darkgray", "darkgoldenrod", "darkgreen", "violet",
"turquoise", "orange", "lightpink", "lavender", "yellow",
"lightgreen", "lightgrey", "lightblue", "darkkhaki",
"darkmagenta", "darkolivegreen", "lightcyan", "darkorange",
"darkorchid", "darkred", "darksalmon", "darkseagreen",
"darkslateblue", "darkslategray", "darkslategrey",
"darkturquoise", "darkviolet", "lightgray", "lightsalmon",
"lightyellow", "maroon"))
lab.ind <- lab.var <- lab.quali.sup <- lab.ind.sup <- FALSE
if (length(label) == 1 && label == "all")
lab.ind <- lab.var <- lab.quali.sup <- lab.ind.sup <- TRUE
if ("ind" %in% label)
lab.ind <- TRUE
if ("var" %in% label)
lab.var <- TRUE
test.invisible <- vector(length = 5)
if (!is.null(invisible)) {
test.invisible[1] <- match("ind", invisible)
test.invisible[2] <- match("var", invisible)
}
else test.invisible <- rep(NA, 5)
coord.var <- res.mca$var$coord[, axes]
coord.ind <- res.mca$ind$coord[, axes]
if (is.null(xlim)) {
xmin <- xmax <- 0
if (is.na(test.invisible[1]))
xmin <- min(xmin, coord.ind[, 1])
if (is.na(test.invisible[1]))
xmax <- max(xmax, coord.ind[, 1])
if (is.na(test.invisible[2]))
xmin <- min(xmin, coord.var[, 1])
if (is.na(test.invisible[2]))
xmax <- max(xmax, coord.var[, 1])
xlim <- c(xmin, xmax) * 1.2
}
else {
xmin = xlim[1]
xmax = xlim[2]
}
if (is.null(ylim)) {
ymin <- ymax <- 0
if (is.na(test.invisible[1]))
ymin <- min(ymin, coord.ind[, 2])
if (is.na(test.invisible[1]))
ymax <- max(ymax, coord.ind[, 2])
if (is.na(test.invisible[2]))
ymin <- min(ymin, coord.var[, 2])
if (is.na(test.invisible[2]))
ymax <- max(ymax, coord.var[, 2])
ylim <- c(ymin, ymax) * 1.2
}
else {
ymin = ylim[1]
ymax = ylim[2]
}
if (habillage == "quali") {
aux = 1
col.var = NULL
for (j in res.mca$call$quali) {
col.var <- c(col.var, rep(aux, nlevels(res.mca$call$X[,
j])))
aux = aux + 1
}
}
if ((habillage != "none") & (habillage != "quali")) {
if (!is.factor(res.mca$call$X[, habillage]))
stop("The variable ", habillage, " is not qualitative")
col.ind <- as.numeric(as.factor(res.mca$call$X[, habillage]))
n.mod <- nlevels(as.factor(res.mca$call$X[, habillage]))
}
if (choix == "ind" | choix == "var") {
sub.titre <- NULL
titre = title
if (is.null(title))
titre <- "SortingTask factor map"
else sub.titre <- "SortingTask factor map"
if (is.na(test.invisible[1]) | is.na(test.invisible[2]) |
is.na(test.invisible[4]) | is.na(test.invisible[5])) {
if (new.plot & (!nzchar(Sys.getenv("RSTUDIO_USER_IDENTITY")))) dev.new()
plot(0, 0, main = titre, xlab = paste("Dim ", axes[1],
" (", signif(res.mca$eig[axes[1], 2], 4), "%)",
sep = ""), ylab = paste("Dim ", axes[2], " (",
signif(res.mca$eig[axes[2], 2], 4), "%)", sep = ""),
xlim = xlim, ylim = ylim, col = "white", asp = 1,
cex = cex)
if (!is.null(sub.titre))
title(sub = sub.titre, cex.sub = cex, font.sub = 2,
col.sub = "steelblue4", adj = 0, line = 3.8)
abline(v = 0, lty = 2, cex = cex)
abline(h = 0, lty = 2, cex = cex)
if (is.na(test.invisible[1])) {
points(coord.ind, pch = 16, col = col.ind)
if (lab.ind)
text(coord.ind[, 1], y = coord.ind[, 2], labels = rownames(coord.ind),
pos = 3, col = col.ind, cex = cex)
}
if (is.na(test.invisible[2])) {
points(coord.var[, 1], y = coord.var[, 2], pch = 17,
col = col.var, cex = cex)
if (lab.var)
text(coord.var[, 1], y = coord.var[, 2], labels = rownames(coord.var),
pos = 3, col = col.var, cex = cex)
if ((habillage != "none") & (habillage != "quali") &
(is.na(test.invisible[1]) | is.na(test.invisible[2])))
legend("topleft", legend = levels(res.mca$call$X[,
habillage]), text.col = 1:n.mod, cex = 0.8)
}
}
}
group = nrow(res.mca$group$coord)
if (choix == "group") {
if (new.plot & (!nzchar(Sys.getenv("RSTUDIO_USER_IDENTITY")))) dev.new()
if (is.null(title))
title <- "Consumers representation"
else sub.title <- "Consumers representation"
coord.actif <- res.mca$group$coord[, axes]
plot(coord.actif, xlab = paste("Dim ", axes[1], " (",
signif(res.mca$eig[axes[1], 2], 4), "%)", sep = ""),
ylab = paste("Dim ", axes[2], " (", signif(res.mca$eig[axes[2],
2], 4), "%)", sep = ""), xlim = c(0, 1), ylim = c(0,
1), pch = 17, cex = cex, main = title, cex.main = cex *
1.2, asp = 1)
title(cex.sub = cex, font.sub = 2, col.sub = "steelblue4",
adj = 0, line = 3.8)
if (lab.grpe)
text(coord.actif[, 1], y = coord.actif[, 2], labels = rownames(coord.actif),
pos = 3)
}
}
|
get_y <- function(x, resp = NULL, sort = FALSE, warn = FALSE, ...) {
stopifnot(is.brmsfit(x))
resp <- validate_resp(resp, x)
sort <- as_one_logical(sort)
warn <- as_one_logical(warn)
args <- list(x, resp = resp, ...)
args$re_formula <- NA
args$check_response <- TRUE
args$only_response <- TRUE
args$internal <- TRUE
sdata <- do_call(standata, args)
if (warn) {
if (any(paste0("cens", usc(resp)) %in% names(sdata))) {
warning2("Results may not be meaningful for censored models.")
}
}
Ynames <- paste0("Y", usc(resp))
if (length(Ynames) > 1L) {
out <- do_call(cbind, sdata[Ynames])
colnames(out) <- resp
} else {
out <- sdata[[Ynames]]
}
old_order <- attr(sdata, "old_order")
if (!is.null(old_order) && !sort) {
stopifnot(length(old_order) == NROW(out))
out <- p(out, old_order)
}
out
}
data_response <- function(x, ...) {
UseMethod("data_response")
}
data_response.mvbrmsterms <- function(x, basis = NULL, ...) {
out <- list()
for (i in seq_along(x$terms)) {
bs <- basis$resps[[x$responses[i]]]
c(out) <- data_response(x$terms[[i]], basis = bs, ...)
}
if (x$rescor) {
out$nresp <- length(x$responses)
out$nrescor <- out$nresp * (out$nresp - 1) / 2
}
out
}
data_response.brmsterms <- function(x, data, check_response = TRUE,
internal = FALSE, basis = NULL, ...) {
data <- subset_data(data, x)
N <- nrow(data)
Y <- model.response(model.frame(x$respform, data, na.action = na.pass))
out <- list(N = N, Y = unname(Y))
if (is_binary(x$family) || is_categorical(x$family)) {
out$Y <- as_factor(out$Y, levels = basis$resp_levels)
out$Y <- as.numeric(out$Y)
if (is_binary(x$family)) {
out$Y <- out$Y - 1
}
}
if (is_ordinal(x$family) && is.ordered(out$Y)) {
out$Y <- as.numeric(out$Y)
}
if (check_response) {
family4error <- family_names(x$family)
if (is.mixfamily(x$family)) {
family4error <- paste0(family4error, collapse = ", ")
family4error <- paste0("mixture(", family4error, ")")
}
if (!allow_factors(x$family) && !is.numeric(out$Y)) {
stop2("Family '", family4error, "' requires numeric responses.")
}
if (is_binary(x$family)) {
if (any(!out$Y %in% c(0, 1))) {
stop2("Family '", family4error, "' requires responses ",
"to contain only two different values.")
}
}
if (is_ordinal(x$family)) {
if (any(!is_wholenumber(out$Y)) || any(!out$Y > 0)) {
stop2("Family '", family4error, "' requires either positive ",
"integers or ordered factors as responses.")
}
}
if (use_int(x$family)) {
if (!all(is_wholenumber(out$Y))) {
stop2("Family '", family4error, "' requires integer responses.")
}
}
if (has_multicol(x$family)) {
if (!is.matrix(out$Y)) {
stop2("This model requires a response matrix.")
}
}
if (is_dirichlet(x$family)) {
if (!is_equal(rowSums(out$Y), rep(1, nrow(out$Y)))) {
stop2("Response values in dirichlet models must sum to 1.")
}
}
ybounds <- family_info(x$family, "ybounds")
closed <- family_info(x$family, "closed")
if (is.finite(ybounds[1])) {
y_min <- min(out$Y, na.rm = TRUE)
if (closed[1] && y_min < ybounds[1]) {
stop2("Family '", family4error, "' requires response greater ",
"than or equal to ", ybounds[1], ".")
} else if (!closed[1] && y_min <= ybounds[1]) {
stop2("Family '", family4error, "' requires response greater ",
"than ", round(ybounds[1], 2), ".")
}
}
if (is.finite(ybounds[2])) {
y_max <- max(out$Y, na.rm = TRUE)
if (closed[2] && y_max > ybounds[2]) {
stop2("Family '", family4error, "' requires response smaller ",
"than or equal to ", ybounds[2], ".")
} else if (!closed[2] && y_max >= ybounds[2]) {
stop2("Family '", family4error, "' requires response smaller ",
"than ", round(ybounds[2], 2), ".")
}
}
out$Y <- as.array(out$Y)
}
if (has_trials(x$family) || is.formula(x$adforms$trials)) {
if (!length(x$adforms$trials)) {
if (is_multinomial(x$family)) {
stop2("Specifying 'trials' is required in multinomial models.")
}
trials <- round(max(out$Y, na.rm = TRUE))
if (isTRUE(is.finite(trials))) {
message("Using the maximum response value as the number of trials.")
warning2(
"Using 'binomial' families without specifying 'trials' ",
"on the left-hand side of the model formula is deprecated."
)
} else if (!is.null(basis$trials)) {
trials <- max(basis$trials)
} else {
stop2("Could not compute the number of trials.")
}
} else if (is.formula(x$adforms$trials)) {
trials <- get_ad_values(x, "trials", "trials", data)
if (!is.numeric(trials)) {
stop2("Number of trials must be numeric.")
}
if (any(!is_wholenumber(trials) | trials < 0)) {
stop2("Number of trials must be non-negative integers.")
}
} else {
stop2("Argument 'trials' is misspecified.")
}
if (length(trials) == 1L) {
trials <- rep(trials, nrow(data))
}
if (check_response) {
if (is_multinomial(x$family)) {
if (!is_equal(rowSums(out$Y), trials)) {
stop2("Number of trials does not match the number of events.")
}
} else if (has_trials(x$family)) {
if (max(trials) == 1L && !internal) {
message("Only 2 levels detected so that family 'bernoulli' ",
"might be a more efficient choice.")
}
if (any(out$Y > trials)) {
stop2("Number of trials is smaller than the number of events.")
}
}
}
out$trials <- as.array(trials)
}
if (has_cat(x$family)) {
ncat <- length(get_cats(x$family))
if (min(ncat) < 2L) {
stop2("At least two response categories are required.")
}
if (!has_multicol(x$family)) {
if (ncat == 2L && !internal) {
message("Only 2 levels detected so that family 'bernoulli' ",
"might be a more efficient choice.")
}
if (check_response && any(out$Y > ncat)) {
stop2("Number of categories is smaller than the response ",
"variable would suggest.")
}
}
out$ncat <- ncat
}
if (has_thres(x$family)) {
thres <- family_info(x, "thres")
if (has_thres_groups(x$family)) {
groups <- get_thres_groups(x)
out$ngrthres <- length(groups)
grthres <- get_ad_values(x, "thres", "gr", data)
grthres <- factor(rename(grthres), levels = groups)
Jgrthres <- match(grthres, groups)
nthres <- as.array(rep(NA, length(groups)))
for (i in seq_along(groups)) {
nthres[i] <- max(subset2(thres, group = groups[i])$thres)
}
if (check_response && any(out$Y > nthres[Jgrthres] + 1)) {
stop2("Number of thresholds is smaller than required by the response.")
}
Kthres_cumsum <- cumsum(nthres)
Kthres_start <- c(1, Kthres_cumsum[-length(nthres)] + 1)
Kthres_end <- Kthres_cumsum
Jthres <- cbind(Kthres_start, Kthres_end)[Jgrthres, , drop = FALSE]
out$Jthres <- Jthres
} else {
nthres <- max(thres$thres)
if (check_response && any(out$Y > nthres + 1)) {
stop2("Number of thresholds is smaller than required by the response.")
}
}
if (max(nthres) == 1L && !internal) {
message("Only 2 levels detected so that family 'bernoulli' ",
"might be a more efficient choice.")
}
out$nthres <- nthres
}
if (is.formula(x$adforms$cat)) {
warning2("Addition argument 'cat' is deprecated. Use 'thres' instead. ",
"See ?brmsformula for more details.")
}
if (is.formula(x$adforms$se)) {
se <- get_ad_values(x, "se", "se", data)
if (!is.numeric(se)) {
stop2("Standard errors must be numeric.")
}
if (min(se) < 0) {
stop2("Standard errors must be non-negative.")
}
out$se <- as.array(se)
}
if (is.formula(x$adforms$weights)) {
weights <- get_ad_values(x, "weights", "weights", data)
if (!is.numeric(weights)) {
stop2("Weights must be numeric.")
}
if (min(weights) < 0) {
stop2("Weights must be non-negative.")
}
if (get_ad_flag(x, "weights", "scale")) {
weights <- weights / sum(weights) * length(weights)
}
out$weights <- as.array(weights)
}
if (is.formula(x$adforms$dec)) {
dec <- get_ad_values(x, "dec", "dec", data)
if (is.character(dec) || is.factor(dec)) {
if (!all(unique(dec) %in% c("lower", "upper"))) {
stop2("Decisions should be 'lower' or 'upper' ",
"when supplied as characters or factors.")
}
dec <- ifelse(dec == "lower", 0, 1)
} else {
dec <- as.numeric(as.logical(dec))
}
out$dec <- as.array(dec)
}
if (is.formula(x$adforms$rate)) {
denom <- get_ad_values(x, "rate", "denom", data)
if (!is.numeric(denom)) {
stop2("Rate denomiators should be numeric.")
}
if (isTRUE(any(denom <= 0))) {
stop2("Rate denomiators should be positive.")
}
out$denom <- as.array(denom)
}
if (is.formula(x$adforms$cens) && check_response) {
cens <- get_ad_values(x, "cens", "cens", data)
cens <- prepare_cens(cens)
if (!all(is_wholenumber(cens) & cens %in% -1:2)) {
stop2(
"Invalid censoring data. Accepted values are ",
"'left', 'none', 'right', and 'interval'\n",
"(abbreviations are allowed) or -1, 0, 1, and 2.\n",
"TRUE and FALSE are also accepted ",
"and refer to 'right' and 'none' respectively."
)
}
out$cens <- as.array(cens)
icens <- cens %in% 2
if (any(icens)) {
y2 <- unname(get_ad_values(x, "cens", "y2", data))
if (is.null(y2)) {
stop2("Argument 'y2' is required for interval censored data.")
}
if (anyNA(y2[icens])) {
stop2("'y2' should not be NA for interval censored observations.")
}
if (any(out$Y[icens] >= y2[icens])) {
stop2("Left censor points must be smaller than right ",
"censor points for interval censored data.")
}
y2[!icens] <- 0
out$rcens <- as.array(y2)
}
}
if (is.formula(x$adforms$trunc)) {
lb <- as.numeric(get_ad_values(x, "trunc", "lb", data))
ub <- as.numeric(get_ad_values(x, "trunc", "ub", data))
if (any(lb >= ub)) {
stop2("Truncation bounds are invalid: lb >= ub")
}
if (length(lb) == 1L) {
lb <- rep(lb, N)
}
if (length(ub) == 1L) {
ub <- rep(ub, N)
}
if (length(lb) != N || length(ub) != N) {
stop2("Invalid truncation bounds.")
}
inv_bounds <- out$Y < lb | out$Y > ub
if (check_response && isTRUE(any(inv_bounds))) {
stop2("Some responses are outside of the truncation bounds.")
}
out$lb <- lb
out$ub <- ub
}
if (is.formula(x$adforms$mi)) {
sdy <- get_sdy(x, data)
if (is.null(sdy)) {
which_mi <- which(is.na(out$Y))
out$Jmi <- as.array(which_mi)
out$Nmi <- length(out$Jmi)
} else {
if (length(sdy) == 1L) {
sdy <- rep(sdy, length(out$Y))
}
if (length(sdy) != length(out$Y)) {
stop2("'sdy' must have the same length as the response.")
}
which_mi <- which(is.na(out$Y) | is.infinite(sdy))
out$Jme <- as.array(setdiff(seq_along(out$Y), which_mi))
out$Nme <- length(out$Jme)
out$noise <- as.array(sdy)
if (!internal) {
out$noise[which_mi] <- Inf
}
}
tbounds <- trunc_bounds(x, data, incl_family = TRUE)
out$lbmi <- tbounds$lb
out$ubmi <- tbounds$ub
if (!internal) {
out$Y[which_mi] <- Inf
}
}
if (is.formula(x$adforms$vreal)) {
vreal <- eval_rhs(x$adforms$vreal)
vreal <- lapply(vreal$vars, eval2, data)
names(vreal) <- paste0("vreal", seq_along(vreal))
for (i in seq_along(vreal)) {
if (length(vreal[[i]]) == 1L) {
vreal[[i]] <- rep(vreal[[i]], N)
}
vreal[[i]] <- as.array(as.numeric(vreal[[i]]))
}
c(out) <- vreal
}
if (is.formula(x$adforms$vint)) {
vint <- eval_rhs(x$adforms$vint)
vint <- lapply(vint$vars, eval2, data)
names(vint) <- paste0("vint", seq_along(vint))
for (i in seq_along(vint)) {
if (length(vint[[i]]) == 1L) {
vint[[i]] <- rep(vint[[i]], N)
}
if (!all(is_wholenumber(vint[[i]]))) {
stop2("'vint' requires whole numbers as input.")
}
vint[[i]] <- as.array(vint[[i]])
}
c(out) <- vint
}
if (length(out)) {
resp <- usc(combine_prefix(x))
out <- setNames(out, paste0(names(out), resp))
}
out
}
data_mixture <- function(bterms, data2, prior) {
stopifnot(is.brmsterms(bterms))
out <- list()
if (is.mixfamily(bterms$family)) {
families <- family_names(bterms$family)
dp_classes <- dpar_class(names(c(bterms$dpars, bterms$fdpars)))
if (!any(dp_classes %in% "theta")) {
take <- find_rows(prior, class = "theta", resp = bterms$resp)
theta_prior <- prior$prior[take]
con_theta <- eval_dirichlet(theta_prior, length(families), data2)
out$con_theta <- as.array(con_theta)
p <- usc(combine_prefix(bterms))
names(out) <- paste0(names(out), p)
}
}
out
}
data_bhaz <- function(bterms, data, data2, prior, basis = NULL) {
out <- list()
if (!is_cox(bterms$family)) {
return(out)
}
y <- model.response(model.frame(bterms$respform, data, na.action = na.pass))
args <- bterms$family$bhaz
bs <- basis$basis_matrix
out$Zbhaz <- bhaz_basis_matrix(y, args, basis = bs)
out$Zcbhaz <- bhaz_basis_matrix(y, args, integrate = TRUE, basis = bs)
out$Kbhaz <- NCOL(out$Zbhaz)
sbhaz_prior <- subset2(prior, class = "sbhaz", resp = bterms$resp)
con_sbhaz <- eval_dirichlet(sbhaz_prior$prior, out$Kbhaz, data2)
out$con_sbhaz <- as.array(con_sbhaz)
out
}
bhaz_basis_matrix <- function(y, args = list(), integrate = FALSE,
basis = NULL) {
require_package("splines2")
if (!is.null(basis)) {
stopifnot(inherits(basis, "mSpline"))
if (integrate) {
class(basis) <- c("matrix", "iSpline")
}
return(predict(basis, y))
}
stopifnot(is.list(args))
args$x <- y
if (!is.null(args$intercept)) {
args$intercept <- as_one_logical(args$intercept)
}
if (is.null(args$Boundary.knots)) {
min_y <- min(y, na.rm = TRUE)
max_y <- max(y, na.rm = TRUE)
diff_y <- max_y - min_y
lower_knot <- max(min_y - diff_y / 50, 0)
upper_knot <- max_y + diff_y / 50
args$Boundary.knots <- c(lower_knot, upper_knot)
}
if (integrate) {
out <- do_call(splines2::iSpline, args)
} else {
out <- do_call(splines2::mSpline, args)
}
out
}
extract_cat_names <- function(x, data) {
stopifnot(is.brmsformula(x) || is.brmsterms(x))
respform <- validate_resp_formula(x$formula)
mr <- model.response(model.frame(respform, data))
if (has_multicol(x)) {
mr <- as.matrix(mr)
out <- as.character(colnames(mr))
if (!length(out)) {
out <- as.character(seq_cols(mr))
}
} else {
out <- levels(factor(mr))
}
out
}
extract_thres_names <- function(x, data) {
stopifnot(is.brmsformula(x) || is.brmsterms(x), has_thres(x))
if (is.null(x$adforms)) {
x$adforms <- terms_ad(x$formula, x$family)
}
nthres <- get_ad_values(x, "thres", "thres", data)
if (any(!is_wholenumber(nthres) | nthres < 1L)) {
stop2("Number of thresholds must be a positive integer.")
}
grthres <- get_ad_values(x, "thres", "gr", data)
if (!is.null(grthres)) {
if (!is_like_factor(grthres)) {
stop2("Variable 'gr' in 'thres' needs to be factor-like.")
}
grthres <- factor(grthres)
group <- levels(grthres)
if (!length(nthres)) {
nthres <- rep(NA, length(group))
for (i in seq_along(group)) {
take <- grthres %in% group[i]
nthres[i] <- extract_nthres(x$formula, data[take, , drop = FALSE])
}
} else if (length(nthres) == 1L) {
nthres <- rep(nthres, length(group))
} else {
for (i in seq_along(group)) {
take <- grthres %in% group[i]
if (length(unique(nthres[take])) > 1L) {
stop2("Number of thresholds should be unique for each group.")
}
}
nthres <- get_one_value_per_group(nthres, grthres)
}
group <- rep(rename(group), nthres)
thres <- ulapply(unname(nthres), seq_len)
} else {
group <- ""
if (!length(nthres)) {
nthres <- extract_nthres(x$formula, data)
}
if (length(nthres) > 1L) {
stop2("Number of thresholds needs to be a single value.")
}
thres <- seq_len(nthres)
}
data.frame(thres, group, stringsAsFactors = FALSE)
}
extract_nthres <- function(formula, data) {
respform <- validate_resp_formula(formula)
mr <- model.response(model.frame(respform, data))
if (is_like_factor(mr)) {
out <- length(levels(factor(mr))) - 1
} else {
out <- max(mr) - 1
}
out
}
|
head(Wetsuits, 3)
dotPlot(~ Wetsuit, xlim = c(1.1, 1.8), cex = .25, data = Wetsuits)
dotPlot(~ NoWetsuit, xlim = c(1.1, 1.8), cex = .25, data = Wetsuits)
|
.guessSeparator <- function(str){
SEPARATORS <- c(space = " " , equal = "=", semicolon = ";",
coma = ",", colon = ":", tab = "\t")
guess <- which.min(
nchar(lapply(stringr::str_split(str,SEPARATORS), "[", i = 1)))
separator <- SEPARATORS[guess]
return(separator)
}
.parseNumericVector <- function(str) {
vec <- as.numeric(unlist(
stringr::str_split(
stringr::str_squish(stringr::str_remove_all(str, "[\\(\\)\\[\\]\\{\\}]")),
.guessSeparator(str))))
if (length(vec) == 1) vec <- rep(vec, 3)
names(vec) <- c("x", "y", "z")
return(vec)
}
readVoxelSpace <- function(f){
vox <- new(Class=("VoxelSpace"))
conn <- file(f, open="r")
firstLine <- readLines(conn, n=1)
stopifnot(
!is.na(stringr::str_match(stringr::str_trim(firstLine), "^VOXEL SPACE$")))
vox@file <- f
parameters <- NULL
nLineHeader <- 0
while ( TRUE ) {
line <- stringr::str_squish(readLines(conn, n = 1))
nLineHeader <- nLineHeader + 1
if ( stringr::str_starts(line, "
lineSplit <- stringr::str_squish(stringr::str_split(line, "
lineParam <- vapply(lineSplit,
function(p) unlist(stringr::str_split(p, ":")),
character(2))
colnames(lineParam) <- as.character(lineParam[1,])
parameters <- c(parameters, lineParam[-1,])
} else {
break
}
}
close(conn)
vox@header@nline <- as.integer(nLineHeader)
columnNames <- unlist(stringr::str_split(line, " "))
vox@header@columnNames <- columnNames
vox@header@mincorner <- .parseNumericVector(parameters["min_corner"])
vox@header@maxcorner <- .parseNumericVector(parameters["max_corner"])
vox@header@split <- .parseNumericVector(parameters["split"])
vox@header@resolution <- .parseNumericVector(parameters["res"])
vox@header@parameters <- parameters
vox@voxels <- data.table::fread(f, header = TRUE, skip = nLineHeader)
return (vox)
}
showVoxelSpace <- function(voxelSpace) {
cat(class(voxelSpace)[1],'\n')
cat(" file", voxelSpace@file, sep='\t', '\n')
writeLines(paste0(" ",
paste(names(voxelSpace@header@parameters),
voxelSpace@header@parameters,
sep='\t')))
cat(" output variables",
paste(voxelSpace@header@columnNames, collapse=", "),
'\n',
sep='\t')
show(voxelSpace@voxels)
}
|
expected <- eval(parse(text="7L"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE), .Dim = c(101L, 3L), .Dimnames = list(NULL, c(\"t1\", \"10 * t1\", \"t1 - 4\")), .Tsp = c(1, 101, 1), class = c(\"mts\", \"ts\", \"matrix\")))"));
do.call(`sum`, argv);
}, o=expected);
|
NULL
add_file_ref_class <- function(x) {
class(x) <- "boxr_file_reference"
x
}
add_folder_ref_class <- function(x) {
class(x) <- "boxr_folder_reference"
x
}
print.boxr_file_reference <- function(x, ...) {
cat("\nbox.com remote file reference\n\n")
cat(" name :", x$name, "\n")
if(x$description != "")
cat(" description :", x$description, "\n")
cat(" file id :", x$id, "\n")
cat(" version :", paste0("V", as.numeric(x$etag) + 1), "\n")
cat(" size :", format_bytes(x$size), "\n")
cat(" modified at :",
as.character(as.POSIXct(gsub("T", " ", x$modified_at))), "\n"
)
cat(" created at :",
as.character(as.POSIXct(gsub("T", " ", x$modified_at))), "\n"
)
cat(" uploaded by :", x$modified_by$login, "\n")
cat(" owned by :", x$owned_by$login, "\n")
shared_link <- x$shared_link
if (is.null(shared_link))
shared_link <- "None"
cat(" shared link :", shared_link, "\n\n")
cat(" parent folder name : ", x$parent$name, "\n")
cat(" parent folder id : ", x$parent$id, "\n")
invisible(x)
}
print.boxr_folder_reference <- function(x, ...) {
cat("\nbox.com remote folder reference\n\n")
cat(" name :", x$name, "\n")
cat(" dir id :", x$id, "\n")
cat(" size :", format_bytes(x$size), "\n")
cat(" modified at :",
as.character(as.POSIXct(gsub("T", " ", x$modified_at))), "\n"
)
cat(" created at :",
as.character(as.POSIXct(gsub("T", " ", x$modified_at))), "\n"
)
cat(" uploaded by :", x$modified_by$login, "\n")
cat(" owned by :", x$owned_by$login, "\n")
shared_link <- x$shared_link
if (is.null(shared_link))
shared_link <- "None"
cat(" shared link :", shared_link, "\n\n")
cat(" parent folder name : ", x$parent$name, "\n")
cat(" parent folder id : ", x$parent$id, "\n")
invisible(x)
}
as.data.frame.boxr_object_list <- function(x, ...) {
summarise_row <- function(x) {
path <- paste0(unlist(
lapply(x$path_collection$entries, function(x) x$name)
), collapse = "/")
data.frame(
name = x$name,
type = x$type,
id = x$id,
size = x$size %|0|% NA_integer_,
description = x$description,
owner = x$owned_by$login,
path = path,
modified_at = box_datetime(x$modified_at),
content_modified_at = box_datetime(x$content_modified_at) %|0|% as.POSIXct(NA),
sha1 = x$sha1 %|0|% NA_character_,
version = as.numeric(x$etag) + 1,
version_no = as.numeric(x$etag) + 1,
version_id = x$file_version$id %|0|% NA_character_,
stringsAsFactors = FALSE
)
}
out <- data.frame(dplyr::bind_rows(lapply(x, summarise_row)))
return(out)
}
print.boxr_object_list <- function(x, ...) {
df <- as.data.frame.boxr_object_list(x)
if (nrow(df) < 1) {
cat("\nbox.com remote object list: Empty (no objects returned)")
return(df)
}
df <- df[1:min(nrow(df), 10),]
if (all(df$description == ""))
df$description <- NULL
if(!is.null(df$description))
df$description <- trunc_end(df$description)
df$path <- trunc_start(df$path)
df$size <- purrr::map_chr(df$size, purrr::possibly(format_bytes, NA))
cat(paste0("\nbox.com remote object list (", length(x), " objects)\n\n"))
cat(paste0(" Summary of first ", nrow(df), ":\n\n"))
print(df[, 1:5])
cat("\n\nUse as.data.frame() to extract full results.\n")
invisible(x)
}
print.boxr_dir_wide_operation_result <- function(x, ...) {
boxr_timediff <- function(x)
paste0("took ", format(unclass(x), digits = 3), " ", attr(x, "units"))
f <- x$file_list
tdif <- boxr_timediff(x$end - x$start)
cat("\nboxr", x$operation, "operation\n\n")
cat(paste0(
" User : ", getOption("boxr.username"), "\n",
" Local dir : ", x$local_tld, "\n",
" box.com folder : ", x$box_tld_id, "\n",
" started at : ", x$start , " (", tdif, ")", "\n",
"\n"
))
summarise_ops(x$file_list, x$msg_list)
cat("Use summary() to see individual file operations.")
invisible(x)
}
summary.boxr_dir_wide_operation_result <- function(object, ...) {
boxr_timediff <- function(x)
paste0("took ", format(unclass(x), digits = 3), " ", attr(x, "units"))
f <- object$file_list
tdif <- boxr_timediff(object$end - object$start)
cat("\nboxr", object$operation, "operation\n\n")
cat(paste0(
" User : ", getOption("boxr.username"), "\n",
" Local dir : ", object$local_tld, "\n",
" box.com folder : ", object$box_tld_id, "\n",
" started at : ", object$start , " (", tdif, ")", "\n",
"\n"
))
if (!is.null(object$file_list[[17]]) && nrow(object$file_list[[17]]) > 0)
object$file_list[[17]][,1] <- dir_id_tidy(object$file_list[[17]][,1])
print_df_summary(object$file_list, object$msg_list)
invisible(object)
}
print.boxr_dir_comparison <- function(x, ...) {
cat("\nboxr remote:local directory comparison\n\n")
origin <- if (x$call_info$load == "up") "Local directory" else "box.com"
destin <- if (x$call_info$load != "up") "Local directory" else "box.com"
cat(paste0(
" User : ", getOption("boxr.username"), "\n",
" Local dir : ", x$call_info$local_dir, "\n",
" box.com folder : ", x$call_info$dir_id, "\n",
" Direction : ", x$call_info$load, "load", "\n",
" Origin : ", origin, "\n",
" Destination : ", destin, "\n",
"\n"
))
object_list <- x[names(x) != "call_info"]
summarise_ops(object_list, x$call_info$msg)
cat("Use summary() to see individual files.")
invisible(x)
}
summary.boxr_dir_comparison <- function(object, ...) {
cat("\nboxr remote:local directory comparison\n\n")
origin <- if (object$call_info$load == "up") "Local directory" else "box.com"
destin <- if (object$call_info$load != "up") "Local directory" else "box.com"
cat(paste0(
" User : ", getOption("boxr.username"), "\n",
" Local dir : ", object$call_info$local_dir, "\n",
" box.com folder : ", object$call_info$dir_id, "\n",
" Direction : ", object$call_info$load, "load", "\n",
" Origin : ", origin, "\n",
" Destination : ", destin, "\n",
"\n"
))
if (!is.null(object$file_list[[17]]) && nrow(object$file_list[[17]]) > 0)
object$file_list[[17]][,1] <- dir_id_tidy(object$file_list[[17]][,1])
object_list <- object[names(object) != "call_info"]
print_df_summary(object_list, object$call_info$msg)
invisible(object)
}
as_tibble.boxr_collab <- function(x, ...) {
stack_row_tbl(x)
}
as.data.frame.boxr_collab <- function(x, ...) {
stack_row_df(x)
}
print.boxr_collab <- function(x, ...) {
print_dispatch(x, ...)
}
as_tibble.boxr_collab_list <- function(x, ...) {
stack_rows_tbl(x)
}
as.data.frame.boxr_collab_list <- function(x, ...) {
stack_rows_df(x)
}
print.boxr_collab_list <- function(x, ...) {
print_dispatch(x, ...)
}
as_tibble.boxr_comment <- function(x, ...) {
stack_row_tbl(x)
}
as.data.frame.boxr_comment <- function(x, ...) {
stack_row_df(x)
}
print.boxr_comment<- function(x, ...) {
print_dispatch(x, ...)
}
as.data.frame.boxr_comment_list <- function(x, ...) {
stack_rows_df(x)
}
as_tibble.boxr_comment_list <- function(x, ...) {
stack_rows_tbl(x)
}
print.boxr_comment_list <- function(x, ...) {
print_dispatch(x, ...);
}
mutate_version_list <- function(x) {
if (is_void(x)) {
return(invisible(NULL))
}
x[["modified_at"]] <- box_datetime(x[["modified_at"]])
x[["created_at"]] <- box_datetime(x[["created_at"]])
x <- x[order(x[["modified_at"]]), ]
colnames(x)[colnames(x) == "id"] <- "version_id"
x[["type"]] <- NULL
col_names <- colnames(x)
x[["version_no"]] <- seq_along(x$version_id) + 1L
x <- x[ ,c("version_no", col_names)]
rownames(x) <- NULL
x
}
as.data.frame.boxr_version_list <- function(x, ...) {
x <- stack_rows_df(x)
x <- mutate_version_list(x)
x
}
as_tibble.boxr_version_list <- function(x, ...) {
x <- stack_rows_tbl(x)
x <- mutate_version_list(x)
x
}
print.boxr_version_list <- function(x, ...) {
print_dispatch(x, ...);
}
grep_tense <- function(msg, n) {
grepTense <- function(msg, n) {
if(is.na(n) || is.null(n) || n > 1) {
return(msg)
}
msg <- gsub("files", "file", msg)
msg <- gsub("directories", "directory", msg)
msg <- gsub("were", "was", msg)
return(msg)
}
mapply(grepTense, msg, n)
}
summarise_ops <- function(file_list, msg_list) {
op_summaries <- unlist(mapply(
function(x, msg) {
if (nrow(x) > 0L) paste(nrow(x), grep_tense(msg, nrow(x)))
},
file_list, msg_list
))
cat(paste0(
paste(op_summaries[!is.null(op_summaries)], collapse = ", "),
".\n\n"
))
}
print_df_summary <- function(file_list, msg_list) {
print_df <- function(x, msg) {
if (nrow(x) > 0) {
cat(nrow(x), msg, ":\n")
print(
format(
data.frame(
" " = x[,grepl("full_path",colnames(x))],
check.names = FALSE
),
justify = "left"
),
row.names = FALSE
)
cat("\n\n")
}
}
dummy_var <- mapply(print_df, file_list, msg_list)
}
print_dispatch <- function(x, ...) {
has_tibble <- requireNamespace("tibble", quietly = TRUE)
print_tibble <- getOption("boxr.print_tibble") %||% FALSE
if (has_tibble && print_tibble) {
print_using_tibble(x, ...)
} else {
print_using_df(x, ...)
}
invisible(x)
}
print_using_df <- function(x, ...) {
has_tibble <- requireNamespace("tibble", quietly = TRUE)
df <- as.data.frame(x)
cat("--- printing as data.frame ---\n")
print(df, max = 10 * ncol(df), ...)
cat("\n")
if (has_tibble) {
cat("Use `as.data.frame()` or `as_tibble()` to extract full results.\n")
} else {
cat("Use `as.data.frame()` to extract full results.\n")
}
invisible(x)
}
print_using_tibble <- function(x, ...) {
tbl <- as_tibble(x)
cat("--- printing as tibble ---\n")
print(tbl, ...)
cat("\n")
cat("Use `as_tibble()` or `as.data.frame()` to extract full results.\n")
invisible(x)
}
|
context("mosaic")
if(!any(grepl("R_CHECK_TIMINGS", names(Sys.getenv())))) {
test_that("results are consistent with affinity()", {
basis(c("CO2", "H2O", "NH3", "O2"), c(0, 0, 0, 0))
species(c("alanine", "glycine"))
a25 <- affinity()
m1_25 <- mosaic(list("NH3", "CO2"))
expect_equal(a25$values, m1_25$A.species$values)
m2_25 <- mosaic(list("NH3", "CO2"), blend = FALSE)
expect_equal(a25$values, m2_25$A.species$values)
a500 <- suppressWarnings(affinity(T=500))
m1_500 <- suppressWarnings(mosaic(list("NH3", "CO2"), T=500))
expect_equal(a500$values, m1_500$A.species$values)
m2_500 <- suppressWarnings(mosaic(list("NH3", "CO2"), blend = FALSE, T=500))
expect_equal(a500$values, m2_500$A.species$values)
})
test_that("blend=TRUE produces reasonable values", {
basis(c("FeO", "SO4-2", "H2O", "H+", "e-"))
basis("SO4-2", -6)
basis("Eh", -0.15)
species(c("hematite", "magnetite"))
bases <- c("SO4-2", "HSO4-", "HS-", "H2S")
pH <- c(0, 14, 29)
m1 <- mosaic(bases, pH = pH, blend = FALSE)
m2 <- mosaic(bases, pH = pH)
expect_equivalent(m2$A.species$values[[1]], m1$A.species$values[[1]])
species(c("pyrrhotite", "pyrite"))
m3 <- mosaic(bases, pH = pH, blend = FALSE)
m4 <- mosaic(bases, pH = pH)
expect_equal(sapply(m3$A.species$values, "[", 13), sapply(m4$A.species$values, "[", 13), tol=1e-1)
expect_equal(sapply(m3$A.species$values, "[", 1), sapply(m4$A.species$values, "[", 1), tol=1e-7)
expect_equal(sapply(m3$A.species$values, "[", 29), sapply(m4$A.species$values, "[", 29), tol=1e-13)
})
test_that("mosaic() - equilibrate() produces equilibrium activities", {
basis(c("CO2", "NH3", "O2", "H2O", "H+"))
species(c("acetamide", "acetic acid", "acetate"))
m <- mosaic(c("NH3", "NH4+"), pH = c(0, 14))
e <- equilibrate(m$A.species)
s1 <- subcrt(c("acetic acid", "NH4+", "acetamide", "water", "H+"), c(-1, -1, 1, 1, 1), T = 25)
logK1 <- s1$out$logK
loga_acetic <- e$loga.equil[[2]]
loga_NH4 <- m$E.bases[[1]]$loga.equil[[2]]
loga_acetamide <- e$loga.equil[[1]]
loga_H2O <- m$E.bases[[1]]$basis$logact[[4]]
loga_Hplus <- - m$E.bases[[1]]$vals$pH
logQ1 <- - loga_acetic - loga_NH4 + loga_acetamide + loga_H2O + loga_Hplus
A1 <- logQ1 - logK1
expect_equivalent(A1, rep(0, length(A1)))
})
test_that("mosaic() - solubility() produces equilibrium activities", {
T <- 250
P <- 500
basis(c("Au", "Cl-", "H2S", "H2O", "oxygen", "H+"))
species(c("Au(HS)2-", "AuHS", "AuOH", "AuCl2-"))
basis("H2S", -2)
basis("O2", -40)
NaCl <- NaCl(T = T, P = P, m_tot = 1)
basis("Cl-", log10(NaCl$m_Cl))
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m <- mosaic(bases, pH = c(2, 10), T = 250, P = 500, IS = NaCl$IS)
s <- solubility(m$A.species)
s1 <- subcrt(c("Au", "H2S", "oxygen", "Au(HS)2-", "H2O", "H+"), c(-1, -2, -0.25, 1, 0.5, 1), T = T, P = P, IS = NaCl$IS)
logK1 <- s1$out$logK
loga_Au <- m$A.bases$basis$logact[[1]]
loga_H2S <- m$E.bases[[1]]$loga.equil[[1]]
logf_O2 <- m$A.bases$basis$logact[[5]]
loga_AuHS2minus <- s$loga.equil[[1]]
loga_H2O <- m$A.bases$basis$logact[[4]]
loga_Hplus <- - m$A.bases$vals$pH
logQ1 <- - 1 * loga_Au - 2 * loga_H2S - 0.25 * logf_O2 + 1 * loga_AuHS2minus + 0.5 * loga_H2O + 1 * loga_Hplus
A1 <- logQ1 - logK1
expect_equivalent(A1, rep(0, length(A1)))
})
test_that("mosaic() - equilibrate() produces equilibrium activities that are consistent with
stability differences of minerals and multiple groups of changing basis species", {
basis(c("FeO", "SO4-2", "H2O", "H+", "e-", "CO3-2"))
basis("SO4-2", -6)
basis("CO3-2", 0)
basis("pH", 6.3)
species(c("pyrrhotite", "pyrite", "hematite", "magnetite", "siderite"))
bases <- list(c("SO4-2", "HSO4-", "HS-", "H2S"),
c("CO3-2", "HCO3-", "CO2"))
m <- mosaic(bases, Eh = c(-0.5, 0))
s1 <- subcrt(c("pyrite", "CO2", "H2O", "H+", "e-", "siderite", "H2S"), c(-1, -1, -1, -2, -2, 1, 2), T = 25)
logK <- s1$out$logK
loga_pyrite <- loga_siderite <- loga_H2O <- 0
loga_Hplus <- m$A.bases[[1]]$basis$logact[[4]]
loga_eminus <- - convert(m$A.bases[[1]]$vals$Eh, "pe")
loga_H2S <- m$E.bases[[1]]$loga.equil[[4]]
loga_CO2 <- m$E.bases[[2]]$loga.equil[[3]]
logQ <- -1 * loga_pyrite - 1 * loga_CO2 - 1 * loga_H2O - 2 * loga_Hplus - 2 * loga_eminus + 1 * loga_siderite + 2 * loga_H2S
A <- logQ - logK
Adiff <- A - (m$A.species$values[[2]] - m$A.species$values[[5]])
expect_equivalent(Adiff, rep(0, length(Adiff)))
})
}
|
library(kedd)
kernel.fun(x = seq(-0.02,0.02,by=0.01), deriv.order = 1, kernel = "gaussian")$kx
kernel.conv(x = seq(-0.02,0.02,by=0.01), deriv.order = 1, kernel = "gaussian")$kx
plot(kernel.fun(deriv.order = 1, kernel = "gaussian"))
plot(kernel.conv(deriv.order = 1, kernel = "gaussian"))
plot(kernel.fun(deriv.order = 1, kernel = "gaussian"),main = "", sub = "")
plot(kernel.conv(deriv.order = 1, kernel = "gaussian"),main = "", sub = "")
fx <- function(x) 0.5 *(-4*x-6)* dnorm(x,-1.5,0.5) + 0.5 *(-4*x+6) * dnorm(x,1.5,0.5)
kernels <- c("gaussian","biweight","triweight","tricube")
plot(dkde(x = bimodal, deriv.order = 1, h = 0.6, kernel = kernels[1]),col = 1,ylim=c(-0.6,0.6) ,sub="", main="")
for (i in 2:length(kernels))lines(dkde(x = bimodal, deriv.order = 1, h = 0.6, kernel = kernels[i] ), col = i)
curve(fx,add=TRUE,lty=8)
legend("topright", legend = c(TRUE,kernels), col = c("black",seq(kernels)),lty = c(8,rep(1,length(kernels))), inset = .015)
h <- c(0.14,0.3,0.6,1.2)
plot(dkde(x = bimodal, deriv.order = 1, h = h[1], kernel = kernels[1]),col = 1,ylim=c(-0.6,1) ,sub="", main="")
for (i in 2:length(h))lines(dkde(x = bimodal, deriv.order = 1, h = h[i], kernel = kernels[1] ), col = i)
curve(fx,add=TRUE,lty=8)
legend("topright", legend = c("TRUE",paste("h =",bquote(.(h)))), col = c("black",seq(h)),lty = c(8,rep(1,length(h))), inset = .015)
hatf <- dkde(bimodal, deriv.order = 0)
hatf1 <- dkde(bimodal, deriv.order = 1)
hatf2 <- dkde(bimodal, deriv.order = 2)
hatf3 <- dkde(bimodal, deriv.order = 3)
fx <- function(x) 0.5 * dnorm(x,-1.5,0.5) + 0.5 * dnorm(x,1.5,0.5)
fx1 <- function(x) 0.5 *(-4*x-6)* dnorm(x,-1.5,0.5) + 0.5 *(-4*x+6) *
dnorm(x,1.5,0.5)
fx2 <- function(x) 0.5 * ((-4*x-6)^2 - 4) * dnorm(x,-1.5,0.5) + 0.5 *
((-4*x+6)^2 - 4) * dnorm(x,1.5,0.5)
fx3 <- function(x) 0.5 * (-4*x-6) * ((-4*x-6)^2 - 12) * dnorm(x,-1.5,0.5) +
0.5 * (-4*x+6) * ((-4*x+6)^2 - 12) * dnorm(x,1.5,0.5)
plot(hatf ,fx = fx)
plot(hatf1,fx = fx1)
plot(hatf2,fx = fx2)
plot(hatf3,fx = fx3)
plot(hatf,fx = fx,lwd=2,sub="",main="")
plot(hatf1,fx = fx1,lwd=2,sub="",main="")
plot(hatf2,fx = fx2,lwd=2,sub="",main="")
plot(hatf3,fx = fx3,lwd=2,sub="",main="")
h.amise(bimodal, deriv.order = 0)
h.amise(bimodal, deriv.order = 1)
h.amise(bimodal, deriv.order = 2)
h.amise(bimodal, deriv.order = 3)
kernels <- eval(formals(h.mlcv.default)$kernel)
hmlcv <- numeric()
for(i in 1:length(kernels))
hmlcv[i] <- h.mlcv(bimodal, kernel = kernels[i])$h
data.frame(kernels,hmlcv)
plot(h.mlcv(bimodal, kernel = kernels[1]), seq.bws = seq(0.1,1,length=50))
plot(h.mlcv(bimodal, kernel = kernels[2]), seq.bws = seq(0.1,1,length=50))
plot(h.mlcv(bimodal, kernel = kernels[1]), seq.bws = seq(0.1,1,length=50),sub="",main="")
plot(h.mlcv(bimodal, kernel = kernels[2]), seq.bws = seq(0.1,1,length=50),sub="",main="")
h.ucv(bimodal, deriv.order = 0)
h.ucv(bimodal, deriv.order = 1)
h.ucv(bimodal, deriv.order = 2)
h.ucv(bimodal, deriv.order = 3)
for (i in 0:3) plot(h.ucv(bimodal, deriv.order = i))
plot(h.ucv(bimodal, deriv.order = 0),sub="",main="")
plot(h.ucv(bimodal, deriv.order = 1),sub="",main="")
plot(h.ucv(bimodal, deriv.order = 2),sub="",main="")
plot(h.ucv(bimodal, deriv.order = 3),sub="",main="")
h.bcv(bimodal, whichbcv = 1, deriv.order = 0)
h.bcv(bimodal, whichbcv = 2, deriv.order = 0)
h.bcv(bimodal, whichbcv = 1, deriv.order = 1, lower=0.1, upper=0.8)
h.bcv(bimodal, whichbcv = 2, deriv.order = 1, lower=0.1, upper=0.8)
plot(h.bcv(bimodal, whichbcv = 2, deriv.order = 0))
lines(h.bcv(bimodal, whichbcv = 1, deriv.order = 0),col="red")
legend("topright", c("BCV1","BCV2"),lty=1,col=c("red","black"),
inset = .015)
plot(h.bcv(bimodal, whichbcv = 2, deriv.order = 1),seq.bws =
seq(0.1,0.8,length=50))
lines(h.bcv(bimodal, whichbcv = 1, deriv.order = 1),col="red")
legend("topright", c("BCV1","BCV2"),lty=1,col=c("red","black"),
inset = .015)
plot(h.bcv(bimodal, whichbcv = 2, deriv.order = 0),sub="",main="")
lines(h.bcv(bimodal, whichbcv = 1, deriv.order = 0),col="red")
legend("topright", c("BCV1","BCV2"),lty=1,col=c("red","black"),inset = .015)
plot(h.bcv(bimodal, whichbcv = 2, deriv.order = 1),seq.bws=seq(0.1,0.8,length=50),sub="",main="")
lines(h.bcv(bimodal, whichbcv = 1, deriv.order = 1),col="red")
legend("topright", c("BCV1","BCV2"),lty=1,col=c("red","black"),inset = .015)
h.ccv(bimodal, deriv.order = 0, upper = 0.5)
h.ccv(bimodal, deriv.order = 1, upper = 0.5)
h.ccv(bimodal, deriv.order = 2, upper = 0.5)
h.ccv(bimodal, deriv.order = 3, upper = 0.5)
for (i in 0:3)
plot(h.ccv(bimodal, deriv.order = i), seq.bws=seq(0.1,0.5,length=50))
plot(h.ccv(bimodal, deriv.order = 0),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
plot(h.ccv(bimodal, deriv.order = 1),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
plot(h.ccv(bimodal, deriv.order = 2),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
plot(h.ccv(bimodal, deriv.order = 3),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
h.mcv(bimodal, deriv.order = 0, upper = 0.5)
h.mcv(bimodal, deriv.order = 1, upper = 0.5)
h.mcv(bimodal, deriv.order = 2, upper = 0.5)
h.mcv(bimodal, deriv.order = 3, upper = 0.5)
for (i in 0:3)
plot(h.mcv(bimodal, deriv.order = i), seq.bws=seq(0.1,0.5,length=50))
plot(h.mcv(bimodal, deriv.order = 0),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
plot(h.mcv(bimodal, deriv.order = 1),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
plot(h.mcv(bimodal, deriv.order = 2),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
plot(h.mcv(bimodal, deriv.order = 3),seq.bws=seq(0.1,0.5,length=50),sub="",main="")
h.tcv(bimodal, deriv.order = 0)
h.tcv(bimodal, deriv.order = 1)
h.tcv(bimodal, deriv.order = 2)
h.tcv(bimodal, deriv.order = 3)
for (i in 0:3) plot(h.tcv(bimodal, deriv.order = i))
plot(h.tcv(bimodal, deriv.order = 0),seq.bws=seq(0.1,1.5,length=50),sub="",main="")
plot(h.tcv(bimodal, deriv.order = 1),seq.bws=seq(0.3,1.5,length=50),sub="",main="")
plot(h.tcv(bimodal, deriv.order = 2),seq.bws=seq(0.5,1.5,length=50),sub="",main="")
plot(h.tcv(bimodal, deriv.order = 3),seq.bws=seq(0.5,1.5,length=50),sub="",main="")
|
dmap <- function(.d, .f, ...) {
deprecate("dmap() is deprecated. Please use the new colwise family in dplyr.\n",
"E.g., summarise_all(), mutate_all(), etc.")
.f <- as_function(.f, ...)
if (dplyr::is.grouped_df(.d)) {
sliced_dmap(.d, .f, ...)
} else {
res <- .Call(map_impl, environment(), ".d", ".f", "list")
dplyr::as_tibble(res)
}
}
sliced_dmap <- function(.d, .f, ...) {
if (length(.d) <= length(group_labels(.d))) {
.d
} else {
set_sliced_env(.d, TRUE, "rows", "", environment(), ".d")
slices <- subset_slices(.d)
.Call(map_by_slice_impl, environment(), ".d", ".f", slices)
}
}
dmap_at <- function(.d, .at, .f, ...) {
deprecate("dmap_at() is deprecated. Please use the new colwise family in dplyr.\n",
"E.g., summarise_at(), mutate_at(), etc.")
sel <- inv_which(.d, .at)
partial_dmap(.d, sel, .f, ...)
}
dmap_if <- function(.d, .p, .f, ...) {
deprecate("dmap_if() is deprecated. Please use the new colwise family in dplyr.\n",
"E.g., summarise_if(), mutate_if(), etc.")
sel <- purrr::map_lgl(.d, .p)
partial_dmap(.d, sel, .f, ...)
}
partial_dmap <- function(.d, .sel, .f, ...) {
.f <- as_function(.f)
subset <- dplyr::select(.d, !!dplyr::group_vars(.d), !!names(.d)[.sel])
set_sliced_env(.d, FALSE, "rows", "", environment(), "slices")
slices <- subset_slices(subset)
res <- .Call(map_by_slice_impl, environment(), "slices", ".f", slices)
res <- dmap_recycle(res, .d)
.d[.sel] <- res
.d
}
dmap_recycle <- function(res, d) {
if (dplyr::is.grouped_df(d)) {
return(dmap_recycle_sliced(res, d))
}
if (!nrow(res) %in% c(0, 1, nrow(d))) {
stop("dmap() only recycles vectors of length 1", call. = TRUE)
}
res
}
dmap_recycle_sliced <- function(res, d) {
if (nrow(res) == nrow(d)) {
return(res)
}
if (nrow(group_labels(d)) == nrow(res)) {
sizes <- group_sizes(d)
indices <- purrr::map2(seq_len(nrow(res)), sizes, ~rep(.x, each = .y))
res <- res[purrr::flatten_int(indices), ]
return(res)
}
stop("dmap() only recycles vectors of length 1")
}
|
Resolvable <-function(n,mat) {
B<-mat
C<-B[n,]
B<-B[-n,]
a<-dim(B)[1]
c<-dim(B)[2]
e<-(c+1)/2
for (j in 1:a) {for (i in 1:c) {if (any (B[j,i]==C)) {B[j,i]<-0}}}
X<-matrix(nrow=a, ncol=e)
for (i in 1:a) {X[i,]<-B[i,][B[i,]>0]}
v <- sort(unique(as.vector(X)))
V<-length(v)
T<-X[1,1]
R<-length(which(T==X))
B<-dim(X)[1]
K<-dim(X)[2]
return(list(V=V,B=B,R=R,K=K,RBIB=X))}
|
"Bolus_1CPT"
|
head(iris)
write.csv(iris, "./data/iris.csv", row.names=F)
write.csv(iris, "./data/irisT.csv", row.names=T)
read1 = read.csv(file="./data/iris.csv", header = TRUE,sep = ",")
read1
read1 = read.csv(file="./data/dhiraj.csv", header = TRUE,sep = ",")
head(read1)
str(read1)
class(read1)
head(read1)
read2 = read.table(file="./data/iris.csv", header = TRUE,sep = ",")
str(read2); class(read2)
head(read2)
read3 = read.delim(file="./data/iris.csv", header = TRUE,sep = ",")
str(read3) ; class(read3)
head(read3)
read4 = read.csv(file=file.choose())
str(read4)
head(read4)
read_web1 = read.csv('http://www.stats.ox.ac.uk/pub/datasets/csb/ch11b.dat')
head(read_web1)
library(data.table)
read_web2 = fread("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(read_web2)
class(read_web2)
read_txt = read.table("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/test.txt", header = FALSE)
head(read_txt)
library(gsheet)
library(gsheet)
url_gsheet = "https://docs.google.com/spreadsheets/d/1QogGSuEab5SZyZIw1Q8h-0yrBNs1Z_eEBJG7oRESW5k/edit
df_gsheet = as.data.frame(gsheet2tbl(url_gsheet))
head(df_gsheet)
url2 = "https://docs.google.com/spreadsheets/d/16KwkNnX6QAO23c03sCnzCElp3nRWfCp0g9tKCcKETsk/edit
newdata = as.data.frame(gsheet2tbl(url2))
head(newdata)
Sys.setenv(JAVA_HOME='C:\\Program Files\\Java\\jre1.8.0_191')
library(xlsx)
df_excel1 = read.xlsx( "./data/myexcel.xlsx", 1)
df_excel1
df_excel2a = read.xlsx("./data/myexcel.xlsx", sheetName = "bowlers")
df_excel2a
df_excel2b = read.xlsx( "./data/myexcel.xlsx", sheetIndex = 2)
df_excel2b
|
amh_eval_priors <- function( pars, prior )
{
NP <- length(pars)
priorval0 <- 0
eps <- 1E-100
for (pp in 1:NP){
pars_pp <- names(pars)[pp]
prior_arg_pp <- prior[[pp]][[2]]
prior_arg_pp[[1]] <- pars[pp]
priorval_pp <- log( do.call( prior[[pp]][[1]], prior_arg_pp ) + eps )
priorval0 <- priorval0 + priorval_pp
}
return(priorval0)
}
|
glm1 = function(y, X, lambda, family="negative.binomial", weights = rep(1, length(y)), b.init = NA, phi.init=NA,
phi.method="ML", tol=c(1.e-8,.Machine$double.eps), n.iter=100, phi.iter=1)
{
counter = 1
zero.counter=0
family.old=family
if (is.character(family))
{
if (family == "negbinomial" || family == "negative.binomial")
family = negative.binomial(1/tol[2])
else
family = get(family, mode = "function", envir = parent.frame())
}
if (is.function(family))
family = family()
if(pmatch("Negative Binomial",family$family,nomatch=0)==0)
is.nb=F
else
{
is.nb=T
if(is.na(phi.init))
{
phi.init = family$var(1)-1
if(phi.init>2*tol[2])
phi.iter=n.iter*2
}
}
if (length(lambda) == 1)
lambda = c( 0, rep(lambda, dim(X)[2]-1) )
likes = c()
phis = c()
mult = 0
if (any(is.na(b.init)) )
b.lasso = c( family$linkfun(mean(y)), rep(0, dim(X)[2] - 1))
if (any(is.na(b.init)) == FALSE)
b.lasso = b.init
is.in = abs(b.lasso) > tol[2] | lambda==0
sign.change = rep(-1, dim(X)[2])
is.different = is.in
signs = sign(b.lasso)
res = mu.update(b.lasso,y,X,weights,family,is.nb,phi.init,lambda,init=T,tol=tol)
while(any(is.different == TRUE))
{
likes = c(likes, res$like)
phis = c(phis, res$phi)
b.old = b.lasso
phi.old = res$phi
xw = t(as.vector(res$weii) * t(t(X[,is.in])))
xwx = solve(xw %*% X[,is.in] + diag( sum(is.in) )*min(tol[1]/100,sqrt(tol[2])) )
betaa = xwx %*% ( xw %*% res$z - as.matrix(lambda[is.in] * signs[is.in]))
b.lasso[is.in] = betaa
res = mu.update(b.lasso,y,X,weights,res$family,is.nb,phi.old,lambda,init=F,phi.step=F,phi.method,tol=tol)
dev.change = (res$like - likes[length(likes)])/abs(likes[length(likes)]+0.1)
half.step = 0
while(dev.change< (-tol[1]) & half.step<4)
{
b.lasso[is.in] = 0.5 * ( b.old[is.in] + b.lasso[is.in] )
half.step = half.step + 1
res = mu.update(b.lasso,y,X,weights,res$family,is.nb,phi.old,lambda,init=F,phi.step=F,phi.method,tol=tol)
dev.change = (res$like - likes[length(likes)])/abs(likes[length(likes)]+0.1)
}
sign.change = rep(1,dim(X)[2])
sign.change[is.in] = signs[is.in]*sign(b.lasso[is.in])
sign.change[lambda==0] = 1
sign.change[sign.change == 0] = 1
if (any(sign.change != 1) == TRUE)
{
delta = b.lasso[is.in]-b.old[is.in]
prop = min(abs(b.old[is.in]/delta)[sign.change[is.in] != 1])
b.lasso[is.in] = b.old[is.in] + prop*delta
mult = 2
res = mu.update(b.lasso,y,X,weights,res$family,is.nb,phi.old,lambda,init=F,phi.step=F,phi.method,tol=tol)
dev.change = (res$like - likes[length(likes)])/abs(likes[length(likes)]+0.1)
}
is.in[abs(b.lasso) < tol[2]] = FALSE
b.lasso[is.in == FALSE] = 0
signs = sign(b.lasso)
xw = t(as.vector(res$weii) * t(t(X)))
score = t( t(xw) / as.vector(res$deriv) ) %*% (y - res$mu)
score.lamb = lambda
score.lamb[lambda == 0] = abs(score[lambda == 0]) + max(lambda) + 100000
viol = as.vector(abs(score))/as.vector(score.lamb)
bigviol = max(viol)
viol.out = (viol==bigviol & is.in == FALSE)
if (any(sign.change != 1) == FALSE)
{
if ( any( viol.out ) & bigviol > (1+tol[1]))
{
{
to.add = which(viol.out)[1]
is.in[to.add] = TRUE
signs[to.add] = sign(score[to.add])
mult = 1
}
}
}
if(is.nb)
{
phi.step = counter%%phi.iter==0
res = mu.update(b.lasso,y,X,weights,res$family,is.nb,phi.old,lambda,init=F,phi.step=phi.step,phi.method,tol=tol)
phis[length(phis)] = res$phi
dev.change = (res$like - likes[length(likes)])/abs(likes[length(likes)]+0.1)
}
likes[length(likes)] = res$like
diff = mult+abs(dev.change)
is.different = rep(diff > tol[1], dim(X)[2])
mult = 0
if ( counter>n.iter)
{
is.different = FALSE
warning('non-convergence!!!')
counter = Inf
}
counter = counter + 1
df = sum(abs(b.lasso)>tol[2])
if(df==0)
{
zero.counter = zero.counter + 1
if(zero.counter>3)
break
is.in[sample(1:dim(X)[2],5)]=T
}
}
likes = likes + sum(as.vector(lambda)*abs(b.lasso))
check = any( abs(score[is.in==F])>lambda[is.in==F]+tol[1] ) || any( abs( abs(score[is.in])-lambda[is.in] ) > tol[1] )
names(b.lasso) = dimnames(X)[[2]]
dimnames(score)[[1]]=dimnames(X)[[2]]
dimnames(res$mu)=dimnames(y)
return(list(coefficients=b.lasso, fitted.values=res$mu, logLs = likes, phis=phis, phi=res$phi, score=score, counter = counter, check=check, family=res$family, weights=weights))
}
mu.update = function(b.lasso, y, X, weights, family, is.nb, phi, lambda, init=F, phi.step=T, phi.method="ML",tol=c(1.e-8,.Machine$double.eps))
{
eta = X %*% b.lasso
mu = family$linkinv(eta)
if(is.nb==F)
phi = NA
if (is.nb == T)
{
if(init == T)
{
disp = sum( (y - mu)^2/(mu ) ) / (length(y) - dim(X)[2])
if (is.na(phi))
{
if (disp > 1)
phi = 1
else
phi <- tol[1]
}
}
if(init == F)
{
if( phi.step==T )
{
if (phi.method=="ML")
{
k <- 1/phi
dl.dk = sum( - (y-mu)/(mu+k) + digamma(y+k) - log(mu+k) ) + length(y) * ( log(k) - digamma(k) )
dl.dphi = - k^2 * dl.dk
like.num = dl.dphi
d2l.dk2 = sum( (y-mu)/(mu+k)^2 + trigamma(y+k) - 1/(mu+k) ) + length(y) * ( 1/k - trigamma(k) )
d2l.dphi2 = 2*k^3*dl.dk + k^4 * d2l.dk2
like.den = d2l.dphi2
phi = phi + like.num/abs(like.den)
}
else
{
like.num = sum( (y - mu)^2/(mu + phi*mu^2) ) / (length(y) - dim(X)[2]) -1
like.den = - sum(mu^2*(y - mu)^2/(mu + phi*mu^2)^2) / (length(y) - dim(X)[2])
phi <- phi - like.num/like.den
}
}
phi <- min(phi,1/tol[1])
}
if(phi<=tol[1])
{
phi = tol[1]
family = poisson()
}
else
{
k = 1/phi
family = negative.binomial(k)
}
}
if( family$family=="binomial" || family$family=="poisson" || pmatch("Negative Binomial",family$family,nomatch=0)==1 )
dev = NA
else
dev = family$dev(y,mu,weights)
like = -sum(family$aic(y,1,mu,weights,dev))/2 - sum(as.vector(lambda)*abs(b.lasso))
vari = family$variance(mu)
deriv = family$mu.eta(eta)
z = eta + (y - mu)/deriv
weii = weights*deriv^2/vari
return(list(eta=eta,mu=mu,like=like,vari=vari,deriv=deriv,z=z,weii=weii,phi=phi,family=family))
}
|
library(testthat)
library(CVXR)
test_check("CVXR", filter="^g04")
|
field_mask <- function(x) {
stopifnot(is_dictionaryish(x))
explicit_mask <- imap(x, field_mask_impl_)
as.character(glue_collapse(unname(unlist(explicit_mask)), ","))
}
field_mask_impl_ <- function(x, y = "") {
if (!is_list(x)) {
return(y)
}
stopifnot(is_dictionaryish(x))
leafs <- !map_lgl(x, is_list)
if (sum(leafs) <= 1) {
leafs <- FALSE
}
names(x)[!leafs] <- glue(".{names(x)[!leafs]}")
if (sum(leafs) > 1) {
nm <- glue("({glue_collapse(names(x)[leafs], sep = ',')})")
x <- list2(!!nm := NA, !!!x[!leafs])
}
map2(x, glue("{y}{names(x)}"), field_mask_impl_)
}
|
BertConfig <- function(vocab_size,
hidden_size = 768L,
num_hidden_layers = 12L,
num_attention_heads = 12L,
intermediate_size = 3072L,
hidden_act = "gelu",
hidden_dropout_prob = 0.1,
attention_probs_dropout_prob = 0.1,
max_position_embeddings = 512L,
type_vocab_size = 16L,
initializer_range = 0.02) {
obj <- list(
"vocab_size" = vocab_size,
"hidden_size" = hidden_size,
"num_hidden_layers" = num_hidden_layers,
"num_attention_heads" = num_attention_heads,
"hidden_act" = hidden_act,
"intermediate_size" = intermediate_size,
"hidden_dropout_prob" = hidden_dropout_prob,
"attention_probs_dropout_prob" = attention_probs_dropout_prob,
"max_position_embeddings" = max_position_embeddings,
"type_vocab_size" = type_vocab_size,
"initializer_range" = initializer_range
)
class(obj) <- "BertConfig"
return(obj)
}
bert_config_from_json_file <- function(json_file) {
args <- jsonlite::fromJSON(json_file)
return(do.call(BertConfig, args = args))
}
BertModel <- function(config,
is_training,
input_ids,
input_mask = NULL,
token_type_ids = NULL,
scope = NULL) {
if (!is_training) {
config$hidden_dropout_prob <- 0.0
config$attention_probs_dropout_prob <- 0.0
}
input_shape <- get_shape_list(input_ids, expected_rank = 2L)
batch_size <- input_shape[[1]]
seq_length <- input_shape[[2]]
if (is.null(input_mask)) {
input_mask <- tensorflow::tf$ones(
shape = tensorflow::shape(batch_size, seq_length),
dtype = tensorflow::tf$int32
)
}
if (is.null(token_type_ids)) {
token_type_ids <- tensorflow::tf$zeros(
shape = tensorflow::shape(batch_size, seq_length),
dtype = tensorflow::tf$int32
)
}
with(tensorflow::tf$variable_scope(scope, default_name = "bert"), {
with(tensorflow::tf$variable_scope("embeddings"), {
elup <- embedding_lookup(
input_ids = input_ids,
vocab_size = config$vocab_size,
embedding_size = config$hidden_size,
initializer_range = config$initializer_range,
word_embedding_name = "word_embeddings"
)
embedding_output <- elup[[1]]
embedding_table <- elup[[2]]
embedding_output <- embedding_postprocessor(
input_tensor = embedding_output,
use_token_type = TRUE,
token_type_ids = token_type_ids,
token_type_vocab_size = config$type_vocab_size,
token_type_embedding_name = "token_type_embeddings",
use_position_embeddings = TRUE,
position_embedding_name = "position_embeddings",
initializer_range = config$initializer_range,
max_position_embeddings = config$max_position_embeddings,
dropout_prob = config$hidden_dropout_prob
)
})
with(tensorflow::tf$variable_scope("encoder"), {
attention_mask <- create_attention_mask_from_input_mask(
input_ids,
input_mask
)
all_encoder_layers <- transformer_model(
input_tensor = embedding_output,
attention_mask = attention_mask,
hidden_size = config$hidden_size,
num_hidden_layers = config$num_hidden_layers,
num_attention_heads = config$num_attention_heads,
intermediate_size = config$intermediate_size,
intermediate_act_fn = get_activation(config$hidden_act),
hidden_dropout_prob = config$hidden_dropout_prob,
attention_probs_dropout_prob = config$attention_probs_dropout_prob,
initializer_range = config$initializer_range,
do_return_all_layers = TRUE
)
})
attention_data <- all_encoder_layers$attention_data
all_encoder_layers <- all_encoder_layers$final_outputs
sequence_output <- all_encoder_layers[[length(all_encoder_layers)]]
with(tensorflow::tf$variable_scope("pooler"), {
first_token_tensor <- sequence_output[, 1, ]
pooled_output <- tensorflow::tf$layers$dense(
first_token_tensor,
config$hidden_size,
activation = tensorflow::tf$tanh,
kernel_initializer = create_initializer(config$initializer_range)
)
})
})
obj <- list(
"embedding_output" = embedding_output,
"embedding_table" = embedding_table,
"all_encoder_layers" = all_encoder_layers,
"attention_data" = attention_data,
"sequence_output" = sequence_output,
"pooled_output" = pooled_output
)
class(obj) <- "BertModel"
return(obj)
}
gelu <- function(x) {
cdf <- 0.5 * (1.0 + tensorflow::tf$tanh(
(sqrt(2 / pi) * (x + 0.044715 * tensorflow::tf$pow(x, 3)))
)
)
return(x * cdf)
}
get_activation <- function(activation_string) {
if (!is.character(activation_string)) {
return(activation_string)
}
activation_string <- tolower(trimws(activation_string))
if (is.na(activation_string) | activation_string == "") {
return(NA)
}
if (activation_string == "linear") {
return(NA)
} else if (activation_string == "relu") {
return(tensorflow::tf$nn$relu)
} else if (activation_string == "gelu") {
return(gelu)
} else if (activation_string == "tanh") {
return(tensorflow::tf$tanh)
} else {
stop(paste("Unsupported activation", activation_string))
}
}
get_assignment_map_from_checkpoint <- function(tvars, init_checkpoint) {
assignment_map <- list()
initialized_variable_names <- list()
name_to_variable <- list()
for (var in tvars) {
name <- var$name
m <- stringr::str_match(string = name, pattern = "^(.*):\\d+$")[[2]]
if (!is.na(m)) {
name <- m
}
name_to_variable[[name]] <- var
}
just_names <- names(name_to_variable)
init_vars <- tensorflow::tf$train$list_variables(init_checkpoint)
assignment_map <- list()
for (x in init_vars) {
name <- x[[1]]
if (name %in% just_names) {
assignment_map[[name]] <- name
initialized_variable_names[[name]] <- 1
initialized_variable_names[[paste0(name, ":0")]] <- 1
}
}
return(list(
"assignment_map" = assignment_map,
"initialized_variable_names" = initialized_variable_names
))
}
dropout <- function(input_tensor, dropout_prob = NULL) {
if (is.null(dropout_prob) | dropout_prob == 0.0) {
return(input_tensor)
}
output <- tensorflow::tf$nn$dropout(input_tensor, 1.0 - dropout_prob)
return(output)
}
layer_norm <- function(input_tensor, name = NULL) {
return(tensorflow::tf$contrib$layers$layer_norm(
inputs = input_tensor,
begin_norm_axis = -1L,
begin_params_axis = -1L,
scope = name
))
}
layer_norm_and_dropout <- function(input_tensor,
dropout_prob = NULL,
name = NULL) {
output_tensor <- layer_norm(input_tensor, name)
output_tensor <- dropout(output_tensor, dropout_prob)
return(output_tensor)
}
create_initializer <- function(initializer_range = 0.02) {
return(
tensorflow::tf$truncated_normal_initializer(stddev = initializer_range)
)
}
embedding_lookup <- function(input_ids,
vocab_size,
embedding_size = 128L,
initializer_range = 0.02,
word_embedding_name = "word_embeddings") {
if (input_ids$shape$ndims == 2L) {
input_ids <- tensorflow::tf$expand_dims(input_ids, axis = c(-1L))
} else if (input_ids$shape$ndims < 2 | input_ids$shape$ndims > 3) {
stop("input_id tensor has incorrect shape.")
}
embedding_table <- tensorflow::tf$get_variable(
name = word_embedding_name,
shape = tensorflow::shape(vocab_size, embedding_size),
initializer = create_initializer(initializer_range)
)
flat_input_ids <- tensorflow::tf$reshape(input_ids, shape = list(-1L))
output <- tensorflow::tf$gather(embedding_table, flat_input_ids)
input_shape <- unlist(get_shape_list(input_ids))
num_dims <- length(input_shape)
last_dim <- input_shape[num_dims][[1]]
first_dims <- input_shape[-num_dims]
target_shape <- unlist(list(first_dims, last_dim * embedding_size),
recursive = FALSE
)
output <- tensorflow::tf$reshape(
output,
target_shape
)
return(list(output, embedding_table))
}
embedding_postprocessor <- function(
input_tensor,
use_token_type = FALSE,
token_type_ids = NULL,
token_type_vocab_size = 16L,
token_type_embedding_name = "token_type_embeddings",
use_position_embeddings = TRUE,
position_embedding_name = "position_embeddings",
initializer_range = 0.02,
max_position_embeddings = 512L,
dropout_prob = 0.1) {
input_shape <- get_shape_list(input_tensor, expected_rank = 3L)
batch_size <- input_shape[[1]]
seq_length <- input_shape[[2]]
width <- input_shape[[3]]
output <- input_tensor
if (use_token_type) {
if (is.null(token_type_ids)) {
stop("`token_type_ids` must be specified if `use_token_type` is TRUE.")
}
token_type_table <- tensorflow::tf$get_variable(
name = token_type_embedding_name,
shape = tensorflow::shape(token_type_vocab_size, width),
initializer = create_initializer(initializer_range)
)
}
flat_token_type_ids <- tensorflow::tf$reshape(token_type_ids,
shape = list(-1L)
)
one_hot_ids <- tensorflow::tf$one_hot(flat_token_type_ids,
depth = token_type_vocab_size
)
token_type_embeddings <- tensorflow::tf$matmul(
one_hot_ids,
token_type_table
)
token_type_embeddings <- tensorflow::tf$reshape(
token_type_embeddings,
shape = list(batch_size, seq_length, width)
)
output <- output + token_type_embeddings
if (use_position_embeddings) {
assert_op <- tensorflow::tf$assert_less_equal(
seq_length,
max_position_embeddings
)
with(tensorflow::tf$control_dependencies(list(assert_op)), {
full_position_embeddings <- tensorflow::tf$get_variable(
name = position_embedding_name,
shape = tensorflow::shape(max_position_embeddings, width),
initializer = create_initializer(initializer_range)
)
position_embeddings <- tensorflow::tf$slice(
full_position_embeddings,
begin = tensorflow::shape(0, 0),
size = tensorflow::shape(seq_length, -1)
)
num_dims <- length(output$shape$as_list())
position_broadcast_shape <- as.integer(c(
rep.int(1, num_dims - 2),
seq_length,
width
))
position_embeddings <- tensorflow::tf$reshape(
position_embeddings,
position_broadcast_shape
)
output <- output + position_embeddings
})
}
output <- layer_norm_and_dropout(output, dropout_prob)
return(output)
}
create_attention_mask_from_input_mask <- function(from_tensor, to_mask) {
from_shape <- get_shape_list(from_tensor, expected_rank = list(2, 3))
batch_size <- from_shape[[1]]
from_seq_length <- from_shape[[2]]
to_shape <- get_shape_list(to_mask, expected_rank = 2)
to_batch_size <- to_shape[[1]]
to_seq_length <- to_shape[[2]]
to_mask <- tensorflow::tf$cast(
tensorflow::tf$reshape(
to_mask,
list(batch_size, 1L, to_seq_length)
),
tensorflow::tf$float32
)
broadcast_ones <- tensorflow::tf$ones(
shape = list(batch_size, from_seq_length, 1L),
dtype = tensorflow::tf$float32
)
mask <- broadcast_ones * to_mask
return(mask)
}
transpose_for_scores <- function(input_tensor,
batch_size,
num_attention_heads,
seq_length,
width) {
output_tensor <- tensorflow::tf$reshape(
input_tensor,
list(
batch_size,
as.integer(seq_length),
as.integer(num_attention_heads),
as.integer(width)
)
)
output_tensor <- tensorflow::tf$transpose(output_tensor,
perm = list(0L, 2L, 1L, 3L)
)
return(output_tensor)
}
attention_layer <- function(from_tensor,
to_tensor,
attention_mask = NULL,
num_attention_heads = 1L,
size_per_head = 512L,
query_act = NULL,
key_act = NULL,
value_act = NULL,
attention_probs_dropout_prob = 0.0,
initializer_range = 0.02,
do_return_2d_tensor = FALSE,
batch_size = NULL,
from_seq_length = NULL,
to_seq_length = NULL) {
from_shape <- get_shape_list(from_tensor, expected_rank = c(2L, 3L))
to_shape <- get_shape_list(to_tensor, expected_rank = c(2L, 3L))
if (length(from_shape) != length(to_shape)) {
stop("The rank of from_tensor must match the rank of to_tensor.")
}
if (length(from_shape) == 3) {
batch_size <- from_shape[[1]]
from_seq_length <- from_shape[[2]]
to_seq_length <- to_shape[[2]]
} else if (
is.null(batch_size) | is.null(from_seq_length) | is.null(to_seq_length)
) {
stop(paste(
"When passing in rank 2 tensors to attention_layer, the values",
"for batch_size, from_seq_length, and to_seq_length",
"must all be specified."
))
}
from_tensor_2d <- reshape_to_matrix(from_tensor)
to_tensor_2d <- reshape_to_matrix(to_tensor)
query_layer <- tensorflow::tf$layers$dense(
from_tensor_2d,
num_attention_heads * size_per_head,
activation = query_act,
name = "query",
kernel_initializer = create_initializer(initializer_range)
)
key_layer <- tensorflow::tf$layers$dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation = key_act,
name = "key",
kernel_initializer = create_initializer(initializer_range)
)
value_layer <- tensorflow::tf$layers$dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation = value_act,
name = "value",
kernel_initializer = create_initializer(initializer_range)
)
query_layer <- transpose_for_scores(
query_layer,
batch_size,
num_attention_heads,
from_seq_length,
size_per_head
)
key_layer <- transpose_for_scores(
key_layer,
batch_size,
num_attention_heads,
to_seq_length,
size_per_head
)
attention_scores <- tensorflow::tf$matmul(query_layer,
key_layer,
transpose_b = TRUE
)
attention_scores <- tensorflow::tf$multiply(
attention_scores,
1.0 / sqrt(size_per_head)
)
if (!is.null(attention_mask)) {
attention_mask <- tensorflow::tf$expand_dims(attention_mask,
axis = list(1L)
)
adder <- (1.0 - tensorflow::tf$cast(
attention_mask,
tensorflow::tf$float32
)) * (-10000.0)
attention_scores <- attention_scores + adder
}
attention_probs <- tensorflow::tf$nn$softmax(attention_scores)
attention_probs <- dropout(attention_probs, attention_probs_dropout_prob)
value_layer <- transpose_for_scores(
input_tensor = value_layer,
batch_size = batch_size,
num_attention_heads = num_attention_heads,
seq_length = to_seq_length,
width = size_per_head
)
context_layer <- tensorflow::tf$matmul(attention_probs, value_layer)
context_layer <- tensorflow::tf$transpose(context_layer,
perm = list(0L, 2L, 1L, 3L)
)
if (do_return_2d_tensor) {
context_layer <- tensorflow::tf$reshape(
context_layer,
list(
batch_size * from_seq_length,
as.integer(num_attention_heads * size_per_head)
)
)
} else {
context_layer <- tensorflow::tf$reshape(
context_layer,
list(
batch_size,
as.integer(from_seq_length),
as.integer(num_attention_heads),
as.integer(size_per_head)
)
)
}
to_return <- list(
"context_layer" = context_layer,
"attention_data" = attention_probs
)
return(to_return)
}
transformer_model <- function(input_tensor,
attention_mask = NULL,
hidden_size = 768L,
num_hidden_layers = 12L,
num_attention_heads = 12L,
intermediate_size = 3072L,
intermediate_act_fn = gelu,
hidden_dropout_prob = 0.1,
attention_probs_dropout_prob = 0.1,
initializer_range = 0.02,
do_return_all_layers = FALSE) {
if (hidden_size %% num_attention_heads != 0) {
stop(paste(
"The hidden size:",
hidden_size,
"is not a multiple of the number of attention heads:",
num_attention_heads
))
}
attention_head_size <- hidden_size %/% num_attention_heads
input_shape <- get_shape_list(input_tensor, expected_rank = 3L)
batch_size <- input_shape[[1]]
seq_length <- input_shape[[2]]
input_width <- input_shape[[3]]
if (input_width != hidden_size) {
stop(paste(
"The width of the input tensor:",
input_width,
"is not equal to the hidden size:",
hidden_size
))
}
prev_output <- reshape_to_matrix(input_tensor)
all_attn_data <- vector(mode = "list", length = num_hidden_layers)
all_layer_outputs <- vector(mode = "list", length = num_hidden_layers)
for (layer_idx in 1:num_hidden_layers) {
python_index <- layer_idx - 1
scope_name <- paste0("layer_", python_index)
with(tensorflow::tf$variable_scope(scope_name), {
layer_input <- prev_output
with(tensorflow::tf$variable_scope("attention"), {
with(tensorflow::tf$variable_scope("self"), {
attention_output <- attention_layer(
from_tensor = layer_input,
to_tensor = layer_input,
attention_mask = attention_mask,
num_attention_heads = num_attention_heads,
size_per_head = attention_head_size,
attention_probs_dropout_prob = attention_probs_dropout_prob,
initializer_range = initializer_range,
do_return_2d_tensor = TRUE,
batch_size = batch_size,
from_seq_length = seq_length,
to_seq_length = seq_length
)
})
attention_data <- attention_output$attention_data
attention_output <- attention_output$context_layer
with(tensorflow::tf$variable_scope("output"), {
attention_output <- tensorflow::tf$layers$dense(
attention_output,
hidden_size,
kernel_initializer = create_initializer(initializer_range)
)
attention_output <- dropout(attention_output, hidden_dropout_prob)
attention_output <- layer_norm(attention_output + layer_input)
})
})
with(tensorflow::tf$variable_scope("intermediate"), {
intermediate_output <- tensorflow::tf$layers$dense(
attention_output,
intermediate_size,
activation = intermediate_act_fn,
kernel_initializer = create_initializer(initializer_range)
)
})
with(tensorflow::tf$variable_scope("output"), {
layer_output <- tensorflow::tf$layers$dense(
intermediate_output,
hidden_size,
kernel_initializer = create_initializer(initializer_range)
)
layer_output <- dropout(layer_output, hidden_dropout_prob)
layer_output <- layer_norm(layer_output + attention_output)
prev_output <- layer_output
all_layer_outputs[[layer_idx]] <- layer_output
all_attn_data[[layer_idx]] <- attention_data
})
})
}
if (do_return_all_layers) {
final_outputs <- purrr::map(
all_layer_outputs,
reshape_from_matrix,
input_shape
)
to_return <- list(
"final_outputs" = final_outputs,
"attention_data" = all_attn_data
)
return(to_return)
} else {
final_output <- reshape_from_matrix(prev_output, input_shape)
return(final_output)
}
}
get_shape_list <- function(tensor, expected_rank = NULL, name = NULL) {
if (is.null(name)) {
name <- tensor$name
}
if (!is.null(expected_rank)) {
assert_rank(tensor, expected_rank, name)
}
shape <- tensor$shape$as_list()
shape <- as.list(shape)
non_static_indexes <- c()
for (index in seq_along(shape)) {
dim <- shape[index]
if (dim == "NULL") {
non_static_indexes <- c(non_static_indexes, index)
}
}
if (length(non_static_indexes) == 0) {
return(shape)
}
dyn_shape <- tensorflow::tf$shape(tensor)
for (index in non_static_indexes) {
shape[[index]] <- dyn_shape[index]
}
return(shape)
}
reshape_to_matrix <- function(input_tensor) {
ndims <- input_tensor$shape$ndims
if (ndims == 2) {
return(input_tensor)
}
if (ndims < 2) {
stop(paste(
"Input tensor must have at least rank 2. Shape =",
input_tensor$shape
))
}
input_shape <- input_tensor$shape$as_list()
width <- input_shape[[ndims]]
output_tensor <- tensorflow::tf$reshape(input_tensor, list(-1L, width))
return(output_tensor)
}
reshape_from_matrix <- function(output_tensor, orig_shape_list) {
output_shape <- get_shape_list(output_tensor)
num_dims <- length(orig_shape_list)
width <- orig_shape_list[num_dims]
orig_dims <- orig_shape_list[-num_dims]
if (length(output_shape) != 2) {
stop("tensor is not rank 2")
}
if (output_shape[[2]] != width) {
stop("width is not consistent")
}
if (length(orig_shape_list) == 2) {
return(output_tensor)
}
return(tensorflow::tf$reshape(
output_tensor,
orig_shape_list
))
}
assert_rank <- function(tensor, expected_rank, name = NULL) {
if (is.null(name)) {
name <- tensor$name
}
actual_rank <- tensor$shape$ndims
if (!actual_rank %in% expected_rank) {
stop(paste0(
"For the tensor ", name,
", the actual rank ", actual_rank,
" (shape = ", tensor$shape,
") is not equal to the expected rank ", expected_rank, "."
))
}
return(TRUE)
}
|
html_element <- function(x, css, xpath) {
UseMethod("html_element")
}
html_elements <- function(x, css, xpath) {
UseMethod("html_elements")
}
html_elements.default <- function(x, css, xpath) {
xml2::xml_find_all(x, make_selector(css, xpath))
}
html_element.default <- function(x, css, xpath) {
xml2::xml_find_first(x, make_selector(css, xpath))
}
make_selector <- function(css, xpath) {
if (missing(css) && missing(xpath))
stop("Please supply one of css or xpath", call. = FALSE)
if (!missing(css) && !missing(xpath))
stop("Please supply css or xpath, not both", call. = FALSE)
if (!missing(css)) {
if (!is.character(css) && length(css) == 1)
stop("`css` must be a string")
selectr::css_to_xpath(css, prefix = ".//")
} else {
if (!is.character(xpath) && length(xpath) == 1)
stop("`xpath` must be a string")
xpath
}
}
|
within.imputationList <- function (data, expr, ...)
{
res <- data
imp <- res$imputations
M <- length(imp)
for (ii in 1:M){
parent <- parent.frame()
data <- imp[[ii]]
e <- evalq(environment(), data, parent)
eval(substitute(expr), e)
l <- as.list(e)
l <- l[!sapply(l, is.null)]
nD <- length(del <- setdiff(names(data), (nl <- names(l))))
data[nl] <- l
if (nD)
data[del] <- if (nD==1)
NULL
else vector("list", nD)
imp[[ii]] <- data
}
res$imputations <- imp
return(res)
}
|
MeasureSurvUnoAUC = R6Class("MeasureSurvUnoAUC",
inherit = MeasureSurvAUC,
public = list(
initialize = function(integrated = TRUE, times) {
ps = ps(
integrated = p_lgl(default = TRUE),
times = p_uty()
)
ps$values$integrated = TRUE
super$initialize(
param_set = ps,
id = "surv.uno_auc",
properties = c("requires_task", "requires_train_set"),
man = "mlr3proba::mlr_measures_surv.uno_auc"
)
}
),
private = list(
.score = function(prediction, task, train_set, ...) {
ps = self$param_set$values
if (!ps$integrated) {
msg = "If `integrated=FALSE` then `times` should be a scalar numeric."
assert_numeric(ps$times, len = 1, .var.name = msg)
} else {
if (!is.null(ps$times) && length(ps$times) == 1) {
ps$integrated = FALSE
}
}
super$.score(
prediction = prediction,
task = task,
train_set = train_set,
FUN = survAUC::AUC.uno,
...)
}
)
)
|
peakDrawing <-
function(vecIP, vecControl, lineIP, lineControl, lineFC, lineAverage,
posInf = 1, posSup = NULL, add = 10, title = ""){
vecINPUT = vecControl
lineINPUT = lineControl
if(is.null(posSup)){
posSup = length(vecIP)
}
xlabels = "chromosomal location"
par(mfrow = c(2,2))
if((posInf-add > 0) & (posSup+add <= length(vecIP))){
plot(vecIP, type = "h", xlab = xlabels, ylab = "T1: IP signal",
main = paste(title, "\nIP sample (T1)"), col = "red",
xlim = c(posInf-add,posSup+add),
ylim = c(0, max(vecIP, vecINPUT, na.rm = T)))
abline(v = posInf, lty = "dashed", col = "blue")
abline(v = posSup, lty = "dashed", col = "blue")
abline(h = lineIP, col = "red")
vecLogFC = log2((vecIP + 1)/(vecINPUT + 1))
plot(vecLogFC, type = "l", xlab = xlabels, ylab = "T3: log2FC",
main = paste(title, "\nlog2FC (T3)"), col = "orange",
xlim = c(posInf-add,posSup+add),
ylim = c(min(vecLogFC, na.rm = T), max(vecLogFC, na.rm = T)))
abline(v = posInf, lty = "dashed", col = "blue")
abline(v = posSup, lty = "dashed", col = "blue")
abline(h = lineFC, col = "red")
plot(vecINPUT, type = "h", xlab = xlabels, ylab = "T2: control signal",
main = paste(title, "\ncontrol sample (T2)"), col = "blue",
xlim = c(posInf-add,posSup+add),
ylim = c(0, max(vecIP, vecINPUT, na.rm = T)))
abline(v = posInf, lty = "dashed", col = "blue")
abline(v = posSup, lty = "dashed", col = "blue")
abline(h = lineINPUT, col = "red")
averageLog = (log2(vecIP + 1) + log2(vecINPUT + 1))/2
plot(averageLog, type = "l", xlab = xlabels, ylab = "T4: (log2(IP) + log2(control)) / 2",
main = paste(title, "\naverage log2 signals (T4)"), col = "purple",
xlim = c(posInf-add,posSup+add),
ylim = c(min(averageLog, na.rm = T), max(averageLog, na.rm = T)))
abline(v = posInf, lty = "dashed", col = "blue")
abline(v = posSup, lty = "dashed", col = "blue")
abline(h = lineAverage, col = "red")
}else{
print("!! peakDrawing() error !! check the values of genomic positions")
}
}
|
pivot_wider.dtplyr_step <- function(data,
id_cols = NULL,
names_from = name,
names_prefix = "",
names_sep = "_",
names_glue = NULL,
names_sort = FALSE,
names_repair = "check_unique",
values_from = value,
values_fill = NULL,
values_fn = NULL,
...) {
sim_data <- simulate_vars(data)
names_from <- names(tidyselect::eval_select(enquo(names_from), sim_data))
values_from <- names(tidyselect::eval_select(enquo(values_from), sim_data))
id_cols <- enquo(id_cols)
if (quo_is_null(id_cols)) {
sim_vars <- names(sim_data)
id_cols <- sim_vars[!sim_vars %in% c(names_from, values_from)]
} else {
id_cols <- names(tidyselect::eval_select(id_cols, sim_data))
}
if (length(names_from) > 1) {
new_vars <- mutate(shallow_dt(data), .names_from = paste(!!!syms(names_from), sep = names_sep))
new_vars <- unique(pull(new_vars, .names_from))
} else {
new_vars <- unique(pull(data, !!sym(names_from)))
new_vars <- as.character(new_vars)
}
if (!is.null(names_glue)) {
glue_df <- as.data.table(distinct(ungroup(data), !!!syms(names_from)))
glue_df <- vctrs::vec_rep(glue_df, length(values_from))
glue_df$.value <- vctrs::vec_rep_each(values_from, length(new_vars))
glue_vars <- as.character(glue::glue_data(glue_df, names_glue))
}
if (length(values_from) > 1) {
new_vars <- lapply(values_from, function(.x) paste(.x, new_vars, sep = names_sep))
new_vars <- unlist(new_vars)
}
no_id <- length(id_cols) == 0
if (no_id) {
lhs <- "..."
new_vars <- c(".", new_vars)
} else {
lhs <- call_reduce(syms(id_cols), "+")
}
rhs <- call_reduce(syms(names_from), "+")
vars <- c(id_cols, new_vars)
args <- list(
formula = call2("~", lhs, rhs),
value.var = values_from,
fun.aggregate = values_fn,
sep = names_sep,
fill = values_fill
)
args <- args[!vapply(args, is.null, lgl(1))]
if (names_sep == "_") {
args$sep <- NULL
}
out <- step_call(data, "dcast", args = args, vars = vars)
if (no_id && names_sort) {
new_vars <- new_vars[new_vars != "."]
cols_sorted <- sort(new_vars)
out <- select(out, !!!syms(cols_sorted))
} else if (no_id) {
new_vars <- new_vars[new_vars != "."]
out <- select(out, -.)
}
if (!is.null(names_glue)) {
out <- step_setnames(out, new_vars, glue_vars, in_place = FALSE)
new_vars <- glue_vars
} else if (nchar(names_prefix) > 0) {
new_names <- paste0(names_prefix, new_vars)
out <- step_setnames(out, new_vars, new_names, in_place = FALSE)
new_vars <- new_names
}
if (names_sort && !no_id) {
cols_sorted <- c(id_cols, sort(new_vars))
out <- step_colorder(out, cols_sorted)
}
out <- step_repair(out, repair = names_repair)
out
}
globalVariables(c(".", ".names_from", "name", "value", "pivot_wider"))
pivot_wider.data.table <- function(data,
id_cols = NULL,
names_from = name,
names_prefix = "",
names_sep = "_",
names_glue = NULL,
names_sort = FALSE,
names_repair = "check_unique",
values_from = value,
values_fill = NULL,
values_fn = NULL,
...) {
data <- lazy_dt(data)
pivot_wider(
data,
id_cols = {{ id_cols }},
names_from = {{ names_from }},
names_prefix = names_prefix,
names_sep = names_sep,
names_glue = names_glue,
names_sort = names_sort,
names_repair = names_repair,
values_from = {{ values_from }},
values_fn = values_fn
)
}
step_repair <- function(data, repair = "check_unique", in_place = TRUE) {
sim_data <- simulate_vars(data)
data_names <- names(sim_data)
repaired_names <- vctrs::vec_as_names(data_names, repair = repair)
if (any(data_names != repaired_names)) {
data <- step_setnames(data, seq_along(data_names), repaired_names, in_place = in_place)
}
data
}
shallow_dt <- function(x) {
filter(x, TRUE)
}
call_reduce <- function(x, fun) {
Reduce(function(x, y) call2(fun, x, y), x)
}
|
cdbRemoveDB <- function(cdb){
fname <- deparse(match.call()[[1]])
cdb <- cdb$checkCdb(cdb,fname)
if( cdb$error == ""){
adrString <- paste(cdb$baseUrl(cdb),
cdb$removeDBName,
sep="")
res <- getURL(utils::URLencode(adrString),
customrequest = "DELETE",
curl = cdb$curl,
.opts = cdb$opts(cdb),
.encoding = cdb$serverEnc
)
cdb$removeDBName <- ""
return(cdb$checkRes(cdb,res))
}else{
stop(cdb$error)
}
}
|
as.data.frame.survTP <- function(x, ..., package="TPmsm") {
if ( missing(x) ) stop("Argument 'x' is missing, with no default")
if ( !is.survTP(x) ) stop("Argument 'x' must be of class 'survTP'")
package <- match.arg(arg=package, choices=c("TPmsm", "p3state.msm", "etm"), several.ok=FALSE)
func <- switch(package, "TPmsm"=OutTPmsm, "p3state.msm"=Outp3state, "etm"=Outetm)
return( func(x[[1]], 1:4) )
}
|
downsample <- function(target, distanceMat, cutoff) {
localDensity <- function(distanceMat, epsilon) {
apply(distanceMat, 1, function(x) mean(x < epsilon))
}
ldens <- localDensity(distanceMat, cutoff)
scalefactor <- sum(1/ldens)/length(ldens)
prob <- (1/ldens)/length(ldens) * target/scalefactor
prob[prob > 0.99999] <- 0.99999
P <- rbinom(length(ldens), 1, prob)
P == 1
}
createGraph <- function(DV, Q) {
M <- as.matrix(DV@distance)
U <- M[upper.tri(M)]
if (missing(Q)) Q <- quantile(M, 0.1)
selU <- U < Q
M <- 0*M
M <- sweep(M, 2, 1:ncol(M), "+")
cols <- M[upper.tri(M)][selU]
M <- 0*M
M <- sweep(M, 1, 1:ncol(M), "+")
rows <- M[upper.tri(M)][selU]
daft <- data.frame(A = colnames(M)[cols],
B = colnames(M)[rows],
weight = 1-U[selU])
myg <- graph_from_data_frame(daft, directed=FALSE)
myg <- set_vertex_attr(myg, "size", value=3)
myg <- set_vertex_attr(myg, "label", value="")
V <- vertex_attr(myg)
syms <- c("square", "circle")[1 + (symv(DV) %% 2)]
names(syms) <- names(symv(DV))
myg <- set_vertex_attr(myg, "color", value=colv(DV)[V$name])
myg <- set_vertex_attr(myg, "shape", value=syms[V$name])
layouts <- list(nicely = layout_nicely(myg))
if (!is.null(MV <- DV@view[["mds"]])) {
V <- igraph::vertex_attr(myg)
layouts[["mds"]] <- MV[V$name,]
}
if (!is.null(TV <- DV@view[["tsne"]])) {
Y <- TV$Y
rownames(Y) <- labels(DV@distance)
V <- igraph::vertex_attr(myg)
layouts[["tsne"]] <- Y[V$name,]
}
list(graph = myg, layouts = layouts)
}
|
estimate<-EstMLEGrassiaIIBin(Chromosome_data$No.of.Asso,Chromosome_data$fre,0.1,0.5)
context("Checking outputs")
test_that("estimate method",{
expect_identical(estimate@method,
"BFGS")
})
test_that("estimate method",{
expect_identical(estimate@optimizer,
"optim")
})
test_that("minimized negative ll value",{
expect_identical(round(estimate@min,4),
436.8255)
})
test_that("Checking class of output",{
expect_that(estimate,
is_a("mle2"))
})
|
check_design_rule <- function(string, sep_in = NULL,
transliterations = NULL, sep_out = NULL, prefix = "",
postfix = "", unique_sep = NULL, empty_fill = NULL, parsing_option = 1){
test_c <- function(string, case){
to_any_case(string = string, case = case, sep_in = sep_in,
transliterations = transliterations,
sep_out = sep_out, prefix = prefix, postfix = postfix,
unique_sep = unique_sep, empty_fill = empty_fill,
parsing_option = parsing_option)
}
all(
test_c(string, case = "snake") == test_c(test_c(string, case = "snake"), case = "snake"),
test_c(string, case = "snake") == test_c(test_c(string, case = "small_camel"), case = "snake"),
test_c(string, case = "snake") == test_c(test_c(string, case = "big_camel"), case = "snake"),
test_c(string, case = "snake") == test_c(test_c(string, case = "screaming_snake"), case = "snake"),
test_c(string, case = "small_camel") == test_c(test_c(string, case = "snake"), case = "small_camel"),
test_c(string, case = "small_camel") == test_c(test_c(string, case = "small_camel"), case = "small_camel"),
test_c(string, case = "small_camel") == test_c(test_c(string, case = "big_camel"), case = "small_camel"),
test_c(string, case = "small_camel") == test_c(test_c(string, case = "screaming_snake"), case = "small_camel"),
test_c(string, case = "big_camel") == test_c(test_c(string, case = "snake"), case = "big_camel"),
test_c(string, case = "big_camel") == test_c(test_c(string, case = "small_camel"), case = "big_camel"),
test_c(string, case = "big_camel") == test_c(test_c(string, case = "big_camel"), case = "big_camel"),
test_c(string, case = "big_camel") == test_c(test_c(string, case = "screaming_snake"), case = "big_camel"),
test_c(string, case = "screaming_snake") == test_c(test_c(string, case = "snake"), case = "screaming_snake"),
test_c(string, case = "screaming_snake") == test_c(test_c(string, case = "small_camel"), case = "screaming_snake"),
test_c(string, case = "screaming_snake") == test_c(test_c(string, case = "big_camel"), case = "screaming_snake"),
test_c(string, case = "screaming_snake") == test_c(test_c(string, case = "screaming_snake"), case = "screaming_snake")
)
}
|
"f.fb.neglog.deriv" <-
function(t, mu, tau, c1)
{
.expr3 <- (sqrt((2 * pi))) * t
.expr4 <- t^2
.expr7 <- (.expr4 * (tau^2)) + t
.expr9 <- .expr3 * (sqrt(.expr7))
.expr10 <- c1/.expr9
.expr12 <- c1 - (mu * t)
.expr13 <- .expr12^2
.expr15 <- 2 * .expr7
.expr17 <- exp((( - .expr13)/.expr15))
.expr18 <- .expr10 * .expr17
.expr22 <- 2 * (t * .expr12)
.expr23 <- .expr22/.expr15
.expr24 <- .expr17 * .expr23
.expr25 <- .expr10 * .expr24
.expr37 <- .expr18^2
.expr42 <- .expr4 * (2 * tau)
.expr43 <- 2 * .expr42
.expr44 <- .expr13 * .expr43
.expr45 <- .expr15^2
.expr46 <- .expr44/.expr45
.expr47 <- .expr17 * .expr46
.expr54 <- .expr7^-0.5
.expr57 <- .expr3 * (0.5 * (.expr42 * .expr54))
.expr58 <- c1 * .expr57
.expr59 <- .expr9^2
.expr60 <- .expr58/.expr59
.expr66 <- (.expr10 * .expr47) - (.expr60 * .expr17)
.expr70 <- - ((((.expr10 * ((.expr47 * .expr23) - (.expr17 * ((.expr22 *
.expr43)/.expr45)))) - (.expr60 * .expr24))/.expr18) - ((
.expr25 * .expr66)/.expr37))
.expr71 <- 1/.expr9
.expr76 <- 2 * .expr12
.expr77 <- .expr76/.expr15
.expr78 <- .expr17 * .expr77
.expr86 <- (.expr71 * .expr17) - (.expr10 * .expr78)
.expr90 <- - ((((.expr71 * .expr24) + (.expr10 * ((.expr17 * ((2 * t)/
.expr15)) - (.expr78 * .expr23))))/.expr18) - ((.expr25 *
.expr86)/.expr37))
.expr94 <- .expr4 * 2
.expr107 <- .expr60 * .expr47
.expr150 <- - (((((.expr71 * .expr47) + (.expr10 * ((.expr17 * ((
.expr76 * .expr43)/.expr45)) - (.expr78 * .expr46)))) - (((
.expr57/.expr59) * .expr17) - (.expr60 * .expr78)))/.expr18) - (
(.expr66 * .expr86)/.expr37))
.expr153 <- .expr71 * .expr78
.value <- - (log(.expr18))
.grad <- array(0, c(length(.value), 3), list(NULL, c("mu", "tau", "c1")
))
.hess <- array(0, c(length(.value), 3, 3), list(NULL, c("mu", "tau",
"c1"), c("mu", "tau", "c1")))
.grad[, "mu"] <- - (.expr25/.expr18)
.grad[, "tau"] <- - (.expr66/.expr18)
.grad[, "c1"] <- - (.expr86/.expr18)
.hess[, "mu", "mu"] <- - (((.expr10 * ((.expr24 * .expr23) - (.expr17 * (
(2 * (t * t))/.expr15))))/.expr18) - ((.expr25 * .expr25)/
.expr37))
.hess[, "tau", "mu"] <- .expr70
.hess[, "c1", "mu"] <- .expr90
.hess[, "mu", "tau"] <- .expr70
.hess[, "tau", "tau"] <- - (((((.expr10 * ((.expr47 * .expr46) + (
.expr17 * (((.expr13 * (2 * .expr94))/.expr45) - ((.expr44 * (2 *
(.expr43 * .expr15)))/(.expr45^2)))))) - .expr107) - (((((c1 * (
.expr3 * (0.5 * ((.expr94 * .expr54) + (.expr42 * (-0.5 * (
.expr42 * (.expr7^-1.5))))))))/.expr59) - ((.expr58 * (2 * (
.expr57 * .expr9)))/(.expr59^2))) * .expr17) + .expr107))/
.expr18) - ((.expr66 * .expr66)/.expr37))
.hess[, "c1", "tau"] <- .expr150
.hess[, "mu", "c1"] <- .expr90
.hess[, "tau", "c1"] <- .expr150
.hess[, "c1", "c1"] <- ((.expr153 + (.expr153 + (.expr10 * ((.expr17 * (
2/.expr15)) - (.expr78 * .expr77)))))/.expr18) + ((.expr86 *
.expr86)/.expr37)
attr(.value, "gradient") <- .grad
attr(.value, "hessian") <- .hess
.value
}
|
mmer.diallel <- function(formula, Block = NULL, Env = NULL,
fct = "GRIFFING2", data, type = "all"){
if(type != "all" & type != "environment"){
print("The argument type only accepts 'all' or 'environment' values")
stop()
}
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "Block", "Env", "data"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
Y <- model.response(mf, "numeric")
mlm <- is.matrix(Y)
ny <- if (mlm)
nrow(Y)
else length(Y)
bName <- deparse(substitute(Block))
Block <- model.extract(mf, "Block")
eName <- deparse(substitute(Env))
Env <- model.extract(mf, "Env")
pars <- attr(mt, "term.labels")
if(missing(data) == T){
Par1 <- mf[,2]
Par2 <- mf[,3]
} else {
Par1 <- data[[pars[1]]]
Par2 <- data[[pars[2]]]
}
if(!is.null(Env)){
cond <- tapply(Y, list(Env, Par1, Par2), length)
cond[is.na(cond)] <- 1
withRep <- any(cond > 1)
if(!is.null(Block)){
df <- data.frame(Y, Env, Block, Par1, Par2)
} else {
df <- data.frame(Y, Env, Par1, Par2)
}
} else {
cond <- tapply(Y, list(Par1, Par2), length)
cond[is.na(cond)] <- 1
withRep <- any(cond > 1)
if(!is.null(Block)){
df <- data.frame(Y, Block, Par1, Par2)
} else {
df <- data.frame(Y, Par1, Par2)
}}
df$dr <- ifelse(as.character(df$Par1) < as.character(df$Par2), -1,
ifelse(as.character(df$Par1) == as.character(df$Par2), 0, 1))
df$combination <- factor(ifelse(as.character(df$Par1) <= as.character(df$Par2),
paste(df$Par1, df$Par2, sep =""),
paste(df$Par2, df$Par1, sep ="")))
df$selfs <- ifelse(as.character(df$Par1) == as.character(df$Par2), 1, 0)
df$crosses <- ifelse(as.character(df$Par1) == as.character(df$Par2), 0, 1)
if(!is.null(Env) & type == "environment"){
if(fct == "HAYMAN1"){
formFix <- Y ~ GCA(Par1, Par2) + tSCA(Par1, Par2) + RGCA(Par1, Par2) +
RSCA(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
RGCA(Par1:Env, Par2:Env, type = "random") +
RSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA:Env", "tSCA:Env", "RGCA:Env", "RSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
RGCA(Par1:Env, Par2:Env, type = "random") +
RSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "tSCA:Env", "RGCA:Env", "RSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
RGCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "tSCA:Env", "RGCA:Env", "RSCA:Env")
}
}else if(fct == "HAYMAN2"){
print("Yet to be implemented. Sorry!")
stop()
}else if(fct == "GRIFFING1"){
formFix <- Y ~ GCA(Par1, Par2) + tSCA(Par1, Par2) + REC(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA:Env", "tSCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "tSCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "tSCA:Env", "REC:Env")
}
} else if(fct == "GRIFFING3"){
formFix <- Y ~ GCA(Par1, Par2) + SCA.G3(Par1, Par2) + REC.G3(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA:Env", "SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "SCA:Env", "REC:Env")
}
} else if(fct == "GRIFFING2"){
formFix <- Y ~ GCA(Par1, Par2) + tSCA(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA:Env", "tSCA:Env","Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "tSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "tSCA:Env")
}
} else if(fct == "GRIFFING4"){
formFix <- Y ~ GCA(Par1, Par2) + SCA.G3(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA:Env", "SCA:Env","Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA:Env", "SCA:Env")
}
}else if(fct == "GE2r"){
formFix <- Y ~ H.BAR(Par1, Par2) + VEi(Par1, Par2) + Hi(Par1, Par2) +
SCA(Par1, Par2) + REC(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "REC:Env")
}
} else if(fct == "GE2"){
formFix <- Y ~ H.BAR(Par1, Par2) + VEi(Par1, Par2) + Hi(Par1, Par2) +
SCA(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block + crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env + crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env")
}
} else if(fct == "GE3r"){
formFix <- Y ~ H.BAR(Par1, Par2) + SP(Par1, Par2) + GCAC(Par1, Par2) +
SCA(Par1, Par2) + REC(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "REC:Env")
}
} else if(fct == "GE3"){
formFix <- Y ~ H.BAR(Par1, Par2) + SP(Par1, Par2) + GCAC(Par1, Par2) +
SCA(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env")
}}
}else if(!is.null(Env) & type == "all"){
if(fct == "HAYMAN1"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Env + Env:Block +
GCA(Par1, Par2, type = "random") +
tSCA(Par1, Par2, type = "random") +
RGCA(Par1, Par2, type = "random") +
RSCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
RGCA(Par1:Env, Par2:Env, type = "random") +
RSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA", "tSCA", "RGCA", "RSCA", "GCA:Env", "tSCA:Env", "RGCA:Env", "RSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
GCA(Par1, Par2, type = "random") +
tSCA(Par1, Par2, type = "random") +
RGCA(Par1, Par2, type = "random") +
RSCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
RGCA(Par1:Env, Par2:Env, type = "random") +
RSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "tSCA", "RGCA", "RSCA", "GCA:Env", "tSCA:Env", "RGCA:Env", "RSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
GCA(Par1, Par2, type = "random") +
tSCA(Par1, Par2, type = "random") +
RGCA(Par1, Par2, type = "random") +
RSCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
RGCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "tSCA", "RGCA", "RSCA", "GCA:Env", "tSCA:Env", "RGCA:Env", "RSCA:Env")
}
}else if(fct == "HAYMAN2"){
print("Yet to be implemented. Sorry!")
stop()
}else if(fct == "GRIFFING1"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Env + Env:Block +
GCA(Par1, Par2, type = "random") +
tSCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA", "tSCA", "REC", "GCA:Env", "tSCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
GCA(Par1, Par2, type = "random") +
tSCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "tSCA", "REC", "GCA:Env", "tSCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
GCA(Par1, Par2, type = "random") +
tSCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "tSCA", "REC", "GCA:Env", "tSCA:Env", "REC:Env")
}
}else if(fct == "GRIFFING3"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Env + Env:Block +
GCA(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA", "SCA", "REC", "GCA:Env", "SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
GCA(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "SCA", "REC", "GCA:Env", "SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
GCA(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "SCA", "REC", "GCA:Env", "tSCA:Env", "REC:Env")
}
} else if(fct == "GRIFFING2"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Env + Env:Block +
GCA(Par1, Par2, type = "random") + tSCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA", "tSCA", "GCA:Env", "tSCA:Env","Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env + GCA(Par1:Env, Par2:Env, type = "random") +
GCA(Par1, Par2, type = "random") + tSCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "tSCA", "GCA:Env", "tSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
GCA(Par1, Par2, type = "random") + tSCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "tSCA", "GCA:Env", "tSCA:Env")
}
} else if(fct == "GRIFFING4"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Env + Env:Block +
GCA(Par1, Par2, type = "random") + SCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "GCA", "SCA", "GCA:Env", "tSCA:Env","Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
GCA(Par1, Par2, type = "random") + SCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random") +
tSCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "SCA", "GCA:Env", "tSCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
GCA(Par1, Par2, type = "random") + SCA(Par1, Par2, type = "random") +
GCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "GCA", "SCA", "GCA:Env", "tSCA:Env")
}
} else if(fct == "GE2r"){
formFix <- Y ~ H.BAR(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
crosses:Env +
VEi(Par1, Par2, type = "random") +
Hi(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "VEi", "Hi", "SCA", "REC", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
crosses:Env +
VEi(Par1, Par2, type = "random") +
Hi(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env","VEi", "Hi", "SCA", "REC", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
crosses:Env +
VEi(Par1, Par2, type = "random") +
Hi(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "VEi", "Hi", "SCA", "REC", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "REC:Env")
}
} else if(fct == "GE2"){
formFix <- Y ~ H.BAR(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
crosses:Env +
VEi(Par1, Par2, type = "random") +
Hi(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "VEi", "Hi", "SCA", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
crosses:Env +
VEi(Par1, Par2, type = "random") +
Hi(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env","VEi", "Hi", "SCA", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
crosses:Env +
VEi(Par1, Par2, type = "random") +
Hi(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "VEi", "Hi", "SCA", "H:BAR:Env", "VEi:Env", "Hi:Env",
"SCA:Env")
}
} else if(fct == "GE3r"){
formFix <- Y ~ H.BAR(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
SP(Par1, Par2, type = "random") +
GCAC(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "SP", "GCAC", "SCA", "REC", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
SP(Par1, Par2, type = "random") +
GCAC(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random") +
REC(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "SP", "GCAC", "SCA", "REC", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "REC:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
SP(Par1, Par2, type = "random") +
GCAC(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
REC(Par1, Par2, type = "random") +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "SP", "GCAC", "SCA", "REC", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "REC:Env")
}
} else if(fct == "GE3"){
formFix <- Y ~ H.BAR(Par1, Par2)
if(!is.null(Block)){
form <- ~ Env + Env:Block +
SP(Par1, Par2, type = "random") +
GCAC(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "Env:Block", "SP", "GCAC", "SCA", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ Env +
SP(Par1, Par2, type = "random") +
GCAC(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
crosses:Env +
SP(Par1:Env, Par2:Env, type = "random") +
GCAC(Par1:Env, Par2:Env, type = "random") +
SCA(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "SP", "GCAC", "SCA", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ Env +
SP(Par1, Par2, type = "random") +
GCAC(Par1, Par2, type = "random") +
SCA(Par1, Par2, type = "random") +
crosses:Env +
VEi(Par1:Env, Par2:Env, type = "random") +
Hi(Par1:Env, Par2:Env, type = "random")
rnam <- c("Env", "SP", "GCAC", "SCA", "H:BAR:Env", "Selfs:Env", "GCAC:Env",
"SCA:Env")
}}
} else {
if(fct == "HAYMAN1"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + overlay(Par1, Par2):dr +
combination + combination:dr
rnam <- c("Block", "GCA", "RGCA", "tSCA", "RSCA", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + overlay(Par1, Par2):dr +
combination + combination:dr
rnam <- c("GCA", "RGCA", "tSCA", "RSCA", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2) + overlay(Par1, Par2):dr +
combination
rnam <- c("GCA", "RGCA", "tSCA", "RSCA")
}
}else if(fct == "HAYMAN2"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Block + crosses + overlay(Par1, Par2) + overlay(Par1, Par2):dr +
overlay(Par1, Par2):selfs + combination + combination:dr
rnam <- c("Block", "MDD", "GCA", "RGCA", "DD", "SCA", "RSCA", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ crosses + overlay(Par1, Par2) + overlay(Par1, Par2):dr +
overlay(Par1, Par2):selfs + combination + combination:dr
rnam <- c("MDD", "GCA", "RGCA", "DD", "SCA", "RSCA", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ crosses + overlay(Par1, Par2) + overlay(Par1, Par2):dr +
overlay(Par1, Par2):selfs + combination
rnam <- c("MDD", "GCA", "RGCA", "DD", "SCA", "RSCA")
}
}else if(fct == "GRIFFING1"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + combination + combination:dr
rnam <- c("Block", "GCA", "tSCA", "REC", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + combination + combination:dr
rnam <- c("GCA", "tSCA", "REC", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2) + combination
rnam <- c("GCA", "tSCA", "REC")
}
}else if(fct == "GRIFFING3"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + combination + combination:dr
rnam <- c("Block", "GCA", "SCA", "REC", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + combination + combination:dr
rnam <- c("GCA", "SCA", "REC", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2) + combination
rnam <- c("GCA", "SCA", "REC")
}
} else if(fct == "GRIFFING2"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + combination
rnam <- c("Block", "GCA", "tSCA", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + combination
rnam <- c("GCA", "tSCA", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2)
rnam <- c("GCA", "tSCA")
}
} else if(fct == "GRIFFING4"){
formFix <- Y ~ 1
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + combination
rnam <- c("Block", "GCA", "SCA", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + combination
rnam <- c("GCA", "SCA", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2)
rnam <- c("GCA", "SCA")
}
} else if(fct == "GE2r"){
formFix <- Y ~ crosses
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + overlay(Par1, Par2):crosses +
combination:crosses + combination:crosses:dr
rnam <- c("Block", "Variety", "h.i", "SCA", "Reciprocals", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + overlay(Par1, Par2):crosses +
combination:crosses + combination:crosses:dr
rnam <- c("Variety", "h.i", "SCA", "Reciprocals", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2) + overlay(Par1, Par2):crosses +
combination:crosses
rnam <- c("Variety", "h.i", "SCA", "Reciprocals")
}
} else if(fct == "GE2"){
formFix <- Y ~ crosses
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2) + overlay(Par1, Par2):crosses +
combination:crosses
rnam <- c("Block", "Variety", "h.i", "SCA", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2) + overlay(Par1, Par2):crosses +
combination:crosses
rnam <- c("Variety", "h.i", "SCA", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2) + overlay(Par1, Par2):crosses
rnam <- c("Variety", "h.i", "SCA")
}
} else if(fct == "GE3r"){
formFix <- Y ~ crosses
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2):crosses + Par1:selfs +
combination:crosses + combination:crosses:dr
rnam <- c("Block", "GCAC", "Selfed par.", "SCA", "Reciprocals", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2):crosses + Par1:selfs +
combination:crosses + combination:crosses:dr
rnam <- c("GCAC", "Selfed par.", "SCA", "Reciprocals", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2):crosses + Par1:selfs +
combination:crosses
rnam <- c("GCAC", "Selfed par.", "SCA", "Reciprocals")
}
} else if(fct == "GE3"){
formFix <- Y ~ crosses
if(!is.null(Block)){
form <- ~ Block + overlay(Par1, Par2):crosses + Par1:selfs +
combination:crosses
rnam <- c("Block", "GCAC", "Selfed par.", "SCA", "Residuals")
} else if(is.null(Block) & withRep == T){
form <- ~ overlay(Par1, Par2):crosses + Par1:selfs +
combination:crosses
rnam <- c("GCAC", "Selfed par.", "SCA", "Residuals")
} else if(is.null(Block) & withRep == F){
form <- ~ overlay(Par1, Par2):crosses + Par1:selfs
rnam <- c("GCAC", "Selfed par.", "SCA")
}
}
}
modh <- sommer::mmer(formFix,
random = form,
verbose = F,
data = df)
vc <- summary(modh)$varcomp[,-c(3:4)]
beta <- summary(modh)$beta
row.names(vc) <- rnam
returnList <- list(mod = modh, beta = beta, varcomp = vc)
return(returnList)
}
|
pp_complete <- function(D, year.range = NULL,
Instrument.set = NULL, Target.set = NULL) {
if (!is.null(year.range)) {
if (sum(which(!(unique(D$Year) %in% seq(year.range[1], year.range[2])))) > 0) {
stop("The original object contains years outside the range provided.")
}
} else {
year.range <- range(D$Year)
}
if (!is.null(Instrument.set)) {
if (sum(which(!(which(unique(D$Instrument) %in% Instrument.set)))) > 0) {
stop("The original object contains instruments that are not present in the full set of instruments provided.")
}
} else {
Instrument.set <- levels(D$Instrument)
}
if (!is.null(Target.set)) {
if (sum(which(!(which(unique(D$Target) %in% Target.set)))) > 0) {
stop("The original object contains targets that are not present in the full set of targets provided.")
}
} else {
Target.set <- levels(D$Target)
}
Original <- D
Full <- expand.grid(Country = levels(Original$Country),
Sector = levels(Original$Sector),
Year = as.integer(seq(year.range[1], year.range[2])),
Instrument = Instrument.set,
Target = Target.set) %>%
as_tibble()
D <- suppressWarnings(dplyr::left_join(Full, Original,
by = c("Country", "Sector", "Year", "Instrument", "Target"))) %>%
dplyr::mutate(covered = ifelse(is.na(covered), 0, covered)) %>%
dplyr::mutate(Instrument = factor(Instrument, levels = Instrument.set)) %>%
dplyr::mutate(Target= factor(Target, levels = Target.set))
message(paste("The original size of the data frame was ", dim(Original)[1], " observations.", sep = ""))
message(paste("The size of the transformed data frame is now ", dim(D)[1], " observations.", sep = ""))
message(paste(" Country: ", length(levels(Original$Country)), " -> ", length(levels(D$Country)), sep = ""))
message(paste(" Year: ", length(unique(Original$Year)), " -> ", length(unique(D$Year)), sep = ""))
message(paste(" Instrument: ", length(levels(Original$Instrument)), " -> ", length(levels(D$Instrument)), sep = ""))
message(paste(" Target: ", length(levels(Original$Target)), " -> ", length(levels(D$Target)), sep = ""))
return(D)
}
|
setClass(
"equation_directional",
contains = "equation_basic",
representation(
separation_subset = "vector"
),
prototype(
separation_subset = NULL
)
)
setMethod(
"initialize", "equation_directional",
function(.Object, specification, data, name, prefix, separation_subset) {
.Object <- callNextMethod(.Object, specification, data, name, prefix)
.Object@separation_subset <- separation_subset
.Object
}
)
|
ssp.plot <-
function(block, pplot, splot, ssplot, Y)
{
name.y <- paste(deparse(substitute(Y)))
name.r <- paste(deparse(substitute(block)))
name.p <- paste(deparse(substitute(pplot)))
name.sp <- paste(deparse(substitute(splot)))
name.ssp <- paste(deparse(substitute(ssplot)))
block<-as.factor(block)
pplot<-as.factor(pplot)
splot<-as.factor(splot)
ssplot<-as.factor(ssplot)
cat("\nANALYSIS SPLIT-SPLIT PLOT: ", name.y, "\nClass level information\n\n")
nrep <- length(unique(block))
np <- length(unique(pplot))
nsp <- length(unique(splot))
nssp<- length(unique(ssplot))
cat(name.p, "\t: ",unique(as.character(pplot)),"\n")
cat(name.sp, "\t: ",unique(as.character(splot)),"\n")
cat(name.ssp,"\t: ",unique(as.character(ssplot)),"\n")
cat(name.r, "\t: ",unique(as.character(block)),"\n")
cat("\nNumber of observations: ", length(Y), "\n\n")
model<- aov(Y ~ block*pplot*splot*ssplot)
B<-suppressWarnings(anova(model))
W<-NULL
W<-B[c(1,2,16,3,7,16,4,9,10,14,16),]
for (j in 1:2){
W[3,j]<-B[5,j]
W[6,j]<-B[6,j]+B[11,j]
W[11,j]<-B[8,j]+B[12,j]+B[13,j]+B[15,j]
}
W[,3]<-W[,2]/W[,1]
W[2,4]<-W[2,3]/W[3,3]
W[4:5,4]<-W[4:5,3]/W[6,3]
W[7:10,4]<-W[7:10,3]/W[11,3]
W[2,5]<-1-pf(W[2,4],W[2,1],W[3,1])
W[4:5,5]<-1-pf(W[4:5,4],W[4:5,1],W[6,1])
W[7:10,5]<-1-pf(W[7:10,4],W[7:10,1],W[11,1])
N<-NULL
N[1]<- name.r
N[2]<- name.p
N[3]<- "Ea"
N[4]<- name.sp
N[5]<- paste(name.p,":",name.sp,sep="")
N[6]<- "Eb"
N[7]<- name.ssp
N[8]<- paste(name.ssp,":",name.p,sep="")
N[9]<- paste(name.ssp,":",name.sp,sep="")
N[10]<-paste(name.ssp,":",name.p,":",name.sp,sep="")
N[11]<- "Ec"
rownames(W)<-N
attributes(W)$heading[2]<-paste("Response:",name.y)
print(W)
medy <- mean(Y,na.rm=TRUE)
gl.a<-W[3,1]; Ea<-W[3,3]
gl.b<-W[6,1]; Eb<-W[6,3]
gl.c<-W[11,1]; Ec<-W[11,3]
cat("\ncv(a) =",round(sqrt(Ea)*100/medy,1),"%,",
"cv(b) =",round(sqrt(Eb)*100/medy,1),"%,",
"cv(c) =",round(sqrt(Ec)*100/medy,1),"%,","Mean =", medy,"\n\n")
output<-list(ANOVA=W, gl.a=gl.a,gl.b=gl.b,gl.c=gl.c,Ea=Ea,Eb=Eb,Ec=Ec)
invisible(output)
}
|
interval_labels <- function(cuts, digits = NULL, right_closed = TRUE) {
if (is.numeric(cuts)) {
if (is.null(digits)) {
cuts <- scales::comma(cuts)
} else cuts <- scales::comma(cuts, accuracy = 10 ^ -digits)
labels <- vector("character", 0)
cuts_no <- length(cuts)
sign1 <- ifelse(right_closed == TRUE, "\u2264", "<")
sign2 <- ifelse(right_closed == TRUE, ">", "\u2265")
if (cuts_no == 2) {
labels <- c("Feature")
}
else if (cuts_no == 3) {
labels <- c(paste0(sign1, cuts[2]), paste0(sign2, cuts[2]))
}
else if (cuts_no > 3) {
for (i in 2:(length(cuts) - 2)) {
temp <- paste0(cuts[i], "\u2013", cuts[i + 1])
labels <- c(labels, temp)
}
labels <-
c(paste0(sign1, cuts[2]),
labels,
paste0(sign2, cuts[length(cuts) - 1]))
}
}
else {
right_closed <- ifelse(stringr::str_sub(cuts[1], -1L, -1L) == "]", TRUE, FALSE)
labels <- stringr::str_replace_all(stringr::str_replace_all(cuts, ", ", "\u2013"), "\\[|\\]|\\)|\\(", "")
sign1 <- ifelse(right_closed == TRUE, "\u2264", "<")
sign2 <- ifelse(right_closed == TRUE, ">", "\u2265")
labels[1] <- glue::glue("{sign1}{stringr::word(labels[2], sep = '\u2013')}")
if (stringr::str_detect(tidyr::replace_na(labels[length(labels)], "NA"), "NA")) {
labels[length(labels) - 1] <- glue::glue("{sign2}{stringr::word(labels[length(labels) - 1], 1, sep = '\u2013')}")
} else {
labels[length(labels)] <- glue::glue("{sign2}{stringr::word(labels[length(labels)], 1, sep = '\u2013')}")
}
}
return(labels)
}
sv_interval_labels_num <- function(cuts, format = NULL, right_closed = TRUE) {
if (is.null(format)) {
cuts <- scales::number(cuts, big.mark = ",")
} else cuts <- format(cuts)
labels <- vector("character", 0)
cuts_no <- length(cuts)
sign1 <- ifelse(right_closed == TRUE, "\u2264", "<")
sign2 <- ifelse(right_closed == TRUE, ">", "\u2265")
if (cuts_no == 2) {
labels <- c("Feature")
}
else if (cuts_no == 3) {
labels <- c(paste0(sign1, cuts[2]), paste0(sign2, cuts[2]))
}
else if (cuts_no > 3) {
for (i in 2:(length(cuts) - 2)) {
temp <- paste0(cuts[i], "\u2013", cuts[i + 1])
labels <- c(labels, temp)
}
labels <-
c(paste0(sign1, cuts[2]),
labels,
paste0(sign2, cuts[length(cuts) - 1]))
}
return(labels)
}
sv_interval_labels_chr <- function(cuts) {
right_closed <- ifelse(stringr::str_sub(cuts[1], -1L, -1L) == "]", TRUE, FALSE)
labels <- stringr::str_replace_all(stringr::str_replace_all(cuts, ", ", "\u2013"), "\\[|\\]|\\)|\\(", "")
sign1 <- ifelse(right_closed == TRUE, "\u2264", "<")
sign2 <- ifelse(right_closed == TRUE, ">", "\u2265")
labels[1] <- glue::glue("{sign1}{stringr::word(labels[2], sep = '\u2013')}")
if (stringr::str_detect(tidyr::replace_na(labels[length(labels)], "NA"), "NA")) {
labels[length(labels) - 1] <- glue::glue("{sign2}{stringr::word(labels[length(labels) - 1], 1, sep = '\u2013')}")
} else {
labels[length(labels)] <- glue::glue("{sign2}{stringr::word(labels[length(labels)], 1, sep = '\u2013')}")
}
return(labels)
}
|
meanValue <-
function() {
showPANmnvl <- function() {
refreshDataSetsList(outp = FALSE)
createSubPanR4C1()
createTITLE(labTitle = "MEAN VALUE")
if (is.null(KTSEnv$dSList$gaps) == FALSE) {
createGapRb()
}
createTsRb()
createEntry(labTitle = "Period(in lags)", textVariableName = "period")
createEntry(labTitle = "Number of periods around",
textVariableName = "perWindow")
createEntry(labTitle = "Maximum number of iterations",
textVariableName = "maxniter")
createEntry(labTitle = "Minimum number of observations (one side)",
textVariableName = "mininumNObs")
createEntry(labTitle = "Statistic", textVariableName = "mediaona",
defaultVal = "median")
createOK(labTitle = "RUN", action = mnvlOnOk)
tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both")
}
mnvlOnOk <- function() {
selTsName <- verifyCharEntry(tcltk::tclvalue(KTSEnv$selTsP),
noValid = NA)
statistic <- verifyCharEntry(tcltk::tclvalue(KTSEnv$mediaona))
lPeriod <- verifyIntEntry(tcltk::tclvalue(KTSEnv$period),
noValid = NA)
nPeriods <- verifyIntEntry(tcltk::tclvalue(KTSEnv$perWindow),
noValid = NA)
maxIter <- verifyIntEntry(tcltk::tclvalue(KTSEnv$maxniter),
noValid = NA)
minPoints <- verifyIntEntry(tcltk::tclvalue(KTSEnv$mininumNObs),
noValid = NA)
if (is.na(selTsName)) {
tcltk::tkmessageBox(message = "Choose a time series",
icon = "warning")
} else if (is.na(lPeriod)) {
tcltk::tkmessageBox(message = paste("Enter the period",
"of the phenomenon in gaps"),
icon = "warning")
} else if (is.na(nPeriods)) {
tcltk::tkmessageBox(message = paste("Enter the number of",
"periods to use around the gap"),
icon = "warning")
} else if (lPeriod == 0) {
tcltk::tkmessageBox(message = paste("The period length must be,",
"at least, 1 (lag)"),
icon = "warning")
} else if (nPeriods < 2) {
tcltk::tkmessageBox(message = paste("The number of periods must be at",
"least 2 (one at each side)"),
icon = "warning")
} else if (is.na(maxIter)) {
tcltk::tkmessageBox(message = paste("Enter the maximum number of times",
"the process will be applied"),
icon = "warning")
} else if (is.na(statistic)) {
tcltk::tkmessageBox(message = paste("Enter the statistic:",
"median or mean"),
icon = "warning")
} else if (statistic != "mean" & statistic != "median") {
tcltk::tkmessageBox(message = paste("The statistic can be",
"median or mean"),
icon = "warning")
} else {
if (is.na(minPoints)) {
minPoints <- 0
}
if (nPeriods%%2 == 1) {
nPeriods <- nPeriods + 1
}
halfNPeriods <- nPeriods/2
selTs <- get(selTsName, envir = KTSEnv)
gapToUse <- gapForSelMethod(selTsName, selTs)
selGap <- gapToUse$selGap
selGapName <- gapToUse$selGapName
nasInSelTs <- which(is.na(selTs$value))
tmComptibility <- areTsGapTimeCompatible(selTs, selGap)
if (length(nasInSelTs) == 0) {
tcltk::tkmessageBox(message = paste("The selected time",
"series contains no NAs"),
icon = "warning")
} else if (length(selGap$gaps) == 0) {
tcltk::tkmessageBox(message = "The gap set is empty",
icon = "warning")
} else if (length(setdiff(union(selGap$gaps, nasInSelTs),
nasInSelTs)) != 0) {
tcltk::tkmessageBox(message = paste("Some NAs in the gap set do",
"not exist in the time series.",
"Check that the selected gap set",
"comes from the selected",
"time series"),
icon = "warning")
} else if (tmComptibility[1] == FALSE) {
tcltk::tkmessageBox(message = paste("The initial date of the time",
"series and the one stored",
"in the gap set do not match"),
icon = "warning")
} else if (tmComptibility[2] == FALSE) {
tcltk::tkmessageBox(message = paste("The sampling period of the",
"time series and the one stored",
"in the gap set do not match"),
icon = "warning")
} else if (tmComptibility[3] == FALSE) {
tcltk::tkmessageBox(message = paste("The time series is shorter",
"than some indices stored",
"in the set of gaps"),
icon = "warning")
} else if (minPoints > halfNPeriods) {
tcltk::tkmessageBox(message = paste("The minimum number of",
"observations must not excede",
"half the number of periods"),
icon = "warning")
} else {
getCentrVal <- function(NAInd, TSV, widthAround,
lPeriod, minPoints,
statistic = "mean") {
lTS <- length(TSV)
eqP <- seq(NAInd - widthAround,
NAInd + widthAround,
lPeriod)
eqP <- eqP[eqP > 0 & eqP <= lTS]
anaobi1 <- is.finite(TSV[eqP[which(eqP < NAInd)]])
anaobi2 <- is.finite(TSV[eqP[which(eqP >NAInd)]])
pointsBefore <- which(anaobi1)
pointsAfter <- which(anaobi2)
pointsBefore <- length(pointsBefore)
pointsAfter <- length(pointsAfter)
if (pointsBefore < minPoints | pointsAfter < minPoints) {
res <- NA
}else if (statistic == "mean") {
res <- mean(TSV[eqP], na.rm = TRUE)
}else{
res <- stats::median(TSV[eqP], na.rm = TRUE)
}
res
}
getValsOneIte <- function(gaps,TSVI, widthAround,
lPeriod, minPoints,
statistic = "mean"){
replacements <- sapply(gaps, FUN = getCentrVal,
minPoints = minPoints,
TSV = TSVI,
widthAround = widthAround,
lPeriod = lPeriod,
statistic = statistic)
replacements[which(is.finite(replacements) == FALSE)] <- NA
replacements
}
fillGapsMV <- function(gaps, TS, maxIter, widthAround,
lPeriod, minPoints,statistic = "mean") {
cont <- 1
remainingGaps <- length(gaps)
while (cont <= maxIter & length(gaps) != 0) {
replacements <- getValsOneIte(gaps = gaps,
TSVI = TS$value,
widthAround = widthAround,
lPeriod = lPeriod,
minPoints = minPoints,
statistic = statistic)
TS$value[gaps] <- replacements
gapsNow <- intersect(which(is.na(TS$value)),gaps)
remainingGaps <- c(remainingGaps, length(gapsNow))
gaps <- gapsNow
cont <- cont + 1
rm(replacements)
}
resultMV <- list(filled = TS, gaps = gaps,
iterations = cont,
advances = remainingGaps)
rownames(resultMV$filled) <- NULL
resultMV
}
widthAround <- halfNPeriods * lPeriod
resMeVal <- fillGapsMV(gaps = selGap$gaps,
TS = selTs,
maxIter = maxIter,
widthAround = widthAround,
lPeriod = lPeriod,
minPoints = minPoints,
statistic = statistic)
filledTS <- resMeVal$filled
assign(paste0(selTsName, "_", selGapName, "_mvl"),
filledTS, envir = KTSEnv)
gapsAfterFill <- getGapsAfterFill(filledTS, selGap,
envir = environment(mnvlOnOk))
remainingNAsInGap <- gapsAfterFill$remainingNAsInGap
filledNasTable <- gapsAfterFill$filledNasTable
sampPerSec <- diff(as.numeric(selTs$time[1:2]))
txtParam <- c(paste("Period(sec):", lPeriod * sampPerSec),
paste("Periods around:",nPeriods),
paste("Minimum number of observations to each side:",
minPoints),
paste("NAs to fill per iteration:",
paste(resMeVal$advances, collapse = ",")))
writeMethodTitle("MEAN/MEDIAN VALUE")
tcltk::tkinsert(KTSEnv$txtWidget, "end",
paste(txtParam, collapse = "\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end", "\n")
writeMethodSummary(filledNasTable, remainingNAsInGap, selTsName,
selGapName, selGap)
endingLines()
cleanEnvir()
refreshDataSetsList(outp = FALSE)
showPANmnvl()
}
}
}
cleanEnvir()
refreshDataSetsList(outp = FALSE)
checkIfAnyTs(action = "showPANmnvl", envirName = environment(showPANmnvl))
}
|
es_stats <- function(index=NULL, type=NULL, metric=NULL, raw=FALSE,
callopts=list(), verbose=TRUE, ...) {
es_GET('_stats', index, type, metric, NULL, 'elastic_stats', raw, callopts, ...)
}
|
package.env <- NULL
.onLoad <- function(libname, pkgname) {
if (Sys.info()["sysname"] == "Darwin") {
Sys.setenv("VECLIB_MAXIMUM_THREADS" = "1")
}
op <- options()
op.rMVP <- list(
rMVP.OutputLog2File = TRUE
)
toset <- !(names(op.rMVP) %in% names(op))
if (any(toset)) {
options(op.rMVP[toset])
}
package.env <<- new.env()
return(invisible())
}
.onAttach <- function(...){
packageStartupMessage("Full description, Bug report, Suggestion and the latest version:")
packageStartupMessage("https://github.com/xiaolei-lab/rMVP")
}
|
library(miRetrieve)
library(testthat)
df_snp <- data.frame("SNP" = c("rs4544 rs3655 test",
"test test",
"rs3655"),
"PMID" = seq(1:3))
df_snp_extract <- extract_snp(df_snp,
col.abstract = SNP)
df_snp_extract_i <- extract_snp(df_snp,
col.abstract = SNP,
indicate = TRUE)
df_snp_extract_d <- extract_snp(df_snp,
col.abstract = SNP,
discard = TRUE)
test_that("Tests that SNPs are correctly recognized in data.frames", {
expect_gte(ncol(df_snp_extract), ncol(df_snp))
expect_gte(ncol(df_snp_extract_i), ncol(df_snp_extract))
expect_lte(nrow(df_snp_extract_d), nrow(df_snp))
})
df_snp_count <- count_snp(df_snp_extract_d)
test_that("Tests that SNPs are counted", {
expect_equal(typeof(df_snp_count), "list")
expect_equal(ncol(df_snp_count), 2)
})
top_snp <- get_snp(df_snp_extract_d, top = 1)
test_that("Tests that SNPs are extracted from data.frame", {
expect_equal(typeof(top_snp), "character")
expect_equal(length(top_snp), 1)
})
df_snp_subset <- subset_snp(df_snp_extract,
top_snp)
test_that("Tests that SNPs are extracted from data.frame", {
expect_equal(nrow(df_snp_subset), 2)
expect_equal(length(unique(df_snp_subset[["SNPs"]])), 1)
})
|
"schaper2019"
|
"diccionario_aglomerados"
|
NULL
rows_insert <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
lifecycle::signal_stage("experimental", "rows_insert()")
UseMethod("rows_insert")
}
rows_insert.data.frame <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
check_dots_empty()
key <- rows_check_key(by, x, y)
y <- auto_copy(x, y, copy = copy)
rows_df_in_place(in_place)
rows_check_key_df(x, key, df_name = "x")
rows_check_key_df(y, key, df_name = "y")
idx <- vctrs::vec_match(y[key], x[key])
bad <- which(!is.na(idx))
if (has_length(bad)) {
abort("Attempting to insert duplicate rows.")
}
rows_bind(x, y)
}
rows_update <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
lifecycle::signal_stage("experimental", "rows_update()")
UseMethod("rows_update", x)
}
rows_update.data.frame <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
check_dots_empty()
key <- rows_check_key(by, x, y)
y <- auto_copy(x, y, copy = copy)
rows_df_in_place(in_place)
rows_check_key_df(x, key, df_name = "x")
rows_check_key_df(y, key, df_name = "y")
idx <- vctrs::vec_match(y[key], x[key])
bad <- which(is.na(idx))
if (has_length(bad)) {
abort("Attempting to update missing rows.")
}
x[idx, names(y)] <- y
x
}
rows_patch <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
lifecycle::signal_stage("experimental", "rows_patch()")
UseMethod("rows_patch", x)
}
rows_patch.data.frame <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
check_dots_empty()
key <- rows_check_key(by, x, y)
y <- auto_copy(x, y, copy = copy)
rows_df_in_place(in_place)
rows_check_key_df(x, key, df_name = "x")
rows_check_key_df(y, key, df_name = "y")
idx <- vctrs::vec_match(y[key], x[key])
bad <- which(is.na(idx))
if (has_length(bad)) {
abort("Can't patch missing row.")
}
new_data <- map2(x[idx, names(y)], y, coalesce)
x[idx, names(y)] <- new_data
x
}
rows_upsert <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
lifecycle::signal_stage("experimental", "rows_upsert()")
UseMethod("rows_upsert", x)
}
rows_upsert.data.frame <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
check_dots_empty()
key <- rows_check_key(by, x, y)
y <- auto_copy(x, y, copy = copy)
rows_df_in_place(in_place)
rows_check_key_df(x, key, df_name = "x")
rows_check_key_df(y, key, df_name = "y")
idx <- vctrs::vec_match(y[key], x[key])
new <- is.na(idx)
idx_existing <- idx[!new]
idx_new <- idx[new]
x[idx_existing, names(y)] <- vec_slice(y, !new)
rows_bind(x, vec_slice(y, new))
}
rows_delete <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
lifecycle::signal_stage("experimental", "rows_delete()")
UseMethod("rows_delete", x)
}
rows_delete.data.frame <- function(x, y, by = NULL, ..., copy = FALSE, in_place = FALSE) {
check_dots_empty()
key <- rows_check_key(by, x, y)
y <- auto_copy(x, y, copy = copy)
rows_df_in_place(in_place)
rows_check_key_df(x, key, df_name = "x")
rows_check_key_df(y, key, df_name = "y")
extra_cols <- setdiff(names(y), key)
if (has_length(extra_cols)) {
bullets <- glue("Ignoring extra columns: ", commas(tick_if_needed(extra_cols)))
inform(bullets, class = c("dplyr_message_delete_extra_cols", "dplyr_message"))
}
idx <- vctrs::vec_match(y[key], x[key])
bad <- which(is.na(idx))
if (has_length(bad)) {
abort("Can't delete missing row.")
}
dplyr_row_slice(x, -idx)
}
rows_check_key <- function(by, x, y, error_call = caller_env()) {
if (is.null(by)) {
by <- names(y)[[1]]
msg <- glue("Matching, by = \"{by}\"")
inform(msg, class = c("dplyr_message_matching_by", "dplyr_message"))
}
if (!is.character(by) || length(by) == 0) {
abort("`by` must be a character vector.", call = error_call)
}
if (any(names2(by) != "")) {
abort("`by` must be unnamed.", call = error_call)
}
bad <- setdiff(colnames(y), colnames(x))
if (has_length(bad)) {
abort("All columns in `y` must exist in `x`.", call = error_call)
}
by
}
rows_check_key_df <- function(df, by, df_name, error_call = caller_env()) {
y_miss <- setdiff(by, colnames(df))
if (length(y_miss) > 0) {
msg <- glue("All `by` columns must exist in `{df_name}`.")
abort(msg, call = error_call)
}
if (vctrs::vec_duplicate_any(df[by])) {
msg <- glue("`{df_name}` key values must be unique.")
abort(msg, call = error_call)
}
}
rows_df_in_place <- function(in_place, error_call = caller_env()) {
if (is_true(in_place)) {
msg <- "Data frames only support `in_place = FALSE`."
abort(msg, call = error_call)
}
}
rows_bind <- function(x, y) {
dplyr_reconstruct(vctrs::vec_rbind(x, y), x)
}
|
summary_patristic_matrix_array <- function(patristic_matrix_array, fn = stats::median) {
return(apply(patristic_matrix_array, MARGIN = c(1, 2), fn, na.rm = TRUE))
}
datelife_result_study_index <- function(datelife_result,
cache = "opentree_chronograms") {
if ("opentree_chronograms" %in% cache) {
utils::data("opentree_chronograms")
cache <- get("opentree_chronograms")
}
return(which(names(cache$trees) %in% names(datelife_result)))
}
get_subset_array_dispatch <- function(study_element,
taxa, phy = NULL,
phy4 = NULL,
dating_method = "PATHd8") {
if (class(study_element) == "array") {
return(patristic_matrix_array_subset_both(study_element, taxa, phy, phy4, dating_method))
} else {
return(phylo_subset_both(reference_tree = study_element, taxa = taxa, phy = phy, phy4 = phy4, dating_method = dating_method))
}
}
results_list_process <- function(results_list, taxa = NULL, partial = FALSE) {
if (is.null(taxa)) {
taxa <- unique(unname(unlist(lapply(final_matrices, rownames))))
}
patristic.matrices <- lapply(results_list, "[[", "patristic_matrix_array")
final_matrices <- patristic.matrices[!is.na(patristic.matrices)]
if (length(final_matrices) > 0) {
if (!partial) {
final_matrices <- final_matrices[sapply(final_matrices, patristic_matrix_taxa_all_matching, taxa = taxa)]
}
to.delete <- c()
for (i in sequence(length(final_matrices))) {
if (all(is.na(final_matrices[[i]]))) {
to.delete <- c(to.delete, i)
}
}
if (length(to.delete) > 0) {
final_matrices <- final_matrices[-to.delete]
}
}
return(final_matrices)
}
patristic_matrix_taxa_all_matching <- function(patristic_matrix, taxa) {
return(sum(!(taxa %in% rownames(patristic_matrix))) == 0)
}
patristic_matrix_array_subset_both <- function(patristic_matrix_array, taxa, phy = NULL, phy4 = NULL, dating_method = "PATHd8") {
if (is.null(phy)) {
return(patristic_matrix_array_subset(patristic_matrix_array = patristic_matrix_array, taxa = taxa, phy4 = phy4))
} else {
return(patristic_matrix_array_congruify(patristic_matrix_array = patristic_matrix_array, taxa = taxa, phy = phy, dating_method))
}
}
patristic_matrix_array_subset <- function(patristic_matrix_array, taxa, phy4 = NULL) {
patristic_matrix_array <- patristic_matrix_array[rownames(patristic_matrix_array) %in% taxa, colnames(patristic_matrix_array) %in% taxa, ]
problem <- "none"
final.size <- sum(rownames(patristic_matrix_array) %in% taxa)
if (final.size < length(taxa)) {
problem <- "missing some taxa on chronogram, so this is probably an underestimate"
if (final.size < 2) {
problem <- "insufficient coverage"
patristic_matrix_array <- NA
}
}
if (!is.null(phy4)) {
if (length(phylobase::descendants(phy4, phylobase::MRCA(phy4, taxa), type = "tips")) > taxa) {
problem <- "set of taxa not a clade, so this is probably an overestimate"
}
}
return(list(patristic_matrix_array = patristic_matrix_array, problem = problem))
}
patristic_matrix_array_congruify <- function(patristic_matrix_array,
taxa,
phy = NULL,
dating_method = "PATHd8") {
patristic_matrix_array <- patristic_matrix_array[rownames(patristic_matrix_array) %in% taxa, colnames(patristic_matrix_array) %in% taxa, ]
problem <- "none"
final.size <- sum(rownames(patristic_matrix_array) %in% taxa)
if (final.size < length(taxa)) {
problem <- "missing some taxa on chronogram, so this is probably an underestimate"
if (final.size < 3) {
problem <- "insufficient coverage"
patristic_matrix_array <- NA
return(list(patristic_matrix_array = patristic_matrix_array, problem = problem))
}
}
patristic_matrix_list <- patristic_matrix_array_split(patristic_matrix_array)
patristic_matrix_array <- patristic_matrix_list_to_array(lapply(patristic_matrix_list, patristic_matrix_array_phylo_congruify, target_tree = phy, scale = dating_method))
return(list(patristic_matrix_array = patristic_matrix_array, problem = problem))
}
patristic_matrix_array_split <- function(patristic_matrix_array) {
asub_for_lapply <- function(idx, x, dims = 3) {
return(abind::asub(x, idx, dims))
}
return(lapply(sequence(dim(patristic_matrix_array)[3]), asub_for_lapply, patristic_matrix_array))
}
patristic_matrix_list_to_array <- function(patristic_matrix_list, pad = TRUE) {
all_taxa <- sort(unique(unname(unlist(lapply(patristic_matrix_list, rownames)))))
if (pad) {
patristic_matrix_list <- lapply(patristic_matrix_list, patristic_matrix_pad, all_taxa = all_taxa)
}
original.size <- length(patristic_matrix_list)
patristic_matrix_list <- lapply(patristic_matrix_list, patristic_matrix_name_reorder)
if (length(patristic_matrix_list) < 1) {
stop(paste0("The patristic matrices you are trying to bind are too few; input was ", original.size, " and current length is ", length(patristic_matrix_list)))
}
standard.rownames <- rownames(patristic_matrix_list[[1]])
standard.colnames <- colnames(patristic_matrix_list[[1]])
matching.names <- sapply(patristic_matrix_list, patristic_matrix_name_order_test, standard.rownames, standard.colnames)
if (sum(matching.names) != length(matching.names)) {
stop("The patristic matrices you are trying to bind do not have the same taxa")
}
return(abind::abind(patristic_matrix_list, along = 3))
}
patristic_matrix_pad <- function(patristic_matrix, all_taxa) {
number.missing <- length(all_taxa) - dim(patristic_matrix)[1]
final_matrix <- patristic_matrix
if (number.missing > 0) {
final_matrix <- rbind(patristic_matrix, matrix(nrow = number.missing, ncol = dim(patristic_matrix)[2]))
final_matrix <- cbind(final_matrix, matrix(ncol = number.missing, nrow = dim(final_matrix)[1]))
rownames(final_matrix) <- c(rownames(patristic_matrix), all_taxa[-which(all_taxa %in% rownames(patristic_matrix))])
colnames(final_matrix) <- c(colnames(patristic_matrix), all_taxa[-which(all_taxa %in% colnames(patristic_matrix))])
}
return(patristic_matrix_name_reorder(final_matrix))
}
patristic_matrix_name_reorder <- function(patristic_matrix) {
return(patristic_matrix[order(rownames(patristic_matrix)), order(colnames(patristic_matrix))])
}
patristic_matrix_name_order_test <- function(patristic_matrix,
standard.rownames,
standard.colnames) {
if (compare::compare(rownames(patristic_matrix), standard.rownames)$result != TRUE) {
return(FALSE)
}
if (compare::compare(colnames(patristic_matrix), standard.colnames)$result != TRUE) {
return(FALSE)
}
return(TRUE)
}
patristic_matrix_array_phylo_congruify <- function(patristic_matrix,
target_tree,
dating_method = "PATHd8",
attempt_fix = TRUE) {
result_matrix <- matrix(nrow = dim(patristic_matrix)[1], ncol = dim(patristic_matrix)[2])
if (is.null(target_tree$edge.length)) {
target_tree$edge.length <- numeric(nrow(target_tree$edge))
}
try(result_matrix <- phylo_to_patristic_matrix(congruify_and_check(
reference = patristic_matrix_to_phylo(patristic_matrix),
target = target_tree, scale = dating_method, attempt_fix = attempt_fix
)))
return(result_matrix)
}
phylo_to_patristic_matrix <- function(phy, test = TRUE, tol = 0.01, option = 2) {
patristic_matrix <- NA
if (class(phy) == "phylo") {
if (test) {
if (!ape::is.ultrametric(phy, tol = tol, option = option)) {
stop("Currently, datelife require that chronograms are ultrametric.")
}
}
patristic_matrix <- stats::cophenetic(phy)
}
return(patristic_matrix)
}
phylo_subset_both <- function(reference_tree,
taxa,
phy = NULL,
phy4 = NULL,
dating_method = "PATHd8") {
congruify <- FALSE
if (inherits(phy, "phylo")) {
congruify <- TRUE
} else {
congruify <- FALSE
}
if (congruify) {
return(phylo_get_subset_array_congruify(reference_tree = reference_tree,
taxa = taxa,
phy = phy,
dating_method = dating_method))
} else {
return(phylo_get_subset_array(reference_tree = reference_tree,
taxa = taxa,
phy4 = phy4,
dating_method = dating_method))
}
}
phylo_get_subset_array <- function(reference_tree,
taxa,
phy4 = NULL,
dating_method = "PATHd8") {
final.size <- sum(reference_tree$tip.label %in% taxa)
if (final.size >= 2) {
reference_tree <- phylo_prune_missing_taxa(reference_tree, taxa)
}
problem <- "none"
patristic_matrix_array <- NA
if (final.size < length(taxa)) {
problem <- "Missing some taxa on chronogram, so this is probably an underestimate."
if (final.size < 2) {
problem <- "Insufficient species to get an MRCA (either 1 or 0)."
patristic_matrix_array <- NA
}
}
if (final.size >= 2) {
patristic_matrix_array <- phylo_to_patristic_matrix(reference_tree)
}
if (!is.null(phy4)) {
if (length(phylobase::descendants(phy4, phylobase::MRCA(phy4, taxa), type = "tips")) > taxa) {
problem <- "'input' of taxa are not a clade, so this is probably an overestimate."
}
}
return(list(patristic_matrix_array = patristic_matrix_array, problem = problem))
}
phylo_get_subset_array_congruify <- function(reference_tree,
taxa,
phy = NULL,
dating_method = "PATHd8") {
final.size <- sum(reference_tree$tip.label %in% taxa)
if (final.size >= 2) {
reference_tree <- phylo_prune_missing_taxa(reference_tree, taxa)
}
problem.new <- "none"
patristic_matrix_array.new <- NA
if (final.size < length(taxa)) {
problem.new <- "missing some taxa on chronogram, so this is probably an underestimate"
if (final.size < 3) {
problem.new <- "insufficient coverage"
patristic_matrix_array.new <- NA
return(list(patristic_matrix_array = patristic_matrix_array.new, problem = problem.new))
}
}
if (final.size >= 3) {
patristic_matrix_array.new <- phylo_congruify(reference_tree, target_tree = phy, dating_method = dating_method)
}
return(list(patristic_matrix_array = patristic_matrix_array.new, problem = problem.new))
}
phylo_prune_missing_taxa <- function(phy, taxa) {
return(ape::drop.tip(phy, tip = phy$tip.label[-(which(phy$tip.label %in% taxa))]))
}
phylo_congruify <- function(reference_tree,
target_tree,
dating_method = "PATHd8",
attempt_fix = TRUE) {
result_matrix <- matrix(nrow = ape::Ntip(reference_tree), ncol = ape::Ntip(reference_tree))
if (is.null(target_tree$edge.length)) {
target_tree$edge.length <- numeric(nrow(target_tree$edge))
}
try(result_matrix <- phylo_to_patristic_matrix(congruify_and_check(reference = reference_tree, target = target_tree, scale = dating_method, attempt_fix = attempt_fix)))
return(result_matrix)
}
congruify_and_check <- function(reference, target, taxonomy = NULL, tol = 0.01,
option = 2, scale = "pathd8", attempt_fix = TRUE) {
if (!ape::is.ultrametric(reference, tol = tol, option = option)) {
return(NA)
}
new.tree <- phylo_tiplabel_underscore_to_space(suppressWarnings(geiger::congruify.phylo(
phylo_tiplabel_space_to_underscore(reference), phylo_tiplabel_space_to_underscore(target),
taxonomy = taxonomy, tol = tol, scale = scale
)$phy))
if (anyNA(new.tree$edge.length) & attempt_fix) {
message("Congruification resulted in NA edge lengths. Resolving polytomies and making up starting branch lengths")
new.tree <- phylo_tiplabel_underscore_to_space(geiger::congruify.phylo(
phylo_tiplabel_space_to_underscore(reference), phylo_tiplabel_space_to_underscore(
ape::compute.brlen(ape::multi2di(target))
), taxonomy, tol, scale,
ncores = 1
)$phy)
if (anyNA(new.tree$edge.length)) {
message("There are still NAs in edge lengths; returning NA")
new.tree <- NA
}
}
new.tree$edge.length[which(new.tree$edge.length < 0)] <- 0
return(new.tree)
}
phylo_tiplabel_space_to_underscore <- function(phy) {
phy$tip.label <- gsub(" ", "_", phy$tip.label)
return(phy)
}
phylo_tiplabel_underscore_to_space <- function(phy) {
phy$tip.label <- gsub("_", " ", phy$tip.label)
return(phy)
}
|
filter.P<-function(data,P.low=0,P.up=90)
{
if(!is.data.frame(data))
stop("Invalid input parameter specification: check data")
if(!is.numeric(c(P.low,P.up)) || (P.low<0 || P.up>90) || P.low>P.up)
stop("Invalid input parameter(s) specification: check value(s) of P.low/P.up")
if(!("P"%in%names(data)))
stop("Error: data does not contain column named P")
data[data$P>=P.low & data$P<=P.up,]
}
|
makeRegrTask = function(id = deparse(substitute(data)), data, target, weights = NULL, blocking = NULL, coordinates = NULL, fixup.data = "warn", check.data = TRUE) {
assertString(id)
assertDataFrame(data)
assertString(target)
assertChoice(fixup.data, choices = c("no", "quiet", "warn"))
assertFlag(check.data)
if (fixup.data != "no") {
if (is.integer(data[[target]])) {
data[[target]] = as.double(data[[target]])
}
}
task = makeSupervisedTask("regr", data, target, weights, blocking, coordinates, fixup.data = fixup.data, check.data = check.data)
if (check.data) {
assertNumeric(data[[target]], any.missing = FALSE, finite = TRUE, .var.name = target)
}
task$task.desc = makeRegrTaskDesc(id, data, target, weights, blocking, coordinates)
addClasses(task, "RegrTask")
}
makeRegrTaskDesc = function(id, data, target, weights, blocking, coordinates) {
addClasses(makeTaskDescInternal("regr", id, data, target, weights, blocking, coordinates), c("RegrTaskDesc", "SupervisedTaskDesc"))
}
|
ff_glimpse <- function(.data, dependent=NULL, explanatory=NULL, digits = 1,
levels_cut = 5){
if(is.null(dependent) && is.null(explanatory)){
df.in = .data
} else {
df.in = .data %>% dplyr::select(dependent, explanatory)
}
df.in %>%
dplyr::select_if(is.numeric) -> df.numeric
if(dim(df.numeric)[2]!=0){
df.numeric %>%
missing_glimpse(digits=digits) -> df.numeric.out1
df.numeric %>%
purrr::map_df(function(x){
mean = mean(x, na.rm = TRUE)
sd = sd(x, na.rm = TRUE)
min = min(x, na.rm = TRUE)
quartile_25 = quantile(x, probs = 0.25, na.rm = TRUE)
median = median(x, na.rm = TRUE)
quartile_75 = quantile(x, probs = 0.75, na.rm = TRUE)
max = max(x, na.rm = TRUE)
df.out = data.frame(mean, sd, min, quartile_25, median, quartile_75, max) %>%
dplyr::mutate_all(round_tidy, digits=digits)
}) -> df.numeric.out2
df.numeric.out = data.frame(df.numeric.out1, df.numeric.out2)
}else{
df.numeric.out = df.numeric
}
df.in %>%
dplyr::select_if(Negate(is.numeric)) -> df.factors
if(dim(df.factors)[2]!=0){
df.factors %>%
missing_glimpse(digits=digits) -> df.factors.out1
fac2char = function(., cut = levels_cut) {
length(levels(.)) > cut
}
df.factors %>%
dplyr::mutate_if(fac2char, as.character) -> df.factors
df.factors %>%
purrr::map_df(function(x){
levels_n = length(levels(as.factor(x)))
levels = ifelse(is.factor(x),
forcats::fct_explicit_na(x) %>%
levels() %>%
paste0("\"", ., "\"", collapse = ", "),
"-")
levels_count = ifelse(is.factor(x),
summary(x) %>%
paste(collapse = ", "),
"-")
levels_percent = ifelse(is.factor(x),
summary(x) %>%
prop.table() %>%
{. * 100} %>%
format(digits = 2) %>%
paste(collapse=", "),
"-")
df.out = tibble::tibble(levels_n, levels, levels_count, levels_percent) %>% data.frame()
}) -> df.factors.out2
df.factors.out = data.frame(df.factors.out1, df.factors.out2)
}else{
df.factors.out = df.factors
}
return(
list(
Continuous = df.numeric.out,
Categorical = df.factors.out)
)
}
finalfit_glimpse <- ff_glimpse
|
capture_first_df <- structure(function
(
...,
nomatch.error=getOption("nc.nomatch.error", TRUE),
engine=getOption("nc.engine", "PCRE")
){
all.arg.list <- list(...)
subject <- all.arg.list[[1]]
if(!is.data.frame(subject)){
stop("subject must be a data.frame with character columns to match")
}
col.pattern.list <- all.arg.list[-1]
if(length(col.pattern.list)==0){
stop(
"no patterns specified in ...; ",
"must specify subjectColName=list(groupName=pattern, etc), etc")
}
valid.name <- names(col.pattern.list) %in% names(subject)
invalid.vec <- names(col.pattern.list)[!valid.name]
if(is.null(names(col.pattern.list)) || length(invalid.vec)){
stop("named args (", paste(invalid.vec, collapse=", "),
") not found in subject column names (", paste(names(subject), collapse=", "),
"); each pattern in ... must be named using a column name of subject")
}
if(names(all.arg.list)[[1]] != ""){
stop("first argument (subject data.frame) should not be named")
}
name.tab <- table(names(col.pattern.list))
if(any(bad <- 1 < name.tab)){
stop(
"each argument / subject column name should be unique, problems: ",
paste(names(name.tab)[bad], collapse=", "))
}
out <- data.table(subject)
name.group.used <- FALSE
for(col.name in names(col.pattern.list)){
subject.vec <- out[[col.name]]
col.arg.list <- c(list(subject.vec), col.pattern.list[[col.name]])
maybe.rep <- c("engine", "nomatch.error")
to.rep <- maybe.rep[!maybe.rep %in% names(col.arg.list)]
col.arg.list[to.rep] <- lapply(to.rep, get, environment())
tryCatch({
m <- do.call(capture_first_vec, col.arg.list)
}, error=function(e){
stop("problem for subject column ", col.name, ": ", e)
})
new.bad <- names(m) %in% names(out)
if(any(new.bad)){
stop(
"capture group names (",
paste(names(m), collapse=", "),
") must not conflict with existing column names (",
paste(names(out), collapse=", "),
")")
}
out <- cbind(out, m, stringsAsFactors=FALSE)
}
out
}, ex=function(){
(sacct.df <- data.frame(
JobID = c(
"13937810_25", "13937810_25.batch",
"13937810_25.extern", "14022192_[1-3]", "14022204_[4]"),
Elapsed = c(
"07:04:42", "07:04:42", "07:04:49",
"00:00:00", "00:00:00"),
stringsAsFactors=FALSE))
int.pattern <- list("[0-9]+", as.integer)
end.pattern <- list(
"-",
task.end=int.pattern)
nc::capture_first_df(sacct.df, JobID=list(
end.pattern, nomatch.error=FALSE))
range.pattern <- list(
"[[]",
task.start=int.pattern,
end.pattern, "?",
"[]]")
nc::capture_first_df(sacct.df, JobID=list(
range.pattern, nomatch.error=FALSE))
task.pattern <- list(
"_",
list(
task.id=int.pattern,
"|",
range.pattern))
nc::capture_first_df(sacct.df, JobID=task.pattern)
type.pattern <- list(
"[.]",
type=".*")
nc::capture_first_df(sacct.df, JobID=list(
type.pattern, nomatch.error=FALSE))
task.type.pattern <- list(
task.pattern,
type.pattern, "?")
nc::capture_first_df(sacct.df, JobID=task.type.pattern)
(task.df <- nc::capture_first_df(
sacct.df,
JobID=list(
job=int.pattern,
task.type.pattern),
Elapsed=list(
hours=int.pattern,
":",
minutes=int.pattern,
":",
seconds=int.pattern)))
str(task.df)
})
|
retrieveText <- function(job.file, api.key) {
jobs <- read.csv(job.file)
untranscribed.inds <- which(jobs$TRANSCRIPT == 'queued' | jobs$TRANSCRIPT == '' | is.na(jobs$TRANSCRIPT) | is.null(jobs$TRANSCRIPT))
for(ind in untranscribed.inds){
ID <- jobs$JOBID[ind]
text <- getRequestResults(ID, api.key = api.key)
jobs$TRANSCRIPT[ind] <- text
}
write.csv(jobs, file = job.file, row.names = FALSE)
return(jobs)
}
|
expected <- eval(parse(text="logical(0)"));
test(id=0, code={
argv <- eval(parse(text="list(integer(0))"));
do.call(`is.na`, argv);
}, o=expected);
|
countpattern2<-function (x)
{
intpatt<-apply(as.matrix(x),1,bin2int)
intpatt<-intpatt+1
pat<-tabulate(intpatt,nbins=2^ncol(as.matrix(x)))
pat
}
|
DSC_Hierarchical <- function(k=NULL, h=NULL, method = "complete",
min_weight=NULL, description=NULL) {
hierarchical <- hierarchical$new(
k=k, h=h, method=method, min_weight=min_weight)
if(is.null(description)) description <- paste("Hierarchical (", method, ")",
sep='')
l <- list(description = description, RObj = hierarchical)
class(l) <- c("DSC_Hierarchical","DSC_Macro","DSC_R","DSC")
l
}
.centroids <- function(centers, weights, assignment){
macroID <- unique(assignment)
macroID <- macroID[!is.na(macroID)]
assignment[is.na(assignment)] <- -1
cs <- t(sapply(macroID, FUN=
function(i) {
take <- assignment==i
colSums(centers[take, ,drop=FALSE] *
matrix(weights[take], nrow=sum(take), ncol=ncol(centers))) /
sum(weights[take])
}))
if(ncol(centers) == 1) cs <- t(cs)
rownames(cs) <- NULL
colnames(cs) <- colnames(centers)
cs <- data.frame(cs)
ws <- sapply(macroID, FUN =
function(i) sum(weights[assignment==i], na.rm=TRUE))
list(centers=cs, weights=ws)
}
hierarchical <- setRefClass("hierarchical",
fields = list(
data = "data.frame",
dataWeights = "numeric",
d = "matrix",
method = "character",
k = "ANY",
h = "ANY",
assignment = "numeric",
details = "ANY",
centers = "data.frame",
weights = "numeric",
min_weight = "numeric"
),
methods = list(
initialize = function(
k=NULL,
h=NULL,
method = "complete",
min_weight = NULL
) {
if(is.null(k) && is.null(h)) stop("Either h or k needs to be specified.")
if(!is.null(k) && !is.null(h)) stop("Only h or k can be specified.")
if(is.null(min_weight)) min_weight <<- 0
else min_weight <<- as.numeric(min_weight)
data <<- data.frame()
dataWeights <<- numeric()
weights <<- numeric()
centers <<- data.frame()
method <<- method
k <<- k
h <<- h
.self
}
),
)
hierarchical$methods(
cluster = function(x, weight = rep(1,nrow(x)), ...) {
if(min_weight>0) {
x <- x[weight>min_weight,]
weight <- weight[weight>min_weight]
}
data <<- x
dataWeights <<- weight
if((!is.null(k) && nrow(data) <=k) || nrow(data)<2) {
centers <<- x
weights <<- weight
}else{
hierarchical <- hclust(d=dist(x), method = method)
details <<- hierarchical
if(is.null(k) || k < length(unlist(hierarchical['height'])))
assignment <<- cutree(hierarchical, k = k, h = h)
else
assignment <<- 1
centroids <- .centroids(x, weight, assignment)
centers <<- centroids$centers
weights <<- centroids$weights
}
},
get_microclusters = function(...) { .nodots(...); data },
get_microweights = function(...) { .nodots(...); dataWeights },
get_macroclusters = function(...) { .nodots(...); centers },
get_macroweights = function(...) { .nodots(...); weights },
microToMacro = function(micro=NULL, ...){
.nodots(...);
if(is.null(micro)) micro <- 1:nrow(data)
structure(assignment[micro], names=micro)
}
)
DSC_registry$set_entry(name = "DSC_Hierarchical",
DSC_Micro = FALSE, DSC_Macro = TRUE,
description = "Hierarchical reclustering")
|
evepan <- function(c = 0, mu = 0, r = 5^0.5, side_censored = "left") {
if (any(r <= 0)) {
stop("Range must be strictly positive")
}
if (any(!(side_censored %in% c("left", "right")))) {
stop("side_censored must either be 'left' or 'right'")
}
setsign <- ifelse(side_censored == "left", 1, -1)
alpha <- setsign * (c - mu)/r
ev <- setsign * r/16 * (1 - alpha)^3 * (3 + alpha) + c
ifelse(abs(alpha) <= 1, ev, ifelse(alpha < -1, mu, c))
}
|
data_rename <- function(data, pattern = NULL, replacement = NULL, safe = TRUE, ...) {
if (is.null(replacement) && is.null(pattern)) {
names(data) <- c(1:ncol(data))
return(data)
} else if (is.null(replacement) && !is.null(pattern)) {
names(data) <- pattern
return(data)
} else if (!is.null(replacement) && is.null(pattern)) {
names(data) <- replacement
return(data)
}
if (length(pattern) != length(replacement)) {
stop("The 'replacement' names must be of the same length than the variable names.")
}
for (i in 1:length(pattern)) {
data <- .data_rename(data, pattern[i], replacement[i], safe)
}
data
}
.data_rename <- function(data, pattern, replacement, safe = TRUE) {
if (isFALSE(safe) & !pattern %in% names(data)) {
stop(paste0("Variable '", pattern, "' is not in your dataframe :/"))
}
names(data) <- replace(names(data), names(data) == pattern, replacement)
data
}
data_rename_rows <- function(data, rows = NULL) {
row.names(data) <- rows
data
}
|
mygllm <- function(y,s,X,maxit=1000, tol=0.00001, E=rep(1,length(s)))
{
out <- .C(".mygllm_sym", as.integer(y), as.integer(s-1),
X=as.double(cbind(X,rep(0,nrow(X)))),
as.integer(maxit), as.double(tol), estimate=as.double(E),
length(s),length(y),ncol(X), PACKAGE="RecordLinkage")
return(out$estimate)
}
|
"mu_cnb" <- function(D, r1, r2, lambda){
if (missing(D) || missing(r1) || missing(r2) || missing(lambda))
stop("Need to specify a full set of arguments: D, r1, r2, lambda.")
if (!is.numeric(D) || length(D)!=1 || !D%%1==0 || D<=0)
stop("D needs to be a positive integer.")
if (!is.numeric(r1) || length(r1)!=1 || r1<=0)
stop("r1 needs to be a positive value.")
if (!is.numeric(r2) || length(r2)!=1 || r2<=0)
stop("r2 needs to be a positive value.")
if (!is.numeric(lambda) || length(lambda)!=1 || lambda<=0)
stop("lambda needs to be a positive value.")
return_value <- 0
if (lambda <= 1) {
lnvalue <- log(Re(hypergeo::hypergeo(-D+1, r1+1, -D-r2+2, lambda))) - log(Re(hypergeo::hypergeo(-D, r1, -D-r2+1, lambda)))
return_value <- D * lambda * r1 / (r2 + D - 1) * exp(lnvalue)
}else{
return_value <- D - mu_cnb(D, r2, r1, 1/lambda)
}
return_value
}
|
stat_wb_column <- function(mapping = NULL,
data = NULL,
geom = "rect",
w.band = NULL,
integral.fun = integrate_xy,
chroma.type = "CMF",
position = "identity",
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
...) {
ggplot2::layer(
stat = StatWbColumn, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(w.band = w.band,
integral.fun = integral.fun,
chroma.type = chroma.type,
na.rm = na.rm,
...)
)
}
wb_col_compute_group <-
function(data,
scales,
w.band,
integral.fun,
chroma.type){
if (length(w.band) == 0) {
w.band <- waveband(data[["x"]])
}
if (is.any_spct(w.band) ||
(is.numeric(w.band) && length(stats::na.omit(w.band)) >= 2)) {
w.band <- waveband(range(w.band, na.rm = TRUE))
}
if (!is.list(w.band) || is.waveband(w.band)) {
w.band <- list(w.band)
}
stopifnot(is.function(integral.fun))
w.band <- trim_wl(w.band, data[["x"]])
integ.df <- data.frame()
for (wb in w.band) {
if (is.numeric(wb)) {
wb <- waveband(wb)
}
range <- range(wb)
mydata <- trim_tails(data[["x"]], data[["y"]], use.hinges = TRUE,
low.limit = range[1],
high.limit = range[2])
yint.tmp <- integral.fun(mydata[["x"]], mydata[["y"]])
ymean.tmp <- yint.tmp / wl_expanse(wb)
wb.color <- photobiology::fast_color_of_wb(wb, chroma.type = chroma.type)
integ.df <- rbind(integ.df,
data.frame(x = midpoint(mydata[["x"]]),
wb.xmin = min(wb),
wb.xmax = max(wb),
y = ymean.tmp,
yzero = 0,
wb.ymin = min(data[["y"]]),
wb.ymax = max(data[["y"]]),
wb.ymean = ymean.tmp,
wb.color = wb.color,
wb.name = labels(wb)[["label"]],
BW.color = black_or_white(wb.color))
)
}
integ.df
}
StatWbColumn <-
ggplot2::ggproto("StatWbColumn", ggplot2::Stat,
compute_group = wb_col_compute_group,
default_aes = ggplot2::aes(xmin = ..wb.xmin..,
xmax = ..wb.xmax..,
ymax = ..wb.ymean..,
ymin = ..yzero..,
fill = ..wb.color..),
required_aes = c("x", "y")
)
|
plot.phenopix <- function(x, y=NULL, what='all',main=NULL, ...) {
attr.retr <- attributes(x)
title <- paste0('fit: ', toupper(attr.retr$fit), ' - thresholds: ', toupper(attr.retr$threshold))
plot(x$data,...)
if (is.null(main)) title(main=title) else title(main=main)
if (what=='all') {
if (is.null(x$metrics)) PhenoPlot(x$fit, metrics=NA, add=TRUE) else {
PhenoPlot(x$fit, x$metrics, add=TRUE)
}
} else {
if (what=='fitting') PhenoPlot(x$fit, metrics=NA, add=TRUE)
if (what=='params') {
if (is.null(x$uncertainty.df)) stop('Uncertainty was not estimated. Try what=all')
parameters <- as.data.frame(t(extract(x, what='curve.params.uncert')))
true.params <- extract(x, what='curve.params')
par(mfrow=c(1, length(parameters)), mar=c(5,0,4,0), oma=c(0,4,0,2))
for (a in 1:length(parameters)) {
boxplot(parameters[,a], main=names(parameters)[a],...)
abline(h=true.params[a], lwd=2, col='red')
}
}
if (what=='thresholds') {
parameters <- extract(x, what='metrics.uncert')
par(mfrow=c(1, length(parameters)), mar=c(5,0,4,0), oma=c(0,4,0,2))
for (a in 1:length(parameters)) {
boxplot(parameters[,a], main=names(parameters)[a], ...)
}
}
}
}
|
"NYCdata"
|
knitr::include_graphics("figures/basicPage.png")
|
add_polygon_layer <- function(deckgl, id = "polygon-layer", data = NULL, properties = list(), ...) {
add_layer(deckgl, "PolygonLayer", id, data, properties, ...)
}
|
kids.g <-
function(n.kids, p.gene){
ptmp <- sum((p.gene-c(1,0))*c(3,1))
return(sample(1:3, n.kids, replace=TRUE, prob=Pgene(1:3, ptmp)))
}
|
do.rbind <- function (x, idcol = "Name", keep.rownames = FALSE) {
.Deprecated("data.table::rbindlist")
u <- sapply(x, inherits, "data.frame")
if (any(!u))
warning("Dropping non data.frame elements from 'x'.")
x <- x[u]
if (!length(x)>0)
stop("No data.frame objects in 'x'.")
n <- names(x)
if (is.null(n))
n <- seq_along(x)
r <- sapply(x, nrow)
i <- rep(n, r)
x <- do.call(rbind, x)
x <- data.frame(IDS = i, x, stringsAsFactors = FALSE)
names(x)[1] <- idcol
if (!keep.rownames) rownames(x) <- NULL
return(x)
}
|
dot(y, v1) / vlength(v1)^2
lm(strength ~ limestone, data = Concretemod) %>% coef()
dot(y, v2) / vlength(v2)^2
lm(strength ~ water, data = Concretemod) %>% coef()
dot(y, w1) / vlength(w1)^2
dot(y, w2) / vlength(w2)^2
coef(concrete.lmmod)
|
survmean <- function(formula, data, adjust = NULL, weights = NULL,
breaks=NULL, pophaz = NULL,
e1.breaks = NULL, e1.pophaz = pophaz, r = "auto",
surv.method = "hazard", subset = NULL, verbose = FALSE) {
pt <- proc.time()
TF__ <- environment()
PF__ <- parent.frame(1L)
attr_form <- copy(formula)
surv.method <- match.arg(surv.method, c("hazard", "lifetable"))
r.e2 <- last.p.e2 <- surv <- survmean_type <- est <- Tstart <- Tstop <-
lex.id <- surv.int <- delta <- surv.exp <- obs <- NULL
checkLexisData(data, check.breaks = FALSE)
checkPophaz(data, pophaz, haz.name = "haz")
checkPophaz(data, e1.pophaz, haz.name = "haz")
pophaz <- setDT(copy(pophaz))
e1.pophaz <- setDT(copy(e1.pophaz))
if (is.numeric(r) && r < 0L) stop("numeric r must be > 0, e.g. r = 0.95")
if (is.character(r)) {
if (substr(r, 1, 4) != "auto") {
stop("character string r must start with 'auto'; e.g. `auto` and ",
"`auto5` are accepted.")
}
if (r == "auto") r <- "auto1"
auto_ints <- regmatches(r, regexec("\\d+", text = r))
auto_ints <- as.integer(auto_ints)
r <- "auto"
}
tscales_all <- attr(data, "time.scales")
breaks_old <- attr(data, "breaks")
if (!is.null(breaks_old)) checkBreaksList(data, breaks_old)
if (is.null(breaks)) breaks <- breaks_old
checkBreaksList(data, breaks)
if (!is.null(e1.breaks)) checkBreaksList(data, e1.breaks)
subset <- substitute(subset)
subset <- evalLogicalSubset(data, subset)
x <- setDT(data[subset, ])
forceLexisDT(x, breaks = breaks_old, allScales = tscales_all)
avoid <- unique(c(names(data), names(x), names(pophaz), names(e1.pophaz)))
pophaz_vars <- c(names(pophaz), names(e1.pophaz))
pophaz_vars <- setdiff(pophaz_vars, c(tscales_all, "haz"))
pophaz_vars <- intersect(pophaz_vars, names(x))
pophaz_vars_tmp <- makeTempVarName(names = avoid, pre = pophaz_vars)
if (!length(pophaz_vars)) {
pophaz_vars_tmp <- NULL
} else {
pophaz_vars_wh <- which(pophaz_vars %in% names(pophaz))
if (sum(pophaz_vars_wh)) {
setnames(pophaz, old = pophaz_vars[pophaz_vars_wh],
new = pophaz_vars_tmp[pophaz_vars_wh])
}
pophaz_vars_wh <- which(pophaz_vars %in% names(e1.pophaz))
if (sum(pophaz_vars_wh)) {
setnames(e1.pophaz, old = pophaz_vars[pophaz_vars_wh],
new = pophaz_vars_tmp[pophaz_vars_wh])
}
x[, (pophaz_vars_tmp) := copy(.SD), .SDcols = pophaz_vars]
}
adSub <- substitute(adjust)
foList <- usePopFormula(formula, adjust = adSub, data = x, enclos = PF__,
Surv.response = "either")
adjust_vars <- names(foList$adjust)
print_vars <- names(foList$print)
by_vars <- c(print_vars, adjust_vars)
avoid <- unique(c(names(data), names(x), names(pophaz), names(e1.pophaz)))
adjust_vars_tmp <- makeTempVarName(names = avoid, pre = adjust_vars)
if (!length(adjust_vars)) adjust_vars_tmp <- NULL
avoid <- unique(c(names(data), names(x), names(pophaz), names(e1.pophaz)))
print_vars_tmp <- makeTempVarName(names = avoid, pre = print_vars)
if (!length(print_vars)) print_vars_tmp <- NULL
by_vars_tmp <- c(print_vars_tmp, adjust_vars_tmp)
lex_vars <- c("lex.id", tscales_all, "lex.dur", "lex.Cst", "lex.Xst")
setcolsnull(x, keep = c(lex_vars, pophaz_vars_tmp), soft = FALSE)
if (length(adjust_vars) > 0L) x[, (adjust_vars_tmp) := foList$adjust]
if (length(print_vars) > 0L) x[, (print_vars_tmp) := foList$print]
formula <- paste0(deparse(formula[[2L]]), " ~ ")
if (length(c(adjust_vars_tmp, print_vars_tmp)) > 0L) {
formula <- paste0(formula, paste0(c(print_vars_tmp, adjust_vars_tmp),
collapse = " + "))
} else {
formula <- paste0(formula, "1")
}
formula <- as.formula(formula)
tscale_surv <- detectSurvivalTimeScale(lex = x, values = foList$y$time)
test_obs <- x[, .(obs=.N), keyby=eval(TF__$by_vars_tmp)]
if (length(by_vars)) setnames(test_obs, by_vars_tmp, by_vars)
if (length(weights) && !length(adjust_vars)) {
weights <- NULL
warning("Replaced weights with NULL due to not supplying variables to ",
"adjust by.")
}
mwDTtest <- makeWeightsDT(test_obs, values = list("obs"), print = print_vars,
adjust = adjust_vars, weights = weights,
internal.weights.values = "obs")
if (length(by_vars)) setnames(test_obs, by_vars, by_vars_tmp)
if (is.null(e1.breaks)) {
e1.breaks <- copy(breaks[tscale_surv])
addBreaks <- max(e1.breaks[[tscale_surv]]) +
c(seq(0,1,1/12), seq(1.2, 1.8, 0.2), 2:19, seq(20, 50, 5))
e1.breaks[[tscale_surv]] <- unique(c(e1.breaks[[tscale_surv]], addBreaks))
checkBreaksList(x, e1.breaks)
}
if (!tscale_surv %in% names(e1.breaks)) {
stop("The survival time scale must be included in the list of breaks ",
"to extrapolate by ('e1.breaks').")
}
if (!all(breaks[[tscale_surv]] %in% e1.breaks[[tscale_surv]])) {
stop("The vector of breaks in 'breaks' for the survival time scale MUST",
"be a subset of the breaks for the survival time scale in ",
"'e1.breaks'. E.g. the former could be 0:10 and the latter 0:100.")
}
if (verbose) {
cat("Time taken by prepping data:", timetaken(pt), "\n")
}
st <- survtab(formula, data = x, breaks = breaks,
pophaz = pophaz,
relsurv.method = "e2",
surv.type = "surv.rel",
surv.method = surv.method)
st_keep_vars <- c(by_vars_tmp, "Tstop", "r.e2", "surv.obs")
all_names_present(
st, st_keep_vars,
msg = paste0("Internal error: expected to have variables ",
"%%VARS%% after computing observed survivals ",
"but didn't. Blame the package maintainer if you ",
"see this.")
)
setcolsnull(st, keep = st_keep_vars, colorder = TRUE)
setDT(st)
setkeyv(st, c(by_vars_tmp, "Tstop"))
st[, "Tstart" := c(0, Tstop[-.N]), by = eval(by_vars_tmp)]
st[, c("r.e2", "surv.obs") := lapply(.SD, function(col) col/c(1, col[-.N])),
by = eval(by_vars_tmp),
.SDcols = c("r.e2", "surv.obs")
]
if (verbose) {
cat("Time taken by estimating relative survival curves:",
timetaken(pt), "\n")
}
pt <- proc.time()
setkeyv(x, c("lex.id", tscale_surv))
tol <- .Machine$double.eps^0.5
xe <- unique(x, by = key(x))[x[[tscale_surv]] < TF__$tol, ]
if (length(breaks) > 1L) {
breaks_drop_tmp <- setdiff(names(breaks), tscale_surv)
breaks_drop_tmp <- breaks[breaks_drop_tmp]
breaks_drop_tmp <- lapply(breaks_drop_tmp, range)
expr <- mapply(function(ch, ra) {
paste0("between(", ch, ", ", ra[1], ", ", ra[2] - tol, ", incbounds = TRUE)")
}, ch = names(breaks_drop_tmp), ra = breaks_drop_tmp, SIMPLIFY = FALSE)
expr <- lapply(expr, function(e) eval(parse(text = e), envir = xe))
setDT(expr)
expr <- expr[, rowSums(.SD)] == ncol(expr)
xe <- xe[expr, ]
}
xe <- x[lex.id %in% unique(xe[["lex.id"]])]
forceLexisDT(xe, breaks = breaks_old, allScales = tscales_all, key = FALSE)
e1 <- comp_e1(xe, breaks = e1.breaks, pophaz = e1.pophaz, immortal = TRUE,
survScale = tscale_surv, by = by_vars_tmp, id = "lex.id")
setnames(e1, tscale_surv, "Tstop")
e1[, "Tstart" := c(0, Tstop[-.N]), by = eval(by_vars_tmp)]
e1[, "surv.int" := cut(Tstart, breaks = e1.breaks[[tscale_surv]],
right = FALSE, labels = FALSE)]
e1[, "delta" := Tstop - Tstart]
e1[, "surv.exp" := surv.exp/c(1, surv.exp[-.N]), by = eval(by_vars_tmp)]
if (verbose) {
cat("Time taken by computing overall expected survival curves:",
timetaken(pt), "\n")
}
N_subjects <- xe[!duplicated(lex.id)][,
list(obs=.N),
keyby=eval(by_vars_tmp)
]
pt <- proc.time()
st[, "surv.int" := cut(Tstart, breaks = e1.breaks[[tscale_surv]],
right = FALSE, labels = FALSE)]
x <- merge(e1, st[, .SD, .SDcols = c(by_vars_tmp, "surv.int", "r.e2", "surv.obs")],
by = c(by_vars_tmp,"surv.int"), all = TRUE)
setkeyv(x, c(by_vars_tmp, "surv.int"))
if (is.numeric(r)) {
set(x, j = "last.p.e2", value = r^x[["delta"]])
} else {
st <- st[, .SD[(.N-TF__$auto_ints+1):.N], by = eval(by_vars_tmp)]
st[, "delta" := Tstop - Tstart]
st[, "r.e2" := r.e2^(1/delta)]
st <- st[, .(last.p.e2 = mean(r.e2)), by = eval(by_vars_tmp)]
st[, "last.p.e2" := pmin(1, last.p.e2)]
if (verbose) {
cat("Using following table of mean RSR estimates",
"(scaled to RSRs applicable to a time interval one",
"unit of time wide, e.g. one year or one day)",
"based on", auto_ints, "interval(s) from the end of the relative",
"survival curve by strata: \n")
prST <- data.table(st)
setnames(prST, c(by_vars_tmp, "last.p.e2"), c(by_vars, "RSR"))
print(prST)
}
if (length(by_vars_tmp)) {
x <- merge(x, st, by = by_vars_tmp, all = TRUE)
} else {
set(x, j = "last.p.e2", value = st$last.p.e2)
}
x[, "last.p.e2" := last.p.e2^(delta)]
x[, "last.p.e2" := pmin(last.p.e2, 1)]
}
x[is.na(r.e2), "r.e2" := last.p.e2]
x[, "surv" := r.e2*surv.exp]
setkeyv(x, c(by_vars_tmp, "surv.int"))
x[, c("surv", "surv.exp") := lapply(.SD, cumprod),
.SDcols = c("surv", "surv.exp"), by = eval(by_vars_tmp)]
x2 <- copy(x)
x[, "surv.exp" := NULL]
x2[, "surv" := NULL]
setnames(x2, "surv.exp", "surv")
x <- rbind(x, x2)
x[, "survmean_type" := rep(c("est", "exp"), each = nrow(x2))]
setcolsnull(
x,
keep = c(by_vars_tmp, "survmean_type",
"surv.int", "Tstart", "Tstop",
"delta", "surv", "surv.exp"),
colorder = TRUE
)
mi <- x[, .(surv = round(min(surv),4)*100),
keyby = eval(c(by_vars_tmp, "survmean_type"))]
if (any(mi$surv > 1)) {
warning("One or several of the curves used to compute mean survival times ",
"or expected mean survival times was > 1 % at the lowest point. ",
"Mean survival estimates may be significantly biased. To avoid ",
"this, supply breaks to 'e1.breaks' which make the curves longer ",
", e.g. e1.breaks = list(FUT = 0:150) where time scale FUT ",
"is the survival time scale (yours may have a different name).")
}
mi[, "surv" := paste0(formatC(surv, digits = 2, format = "f"), " %")]
mi[, "survmean_type" := factor(survmean_type, c("est", "exp"),
c("Observed", "Expected"))]
setnames(mi, c("survmean_type", "surv"),
c("Obs./Exp. curve", "Lowest value"))
if (length(by_vars)) setnames(mi, by_vars_tmp, by_vars)
if (verbose) {
cat("Lowest points in observed / expected survival curves by strata:\n")
print(mi)
}
setkeyv(x, c(by_vars_tmp, "survmean_type", "Tstop"))
sm <- x[, .(survmean = sum(delta*(surv + c(1, surv[-.N]))/2L)),
keyby = c(by_vars_tmp, "survmean_type")]
sm <- cast_simple(sm, columns = "survmean_type",
rows = by_vars_tmp, values = "survmean")
setkeyv(sm, by_vars_tmp); setkeyv(N_subjects, by_vars_tmp)
sm[, "obs" := N_subjects$obs]
sm[, "YPLL" := (exp-est)*obs]
sm <- makeWeightsDT(sm, values = list(c("est", "exp", "obs", "YPLL")),
print = print_vars_tmp, adjust = adjust_vars_tmp,
weights = weights, internal.weights.values = "obs")
if (length(adjust_vars)) {
vv <- c("est", "exp", "obs", "YPLL")
sm[, c("est", "exp") := lapply(.SD, function(col) col*sm$weights),
.SDcols = c("est", "exp")]
sm <- sm[, lapply(.SD, sum), .SDcols = vv, by = eval(print_vars_tmp)]
}
if (verbose) {
cat("Time taken by final touches:", timetaken(pt), "\n")
}
if (length(print_vars)) setnames(sm, print_vars_tmp, print_vars)
at <- list(call = match.call(),
formula = attr_form,
print = print_vars,
adjust = adjust_vars,
tprint = print_vars_tmp,
tadjust = adjust_vars_tmp,
breaks = breaks,
e1.breaks = e1.breaks,
survScale = tscale_surv,
curves = copy(x))
setattr(sm, "class", c("survmean","data.table", "data.frame"))
setattr(sm, "survmean.meta", at)
if (!return_DT()) setDFpe(sm)
return(sm[])
}
|
varPercent <- function(level, plotObj){
if (level == 12){
eigenvalues = c(plotObj$evalues$level1, plotObj$evalues$level2)
}else{eigenvalues = plotObj$evalues[[level]]}
percent <- lapply(eigenvalues, function(i){100*round(i/sum(eigenvalues), 3)})
return(percent)
}
|
library(spData)
library(sf)
world_df = sf::st_coordinates(world)
head(world_df)
summary(world_df)
world_df_sfh = sfheaders::sf_to_df(world)
head(world_df_sfh)
world_sfh = sfheaders::sf_multipolygon(world_df_sfh)
world_sfh = sfheaders::sf_multipolygon(world_df_sfh, x = "x", y = "y", polygon_id = "", multipolygon_id = "multipolygon_id")
length(world$geom)
length(world_sfh$geometry)
waldo::compare(world$geom[1], world_sfh$geometry[1])
world$geom[1][[1]][[2]]
world_sfh$geom[1][[1]][[2]]
plot(world$geom[1])
plot(world_sfh$geometry[1])
bench::mark(
check = FALSE,
sf = sf::st_coordinates(world),
sfheaders = sfheaders::sf_to_df(world)
)
library(sf)
nc = sf::st_read(system.file("./shape/nc.shp", package = "sf"))
sfheaders::sf_cast(nc, "LINESTRING")
bench::mark(check = FALSE,
sf = {
sf::st_cast(nc, "POINT")
},
sfheaders = {
sfheaders::sf_cast(nc, "POINT")
}
)
|
plot.idaLm <- function(x, names = TRUE, max_forw = 50, max_plot = 15, order = NULL,
lmgON = FALSE, backwardON = FALSE, ...){
if (!requireNamespace("ggplot2", quietly = TRUE)) {
stop("ggplot2 is required to plot idaLm objects.")
}
idaLm <- x
if(!("idaLm" %in% class(idaLm))){
stop("Input is not an idaLm object.")
}
if(is.null(idaLm$CovMat)){
stop("Function needs an idaLm object with a Covariance Matrix")
}
if(is.numeric(max_forw)){
if(!(max_forw%%1 == 0 && max_forw > 1)){
stop("max_forw must be an integer bigger than 1.")
}
}else{
stop("max_forw must be numeric.")
}
if(is.numeric(max_plot)){
if(!(max_plot%%1 == 0 && max_plot > 0)){
stop("max_plot must be an integer bigger than 0.")
}
}else{
stop("max_plot must be numeric.")
}
if(!is.logical(names)){
stop("The parameter \"names\" must be logical.")
}
if(!is.logical(lmgON)){
stop("The parameter \"lmgON\" must be logical.")
}
if(!is.logical(backwardON)){
stop("The parameter \"backwardON\" must be logical.")
}
mat <- idaLm$CovMat
nrowMat <- nrow(mat)
if(rownames(mat)[nrowMat] != "Intercept"){
stop("Plotting a model without intercept is currently not supported.")
}else{
n = mat[nrowMat, nrowMat]
}
card <- idaLm$card
colNames <- names(card)
if(is.vector(order)){
check <- order %in% colNames
if(all(check)){
lastcol <- cumsum(card)[!(colNames %in% order)] + 1
delcard <- card[!(colNames %in% order)]
deletecols <- unlist(mapply(FUN = function(x, y){do.call(":",list(x-y+1,x))}, lastcol, delcard))
card <- card[colNames %in% order]
mat <- mat[-deletecols, -deletecols]
colNames <- names(card)
}else{
error <- "Some of the Attributes of the vector are not in the model:"
error <- paste(error, paste(order[!check], collapse = ","))
stop(error)
}
}
YTY = mat[1, 1]
XTX = mat[-1, -1]
XTY = mat[1, -1]
nomCols <- names(card)[card > 1]
getRelImp <- function(colNames, card, nomCols, numrow, XTX, XTY, YTY, order, lmgON,
backwardON){
nrowXTX <- nrow(XTX)
mean_y <- XTY[nrowXTX] / numrow
Var_y <- YTY - mean_y * mean_y * numrow
SXY <- matrix(nrow = 1, ncol = nrowXTX)
SXY[1, ] <- XTY - XTX[nrowXTX, ] * mean_y
SXY[1, nrowXTX] <- 0
SXY <- SXY / Var_y
calc <- function(SXY, XTX, XTY){
coeff <- NULL
try({coeff = solve(XTX, XTY)}, silent=T)
if(is.null(coeff)) {
coeff <- ginv(XTX, tol = 1e-16) %*% XTY
}
SXY %*% coeff
}
totalR2 <- calc(SXY, XTX, XTY)
if(length(colNames) < 2){
if(is.vector(order)){
res <- data.frame(totalR2)
names(res) <- c('Model_Values')
rownames(res) <- order
}else{
if(backwardON){
res <- data.frame(0)
names(res) <- c('Backward_Values')
rownames(res) <- colNames
}else{
res <- data.frame(totalR2)
names(res) <- c('Forward_Values')
rownames(res) <- colNames
}
}
if(lmgON){
res2 <- data.frame(res, totalR2, totalR2, totalR2)
names(res2) <- c(names(res), 'Usefulness', 'First', 'LMG')
}else{
res2 <- data.frame(res, totalR2, totalR2)
names(res2) <- c(names(res), 'Usefulness', 'First')
}
res2
}else{
posofAttr <- list()
R2 <- c()
First <- c()
disposition <- 0
for(i in 1:length(colNames)){
length <- card[colNames[i]]-1
tempPos <- (i+disposition) : (i+disposition+length)
posofAttr[[colNames[i]]] <- tempPos
lastXTX <- XTX[-tempPos, -tempPos]
lastXTY <- XTY[-tempPos]
lastSXY <- SXY[1, -tempPos]
R2 <- c(R2, calc(lastSXY, lastXTX, lastXTY))
firstXTX <- XTX[c(tempPos, nrowXTX), c(tempPos, nrowXTX)]
firstXTY <- XTY[c(tempPos, nrowXTX)]
firstSXY <- SXY[1, c(tempPos, nrowXTX)]
First <- c(First, calc(firstSXY, firstXTX, firstXTY))
disposition <- disposition + length
}
names(First) <- colNames
Usefulness <- totalR2-R2
names(R2) <- colNames
stepbystep <- function(StartingVal, posofAttr, SXY, XTX, XTY, max_forw,
direction = "forward"){
tempcolNames <- names(StartingVal)
bestpos <- match(max(StartingVal), StartingVal)[1]
swap <- tempcolNames[1]
tempcolNames[1] <- names(StartingVal)[bestpos]
tempcolNames[bestpos] <- swap
indices <- posofAttr[[tempcolNames[1]]]
if(direction == "forward"){
indices <- c(indices,nrowXTX)
}
modelval <- StartingVal[bestpos]
max_forw <- min(length(tempcolNames), max_forw)
for(i in 2:max_forw){
tempvalues <- c()
for(j in i:length(tempcolNames)){
tempindices <- indices
tempindices <- c(tempindices,posofAttr[[tempcolNames[j]]])
if(direction == "forward"){
tempXTX <- XTX[tempindices, tempindices]
tempSXY <- SXY[tempindices]
tempXTY <- XTY[tempindices]
}else{
tempXTX <- XTX[-tempindices, -tempindices]
tempSXY <- SXY[-tempindices]
tempXTY <- XTY[-tempindices]
}
tempvalues <- c(tempvalues, calc(tempSXY, tempXTX, tempXTY))
}
names(tempvalues) <- tempcolNames[i:length(tempcolNames)]
modelval[i] <- max(tempvalues)
bestpos <- match(modelval[i], tempvalues)[1]
swap <- tempcolNames[i]
tempcolNames[i] <- tempcolNames[i+bestpos-1]
tempcolNames[i+bestpos-1] <- swap
indices <- c(indices, posofAttr[[tempcolNames[i]]])
}
data.frame(tempcolNames[1:max_forw], modelval)
}
lmg <- function(posofAttr, First, SXY, XTX, XTY){
colNames <- names(First)
calc.index <- function(indices,SXY,XTX,XTY){
indices <- c(indices, nrow(XTX))
tempXTX <- XTX[indices, indices]
tempSXY <- SXY[indices]
tempXTY <- XTY[indices]
calc(tempSXY, tempXTX, tempXTY)
}
NrAttr <- length(colNames)
lmgRes <- factorial(NrAttr-1)*First
dataold <- t(matrix(1:NrAttr))
valold <- First
for(cardsubset in 2:NrAttr){
nrofSets <- choose(NrAttr, cardsubset)
valnew <- vector(mode = "integer", length = nrofSets)
datanew <- matrix(, ncol = nrofSets, nrow = cardsubset)
count <- 0
for(NrPred in 1:NrAttr){
for(NrSubset in 1:ncol(dataold)){
tmpSet <- dataold[, NrSubset]
if(!(NrPred %in% tmpSet)){
newSet <- c(tmpSet, NrPred)
temp <- calc.index(unlist(posofAttr[newSet]), SXY, XTX, XTY)
if(NrPred > max(tmpSet)){
count <- count + 1
datanew[, count] <- newSet
valnew[count] <- temp
}
lmgRes[NrPred] = lmgRes[NrPred] + factorial(cardsubset-1) * factorial(NrAttr-cardsubset)*(temp-valold[NrSubset])
}
}
}
dataold <- datanew
valold <- valnew
}
lmgRes <- lmgRes/(factorial(NrAttr))
lmgRes <- data.frame(lmgRes)
lmgRes
}
orderfct <- function(order,posofAttr,XTX,XTY,SXY,nrowXTX,First){
orderval <- First[order[1]]
indices <- c(posofAttr[[order[1]]], nrowXTX)
if(length(order) > 1){
for(i in 2:length(order)){
indices <- c(indices, posofAttr[[order[i]]])
tempXTX <- XTX[indices, indices]
tempSXY <- SXY[indices]
tempXTY <- XTY[indices]
orderval <- c(orderval, calc(tempSXY, tempXTX, tempXTY))
}
}
names(orderval) <- NULL
res <- data.frame(orderval)
res
}
if(is.vector(order)){
res <- as.data.frame(orderfct(order, posofAttr, XTX, XTY, SXY, nrowXTX, First))
names(res) <- c('Model_Values')
rownames(res) <- order
}else{
if(backwardON){
backward <- stepbystep(R2, posofAttr, SXY, XTX, XTY, max_forw = max_forw, direction = "backward")
res <- data.frame(backward[, 2])
names(res) <- c('Backward_Values')
rownames(res) <- backward[, 1]
}else{
forward <- stepbystep(First, posofAttr, SXY, XTX, XTY, max_forw = max_forw)
res <- data.frame(forward[, 2])
names(res) <- c('Forward_Values')
rownames(res) <- forward[, 1]
}
}
if(lmgON){
lmgval <- lmg(posofAttr, First, SXY, XTX, XTY)
}
neworder <- match(rownames(res), names(First))
First <- First[neworder]
Usefulness <- Usefulness[neworder]
if(lmgON){
lmgval <- lmgval[neworder,]
res2 <- data.frame(res, Usefulness, First, lmgval)
names(res2) <- c(names(res), 'Usefulness', 'First', 'LMG')
}else{
res2 <- data.frame(res, Usefulness, First)
names(res2) <- c(names(res), 'Usefulness', 'First')
}
res2
}
}
if(lmgON){
if(length(colNames) > 15){
stop("The method recommends to not use LMG for more than 15 Attributes due to runtime.")
}
}
tryCatch({
relImp=getRelImp(colNames, card, nomCols, n, XTX, XTY, YTY, order, lmgON, backwardON)
}, error = function(e){stop(e)})
plot3 <- function(relImp, max_plot, names){
reshaped <- relImp
ModelVal <- colnames(reshaped)[1]
reshaped$Attributes <- rownames(relImp)
max_plot <- min(nrow(reshaped), max_plot)
reshaped <- reshaped[1:max_plot, ]
reshaped <- reshaped[, c('Attributes', 'Usefulness', 'First', ModelVal)]
if(!names){
reshaped$Attributes <- as.character(1:nrow(reshaped))
reshaped$Attributes <- factor(reshaped$Attributes, levels = reshaped$Attributes)
}else{
reshaped$Attributes <- factor(reshaped$Attributes, levels = reshaped$Attributes)
reshaped <- reshaped[1:nrow(reshaped), ]
}
reshaped <- reshape(reshaped, varying=c( ModelVal, 'First', 'Usefulness'),
v.names = c('Explanation'), direction="long")
reshaped$time[reshaped$time == 1] <- 'Model_Value'
reshaped$time[reshaped$time == 2] <- 'First'
reshaped$time[reshaped$time == 3] <- 'Usefulness'
reshaped$time <- factor(reshaped$time)
png(filename = "RelImpPlot.png")
plot1 <- ggplot(reshaped, aes_string(x = 'Attributes', y = 'Explanation', fill = "time",
width=0.4)) +
scale_x_discrete(expand=c(0.1,0))+
scale_fill_manual(values=c("
breaks=c("Model_Value","First", "Usefulness"),
c('Model_Value', 'First', 'Usefulness'))+
geom_bar(stat = "identity", position = "identity")+
guides(fill = guide_legend(reverse = FALSE, title = NULL))
if(names == TRUE){
plot1 <- plot1 + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
}
print(plot1)
dev.off()
print(plot1)
if(!names){
name_df <- as.data.frame(rownames(relImp[1:max_plot, ]))
names(name_df) <- c('Attributes')
cat("The order of the attributes in the plot is:\n")
print(name_df)
}
}
plotlmg <- function(relImp, max_plot, names){
max_plot <- min(max_plot, nrow(relImp))
data <- relImp
data$Attributes <- rownames(relImp)
data$Explanation <- relImp$LMG
data <- data[1:max_plot, ]
if(!names){
data$Attributes <- as.character(1:nrow(data))
data$Attributes <- factor(data$Attributes, data$Attributes)
}else{
data$Attributes <- factor(data$Attributes, data$Attributes)
data <- data[1:nrow(data), ]
}
png(filename="RelImpPlot.png")
plot1 <- ggplot(data, aes_string(x = 'Attributes', y = 'Explanation')) +
geom_bar(stat = "identity", fill="
scale_x_discrete(expand=c(0.1,0))
if(names == TRUE){
plot1 <- plot1 + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
}
print(plot1)
dev.off()
print(plot1)
if(!names){
name_df <- as.data.frame(rownames(relImp[1:max_plot, ]))
names(name_df) <- c('Attribute')
cat("Die Attribute im Plot haben die folgende Reihenfolge:\n")
print(name_df)
}
}
relImp[relImp > 1] <- 1
relImp[relImp < 0] <- 0
if(lmgON){
plotlmg(relImp, max_plot, names)
}else{
plot3(relImp, max_plot, names)
}
relImp
}
|
CDP <- function(Q, par, alpha, model=c("DINA", "DINO", "NIDA", "GNIDA", "RRUM")){
natt <- length(Q)
model <- match.arg(model)
if (model %in% c("DINA", "DINO", "NIDA", "GNIDA")){
par$slip[par$slip == 0] <- 0.001
par$guess[par$guess == 0] <- 0.001
par$slip[par$slip == 1] <- 0.999
par$guess[par$guess == 1] <- 0.999
}
if (model == "RRUM"){
par$pi[par$pi == 0] <- 0.001
par$r[par$r == 0] <- 0.001
par$pi[par$pi == 1] <- 0.999
par$r[par$r == 1] <- 0.999
}
{
if (model == "DINA")
{
ita <- prod(alpha ^ Q)
P <- (1 - par$slip) ^ ita * par$guess ^ (1 - ita)
} else if (model == "DINO")
{
omega <- 1 - prod((1 - alpha) ^ Q)
P <- (1 - par$slip) ^ omega * par$guess ^ (1 - omega)
} else if (model %in% c("NIDA", "GNIDA"))
{
P <- prod(((1 - par$slip) ^ alpha * par$guess ^ (1 - alpha)) ^ Q)
} else if (model == "RRUM")
{
P <- par$pi * prod(par$r ^ (Q * (1 - alpha)))
} else return(warning("Model specification is not valid."))
}
return(P)
}
|
'.gdalwarp' <- function(src,dst=NULL,grid=NULL,resample="near",nodata=NA
,resetGrid=FALSE,opt=NULL,close=FALSE,verbose=0L) {
if (is.null(grid)) {
if (is.ursa(dst,"grid")) {
grid <- dst
dst <- NULL
}
else if (is.ursa(dst)) {
grid <- ursa(dst,"grid")
dst <- NULL
}
else
grid <- getOption("ursaSessionGrid")
}
else
grid <- ursa_grid(grid)
if (!nchar(Sys.which("gdalwarp"))) {
withRaster <- requireNamespace("raster",quietly=.isPackageInUse())
if (withRaster) {
r1 <- as.Raster(src)
session_grid(grid)
r2 <- as.Raster(ursa_new(0L))
r3 <- try(raster::resample(r1,r2,method=c("bilinear","ngb")[1]))
if (inherits(r3,"try-error")) {
if (verbose)
message('reprojection is failed')
return(src)
}
}
else if (verbose)
message(paste("'gdalwarp' is not found; package 'raster' is not found."
,"Reprojection is failed."))
return(src)
}
if (is.ursa(src)) {
removeSrc <- TRUE
.src <- src
nodata <- ignorevalue(src)
src <- .maketmp(ext=".")
write_envi(.src,src)
}
else {
removeSrc <- FALSE
}
inMemory <- is.null(dst)
if (inMemory) {
dst <- .maketmp(ext="")
driver <- "ENVI"
}
else {
driver <- switch(.gsub("^.+(\\.(.+))$","\\2",tolower(basename(dst)))
,tif="GTiff",tiff="GTiff",envi="ENVI",img="HFA",hfa="HFA"
,"ENVI")
}
if (verbose)
print(c(inMemory=inMemory,removeSrc=removeSrc,isNullGrid=is.null(grid)))
proj4 <- ursa_crs(grid)
if (!nchar(proj4)) {
opt <- c(opt,to="SRC_METHOD=NO_GEOTRANSFORM",to="DST_METHOD=NO_GEOTRANSFORM")
}
if (!("co" %in% names(opt))) {
if (driver=="GTiff")
opt <- c(opt,co="COMPRESS=DEFLATE",co="PREDICTOR=2",co="TILED=NO")
else if (driver=="HFA") {
opt <- c(opt,co="COMPRESSED=YES")
}
}
if (is.null(opt)) {
optF <- ""
}
else if (!is.null(names(opt))) {
optS <- unlist(opt)
optF <- paste(paste0("-",names(optS)," ",.dQuote(unname(optS))),collapse=" ")
optF <- gsub("\\s*\"TRUE\"","",optF)
optF <- .gsub("\\s\\\"\\\"","",optF)
}
else
optF <- ""
if (!("r" %in% names(opt))) {
optF <- paste(optF,"-r",resample)
}
if (is.null(grid))
cmd <- paste("gdalwarp -overwrite -of",driver
,ifelse(is.na(nodata),"",paste("-srcnodata",nodata,"-dstnodata",nodata))
,ifelse(verbose==0L,"-q","")
,optF,src,dst)
else
cmd <- with(grid,paste("gdalwarp -overwrite -of",driver
,ifelse(nchar(proj4),paste("-t_srs",.dQuote(proj4)),"")
,"-nosrcalpha"
,"-tr",resx,resy,"-te",minx,miny,maxx,maxy
,ifelse(is.na(nodata),"",paste("-srcnodata",nodata,"-dstnodata",nodata))
,ifelse(verbose==0L,"-q","")
,optF,src,dst))
if (verbose)
message(cmd)
if (verbose>1)
return(NULL)
proj_lib <- Sys.getenv("PROJ_LIB")
Sys.setenv(PROJ_LIB=file.path(dirname(dirname(Sys.which("gdalwarp"))),"share/proj"))
system(cmd)
Sys.setenv(PROJ_LIB=proj_lib)
session_grid(NULL)
if (inMemory) {
ret <- if (driver=="ENVI") read_envi(dst) else read_gdal(dst)
}
else if (!close)
ret <- if (driver=="ENVI") open_envi(dst) else open_gdal(dst)
else
ret <- NULL
if (!is.na(nodata)) {
ignorevalue(ret) <- nodata
if (inMemory)
ret[ret==nodata] <- NA
}
if (inMemory) {
envi_remove(dst)
}
if (removeSrc) {
envi_remove(src)
}
if (resetGrid)
session_grid(ret)
ret
}
|
sel_scale_1d_wgs = function(cnMax=6,pscnMax=6,ngrid = 100,nslaves = 50,temp){
tt = exp(-(0:6-1)^2);prior_f = tt%*%t(tt);lprior_f_2d = -log(prior_f)*1e-3
rtt = exp(-(6:0-1)^2);rprior_f = rtt%*%t(rtt);rlprior_f_2d = -log(rprior_f)*1e-3
baf <- temp$baf
lrr <- temp$lrr
n_baf <- temp$n_baf
nrc <- temp$nrc
scale_max = mean(exp(lrr))*2
scale_min = mean(exp(lrr))/3
sim_func <- function(ss,ngrid=100,pscnMax=6){
scale = scale_min+ss*(scale_max-scale_min)/ngrid
n_seg = length(baf)
L_tot_1d = matrix(0,100,n_seg)
for(i in which(!is.na(baf))){
L_tot_1d[,i]=calcll_1d_baf(lrr[i],nrc[i],baf[i],n_baf[i],lprior_f_2d*0,rlprior_f_2d*0,scale,6,6)[[1]]
}
L_sum_1d = apply(L_tot_1d,1,sum)
out = min(L_sum_1d)
return(out)
}
ll <- lapply(1:100, sim_func)
ll <-unlist(ll)
ind = 3:(ngrid-2)
id = which(ll[ind]<ll[ind+1]&ll[ind]<ll[ind+2]&ll[ind]<ll[ind-1]&ll[ind]<ll[ind-2])+2
if(length(id)>1){id1 = which.min(ll[id]);id2 = which.min(ll[id[-id1]]);id2 = (id[-id1])[id2];id1 = id[id1];id=c(id1,id2)}
scale1d = id*(scale_max-scale_min)/ngrid+scale_min
res = list()
res$ll = ll
res$scale_max = scale_max
res$scale_min = scale_min
res$scale1d = scale1d
return(res)
}
|
manual_scale <- function(aesthetic, values = NULL, breaks = waiver(), ...) {
if (is_missing(values)) {
values <- NULL
} else {
force(values)
}
if (is.vector(values) && is.null(names(values)) && !is.waive(breaks) &&
!is.null(breaks)) {
if (length(breaks) != length(values)) {
abort(glue("
Differing number of values and breaks in manual scale.
{length(values)} values provided compared to {length(breaks)} breaks.
"))
}
names(values) <- breaks
}
pal <- function(n) {
if (n > length(values)) {
abort(glue("Insufficient values in manual scale. {n} needed but only {length(values)} provided."))
}
values
}
discrete_scale(aesthetic, "manual", pal, breaks = breaks, ...)
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(tinyscholar)
profile <- tinyscholar("FvNp0NkAAAAJ")
str(profile, max.level = 1)
tb <- scholar_table(profile)
tb$citations
tb$publications
pl <- scholar_plot(profile)
pl$citations
pl$publications
|
PurpleAirQC_hourly_AB_01 <- function(
pat = NULL,
min_count = 20,
returnAllColumns = FALSE
) {
MazamaCoreUtils::stopIfNull(pat)
MazamaCoreUtils::stopIfNull(min_count)
MazamaCoreUtils::stopIfNull(returnAllColumns)
countData <-
pat %>%
pat_aggregate( function(x) { base::length(na.omit(x)) } ) %>%
pat_extractData()
meanData <-
pat %>%
pat_aggregate( function(x) { base::mean(x, na.rm = TRUE) } ) %>%
pat_extractData()
FUN <- function(x) {
result <- try({
hourly_ttest <- stats::t.test(x$pm25_A, x$pm25_B, paired = FALSE)
tbl <- dplyr::tibble(
t_score = as.numeric(hourly_ttest$statistic),
p_value = as.numeric(hourly_ttest$p.value),
df_value = as.numeric(hourly_ttest$parameter)
)
}, silent = TRUE)
if ( "try-error" %in% class(result) ) {
tbl <- dplyr::tibble(
t_score = as.numeric(NA),
p_value = as.numeric(NA),
df_value = as.numeric(NA)
)
}
return(tbl)
}
suppressWarnings({
ttestData <-
pat %>%
pat_extractData() %>%
patData_aggregate(FUN)
})
hourlyData <-
dplyr::tibble(datetime = meanData$datetime) %>%
dplyr::mutate(pm25 = (meanData$pm25_A + meanData$pm25_B) / 2) %>%
dplyr::mutate(min_count = pmin(countData$pm25_A, countData$pm25_B, na.rm = TRUE)) %>%
dplyr::mutate(mean_diff = abs(meanData$pm25_A - meanData$pm25_B)) %>%
dplyr::mutate(pm25 = replace(
.data$pm25,
which(.data$min_count < min_count),
NA)
) %>%
dplyr::mutate(pm25 = replace(
.data$pm25,
which( (ttestData$p_value < 1e-4) & (.data$mean_diff > 10) ),
NA)
) %>%
dplyr::mutate(pm25 = replace(
.data$pm25,
which( (.data$pm25 < 100) & (.data$mean_diff > 20) ),
NA)
)
if ( returnAllColumns ) {
hourlyData <-
hourlyData %>%
dplyr::mutate(
pm25_A_count = countData$pm25_A,
pm25_B_count = countData$pm25_B,
pm25_A_mean = meanData$pm25_A,
pm25_B_mean = meanData$pm25_B,
p_value = ttestData$p_value
)
} else {
hourlyData <-
hourlyData %>%
dplyr::select(.data$datetime, .data$pm25)
}
return(hourlyData)
}
|
process__exists <- function(pid) {
rethrow_call(c_processx__process_exists, pid)
}
|
fun.simu.bias.correct.alt <-
function (r, fit.obj)
{
n.simu <- nrow(r)
index.var <- 2:(match("L1", dimnames(r)[[2]]) - 1)
r.adj <- data.matrix(r[, index.var])
r.adj.val <- do.call("rbind", lapply(1:n.simu, function(i,
r.adj, fit.obj, index.var) t(matrix(as.numeric(r.adj[i,
])) - matrix(fit.obj[[3]][index.var - 1])), r.adj, fit.obj,
index.var))
r.adj.val <- colMeans(r.adj.val)
mode(r.adj) <- "numeric"
r.adj.f <- r.adj - matrix(rep(r.adj.val, n.simu), ncol = ncol(r.adj),
byrow = T)
return(r.adj.f)
}
|
extract_lm <- function(parameter, algorithm, df){
my_lm = lm(as.formula(paste(parameter, "~" ,algorithm)), data =df)
R_Squared = summary(my_lm)$r.squared
P_Value = summary(my_lm)$coefficients[8]
Slope = summary(my_lm)$coefficients[2]
Intercept = summary(my_lm)$coefficients[1]
tibble::tibble(R_Squared = R_Squared, Slope = Slope,
Intercept = Intercept, P_Value = P_Value)
}
extract_lm_cv <- function(parameter, algorithm, df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats =5){
if (!requireNamespace("caret", quietly = TRUE))
stop("package caret required, please install it first")
my_formula = as.formula(paste(parameter, "~" ,algorithm))
caret_model = caret::train(form = my_formula,
data = df,
method = "lm",
na.action = na.exclude,
trControl = caret::trainControl(method = "repeatedcv",
number = folds, repeats = nrepeats))
my_lm = caret_model$finalModel
CV_R_Squared = caret::getTrainPerf(caret_model)[, "TrainRsquared"]
RMSE = caret::getTrainPerf(caret_model)[, "TrainRMSE"]
MAE = caret::getTrainPerf(caret_model)[, "TrainMAE"]
R_Squared = summary(my_lm)$r.squared
P_Value = summary(my_lm)$coefficients[8]
Slope = summary(my_lm)$coefficients[2]
Intercept = summary(my_lm)$coefficients[1]
tibble::tibble(R_Squared = R_Squared, Slope = Slope, Intercept = Intercept,
P_Value = P_Value, CV_R_Squared = CV_R_Squared, RMSE = RMSE, MAE = MAE)
}
extract_lm_cv_multi <- function(parameters, algorithms, df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5){
if (!requireNamespace("caret", quietly = TRUE))
stop("package caret required, please install it first")
list = list()
for (i in seq_along(parameters)) {
names(algorithms) <- algorithms %>%
purrr::map_chr(., ~ paste0(parameters[[i]], "_",.))
list[[i]] = algorithms %>%
purrr::map_dfr(~extract_lm_cv(parameter = parameters[[i]], algorithm = algorithms, df = df,
train_method = train_method, control_method = control_method,
folds = folds, nrepeats = nrepeats), .id = "Algorithms")
}
extract_lm_cv_multi_results <- (do.call(rbind, list))
}
extract_lm_cv_all <- function(parameters, df, train_method = "lm", control_method = "repeatedcv", folds = 3, nrepeats = 5){
if (!requireNamespace("caret", quietly = TRUE))
stop("package caret required, please install it first")
list = list()
for (i in seq_along(parameters)) {
algorithms = df %>%
dplyr::select(which(sapply(., class) == "numeric"), -parameters) %>%
names()
names(algorithms) <- algorithms %>%
purrr::map_chr(., ~ paste0(parameters[[i]], "_", .))
list[[i]] = algorithms %>%
purrr::map_dfr(~extract_lm_cv(parameter = parameters[[i]], algorithm = ., df = df,
train_method = train_method, control_method = control_method,
folds = folds, nrepeats = nrepeats), .id = "Algorithms")
}
extract_lm_cv_all_results <- (do.call(rbind, list))
}
|
omegaFreqData <- function(
data,
interval,
omega.int.analytic,
pairwise,
n.boot = 1e3,
parametric = FALSE,
callback = function(){}) {
p <- ncol(data)
n <- nrow(data)
file <- lavOneFile(data)
colnames(data) <- file$names
lam_names <- paste("l", 1:p, sep = "")
err_names <- paste("e", 1:p, sep = "")
model <- paste0("f1 =~ ")
loadings <- paste(paste(lam_names, "*", file$names, sep = ""),
collapse = " + ")
errors <- paste(paste(file$names, " ~~ ", err_names, "*",
file$names, sep = ""), collapse = "\n")
sum_loads <- paste("loading :=", paste(lam_names, collapse = " + "),
"\n")
sum_errs <- paste("error :=", paste(err_names, collapse = " + "),
"\n")
omega <- "omega := (loading^2) / ((loading^2) + error) \n"
mod <- paste(model, loadings, "\n", errors,
"\n", sum_loads, sum_errs, omega)
if (pairwise) {
fit <- fitmodelMis(mod, data)
} else {
fit <- fitmodel(mod, data)
}
if (is.null(fit)) {
return(list(omega = NA, fit.object = NULL))
} else {
params <- lavaan::parameterestimates(fit, level = interval)
omega <- params$est[params$lhs == "omega"]
if (omega.int.analytic) {
om_low <- params$ci.lower[params$lhs == "omega"]
om_up <- params$ci.upper[params$lhs == "omega"]
om_obj <- NA
} else {
if (parametric) {
if (pairwise) {
cc <- cov(data, use = "pairwise.complete.obs")
} else {
cc <- cov(data)
}
om_obj <- numeric(n.boot)
for (i in 1:n.boot){
boot_data <- MASS::mvrnorm(n, colMeans(data, na.rm = TRUE), cc)
fit <- fitmodel(mod, boot_data)
callback()
if (!is.null(fit)) {
params <- lavaan::parameterestimates(fit, level = interval)
om_obj[i] <- params$est[params$lhs == "omega"]
} else {
om_obj[i] <- NA
}
}
if (sum(!is.na(om_obj)) > 1) {
om_low <- quantile(om_obj, prob = (1 - interval) / 2, na.rm = TRUE)
om_up <- quantile(om_obj, prob = interval + (1 - interval) / 2, na.rm = TRUE)
} else {
om_low <- NA
om_up <- NA
om_obj <- NA
}
} else {
om_obj <- numeric(n.boot)
for (i in 1:n.boot){
boot_data <- as.matrix(data[sample.int(n, size = n, replace = TRUE), ])
if (pairwise) {
fit <- fitmodelMis(mod, boot_data)
} else {
fit <- fitmodel(mod, boot_data)
}
callback()
if (!is.null(fit)) {
params <- lavaan::parameterestimates(fit, level = interval)
om_obj[i] <- params$est[params$lhs=="omega"]
} else {
om_obj[i] <- NA
}
}
if (sum(!is.na(om_obj)) > 1) {
om_low <- quantile(om_obj, prob = (1 - interval) / 2, na.rm = TRUE)
om_up <- quantile(om_obj, prob = interval + (1 - interval) / 2, na.rm = TRUE)
} else {
om_low <- NA
om_up <- NA
om_obj <- NA
}
}
}
fit_tmp <- lavaan::fitMeasures(fit)
indic <- c(fit_tmp["chisq"], fit_tmp["df"], fit_tmp["pvalue"],
fit_tmp["rmsea"], fit_tmp["rmsea.ci.lower"], fit_tmp["rmsea.ci.upper"],
fit_tmp["srmr"])
}
return(list(omega = omega, omega_lower = om_low, omega_upper = om_up, indices = indic, fit.object = fit,
omega_boot = om_obj))
}
fitmodel <- function(mod, data) {
out <- tryCatch(
{
lavaan::cfa(mod, data, std.lv = TRUE)
},
error = function(cond) {
return(NULL)
},
warning = function(cond) {
return(NULL)
},
finally = {}
)
return(out)
}
fitmodelMis <- function(mod, data) {
out <- tryCatch(
{
lavaan::cfa(mod, data, std.lv = TRUE, missing = "ML")
},
error = function(cond) {
return(NULL)
},
warning = function(cond) {
return(NULL)
},
finally = {}
)
return(out)
}
|
get_gene_symbol <- function(wilcoxon_rank_mat_t) {
if(is.null(rownames(wilcoxon_rank_mat_t))) {
stop("wilcoxon_rank_mat_t must be an object with row names. Currently, rownames == NULL")
}
the_human <- length(grep("ENSG00", rownames(wilcoxon_rank_mat_t)))
the_mouse <- length(grep("ENSMUSG00", rownames(wilcoxon_rank_mat_t)))
if((the_mouse == 0 & the_human == 0)[1]) {
stop("Matrix is not internal and this function should not be required. gene symbols of genes, bulk matrix, and signature matrix should already match.")
}
if(the_human >= the_mouse) {
theSpecies <- "human"
}
if(the_mouse > the_human) {
theSpecies <- "mouse"
}
sm <- wilcoxon_rank_mat_t
RN = rownames(sm)
RN_1 <- sub('(.*)[.](.*)','\\1',RN)
if(theSpecies == "human") {
RN_2 <- substr(RN_1, 1, nchar(RN_1) - 16)
}
if(theSpecies == "mouse" ) {
RN_2 <- substr(RN_1, 1, nchar(RN_1) - 19)
}
return(list(rowname = RN_2, species = theSpecies))
}
|
expect_hms_equal <- function(x, y) {
expect_s3_class(x, "hms")
expect_s3_class(y, "hms")
expect_equal(as.numeric(x), as.numeric(y))
}
expect_difftime_equal <- function(x, y) {
expect_s3_class(x, "difftime")
expect_s3_class(y, "difftime")
expect_equal(as.numeric(as_hms(x)), as.numeric(as_hms(y)))
}
|
test_that("coherence and phase works for single entry", {
a <- array(rnorm(100), dim = c(100, 1, 1))
expect_warning(phase(a))
expect_warning(coherence(a))
})
|
library("stsm")
library("numDeriv")
y <- log(AirPassengers)
pars <- c("var2" = 7, "var3" = 3.5, "var4" = 25)
cpar <- c("var1" = 12)
nopars <- NULL
transP <- NULL
bar <- list(type = "1", mu = 0)
m <- stsm.model(model = "BSM", y = y,
pars = pars, cpar = cpar, nopars = nopars,
transPars = transP)
get.pars(m)
get.cpar(m)
get.nopars(m)
mcloglik.fd(model = m, barrier = bar)
mcloglik.fd(x = m@pars, model = m, barrier = bar)
a1 <- mcloglik.fd.deriv(model = m,
gradient = TRUE, hessian = TRUE, infomat = TRUE)
a1$gradient
a1$hessian
a2 <- mcloglik.fd.deriv(model = m,
gradient = TRUE, hessian = TRUE, infomat = TRUE)
a2$gradient
a2$hessian
length(a1) == length(a2)
for (i in seq(along = a1))
print(all.equal(a1[[i]], a2[[i]], check.attributes = FALSE))
g <- grad(func = mcloglik.fd, x = m@pars, model = m, barrier = bar)
g
h <- hessian(func = mcloglik.fd, x = m@pars, model = m, barrier = bar)
h
all.equal(a1$gradient, g, check.attributes = FALSE)
all.equal(a1$hessian, h, check.attributes = FALSE)
|
"gcdg_ecu"
|
simYes.opiClose <- function() { return(NULL) }
simYes.opiQueryDevice <- function() { return (list(type="SimNo", isSim=TRUE)) }
simYes.opiInitialize <- function(display = NA) {
if(simDisplay.setupDisplay(display))
warning("opiInitialize (SimNo): display parameter may not contain 4 numbers.")
return(NULL)
}
simYes.opiSetBackground <- function(col, gridCol) {
return (simDisplay.setBackground(col, gridCol))
}
simYes.opiPresent <- function(stim, nextStim=NULL) {
simDisplay.present(stim$x, stim$y, stim$color, stim$duration, stim$responseWindow)
return ( list(
err = NULL,
seen= TRUE,
time= 0
))
}
|
calculate_roc <- function(M, D, ci = FALSE, alpha = .05){
if(sum(c(is.na(M), is.na(D))) > 0) stop("No missing data allowed")
D <- verify_d(D)
T.order <- order(M, decreasing=TRUE)
TTT <- M[T.order]
TPF <- cumsum(D[T.order] == 1)
FPF <- cumsum(D[T.order] == 0)
dups <- rev(duplicated(rev(TTT)))
tp <- c(0, TPF[!dups])/sum(D == 1)
fp <- c(0, FPF[!dups])/sum(D == 0)
cutoffs <- c(Inf, TTT[!dups])
df <- data.frame(FPF = fp, TPF = tp, c = cutoffs)
if(ci){
stopifnot(is.finite(alpha) && alpha < 1 && alpha > 0)
alpha.star <- 1 - sqrt(1 - alpha)
n0 <- sum(D == 0)
n1 <- sum(D == 1)
M0 <- M[D == 0]
M1 <- M[D == 1]
ci_res <- sapply(c, function(x){
FP.L <- stats::qbeta(alpha.star, sum(M0 > x), n0 - sum(M0 > x) + 1)
FP.U <- stats::qbeta(1 - alpha.star, sum(M0 > x) + 1, n0 - sum(M0 > x))
TP.L <- stats::qbeta(alpha.star, sum(M1 > x), n1 - sum(M1 > x) + 1)
TP.U <- stats::qbeta(1 - alpha.star, sum(M1 > x) + 1, n1 - sum(M1 > x))
c(FP.L, FP.U, TP.L, TP.U)
})
ci_res2 <- as.data.frame(t(ci_res))
colnames(ci_res2) <- c("FP.L", "FP.U", "TP.L", "TP.U")
df <- cbind(df, ci_res2)
}
df
}
calculate_multi_roc <- function(data, M_string, D_string){
out_list <- vector("list", length = length(M_string))
D <- verify_d(data[D_string][,1])
for(i in 1:length(out_list)){
M <- data[M_string[i]][,1]
if(sum(c(is.na(M), is.na(D))) > 0) stop("No missing data allowed")
T.order <- order(M, decreasing=TRUE)
TTT <- M[T.order]
TPF <- cumsum(D[T.order] == 1)
FPF <- cumsum(D[T.order] == 0)
dups <- rev(duplicated(rev(TTT)))
tp <- c(0, TPF[!dups])/sum(D == 1)
fp <- c(0, FPF[!dups])/sum(D == 0)
cutoffs <- c(Inf, TTT[!dups])
df <- data.frame(FPF = fp, TPF = tp, c = cutoffs)
out_list[[i]] <- df
}
out_list
}
verify_d <- function(D){
if(length(levels(as.factor(D))) > 2) stop("Only labels with 2 classes supported")
slev <- sort(levels(as.factor(D)))
if(slev[1] == 0 & slev[2] == 1) return(D)
warning(paste0("D not labeled 0/1, assuming ", slev[1], " = 0 and ", slev[2], " = 1!"))
zero1 <- c(0, 1)
names(zero1) <- slev
zero1[as.character(D)]
}
melt_roc <- function(data, d, m, names = NULL){
if(is.null(names)){
names <- colnames(data[, m])
}
data.frame(D = rep(data[, d], length(m)),
M = do.call(c, data[, m]),
name = rep(names, each = nrow(data)), stringsAsFactors = FALSE)
}
is.discrete <- function(x) {
is.factor(x) || is.character(x) || is.logical(x)
}
calc_auc <- function(ggroc){
lays <- sapply(ggroc$layers, function(g) class(g$geom)[1])
stopifnot("GeomRoc" %in% lays)
l1 <- ggplot_build(ggroc)$data[[1]]
comp_auc <- function(df){
auc <- 0
for (i in 2:length(df$x)) {
auc <- auc + 0.5 * (df$x[i] - df$x[i-1]) * (df$y[i] + df$y[i-1])
}
return(data.frame(AUC = auc))
}
plyr::ddply(l1, ~ PANEL + group, comp_auc)
}
|
test_that("dg works", {
depo <- as.list(gen_GHvalid(1, h = 0)[, c('a', 'b', 'g')])
depo %<>%
modifyList(list(n = 250)) %>%
do.call('rg', .) %>%
list(x = .) %>%
modifyList(depo) %>%
do.call('dg', .)
expect_true(all(depo >= 0))
depo <- gen_GHvalid(100, g = 0, h = 0)
depox <- rnorm(100, depo$a, depo$b)
expect_equal(
with(depo, dg(depox, a, b, g)),
with(depo, dnorm(depox, a, b)),
tolerance = 1e-7
)
depo <- gen_GHvalid(100, h = 0)
depo$g %<>% abs
depo$x <- with(depo, mapply(rg, a = a, b = b, g = g, MoreArgs = list(n = 1)))
expect_equal(
with(depo, dg(depo$x, a, b, g)),
with(depo, g / b * dlnorm(1 + g * (depo$x - a) / b, 0, g)),
tolerance = 1e-7
)
})
|
guessDateFormat <- function(x) {
x1 <- x
if(!inherits(x1[1], "character")) {
x1 <- as.character(x1)
}
x1[x1 == ""] <- NA
x1 <- x1[!is.na(x1)]
if(length(x1) == 0) return(NA)
dateTimes <- do.call(rbind, strsplit(x1, ' '))
for(i in ncol(dateTimes)) {
dateTimes[dateTimes[,i] == "NA"] <- NA
}
timePart <- which(apply(dateTimes, MARGIN=2, FUN=function(i) { any(grepl(":", i)) }))
datePart <- setdiff(seq(ncol(dateTimes)), timePart)
if(length(timePart) > 1 || length(datePart) != 1) stop("cannot parse your time variable")
timeFormat <- NA
if(length(timePart)) {
hasNoTm <- is.na(dateTimes[,timePart])
ncolons <- max(nchar(gsub("[^:]", "", dateTimes[!hasNoTm,timePart])))
if(ncolons == 1) {
timeFormat <- "%H:%M"
} else if(ncolons == 2) {
timeFormat <- "%H:%M:%S"
} else stop("timePart should have 1 or 2 colons")
}
hasNoDt <- is.na(dateTimes[,datePart])
nonMissDt <- dateTimes[!hasNoDt,datePart]
sep <- unique(substr(gsub("[0-9]", "", nonMissDt), 1, 1))
if(length(sep) > 1 && "" %in% sep) {
sep <- sep[sep != '']
}
if(length(sep) > 1) stop("too many seperators in datePart")
dates <- gsub("[^0-9]", "", nonMissDt)
dlen <- max(nchar(dates))
dateFormat <- NA
dtfrm1 <- paste0("%y", "%m", "%d")
dtfrm2 <- paste0("%m", "%d", "%y")
dtfrm3 <- paste0("%Y", "%m", "%d")
dtfrm4 <- paste0("%m", "%d", "%Y")
if(dlen %in% 4:6) {
if(sum(is.na(as.Date(dates, format=dtfrm1))) == 0) {
dateFormat <- dtfrm1
} else if(sum(is.na(as.Date(dates, format=dtfrm2))) == 0) {
dateFormat <- dtfrm2
} else stop("datePart format [four-six characters] is inconsistent")
} else if(dlen %in% 7:8) {
if(sum(is.na(as.Date(dates, format=dtfrm3))) == 0) {
dateFormat <- dtfrm3
} else if(sum(is.na(as.Date(dates, format=dtfrm4))) == 0) {
dateFormat <- dtfrm4
} else stop("datePart format [seven-eight characters] is inconsistent")
} else {
stop(sprintf("datePart has unusual length: %s", dlen))
}
dateFormat <- paste(substr(dateFormat, 1, 2), substr(dateFormat, 3, 4), substr(dateFormat, 5, 6), sep = sep)
if(is.na(timeFormat)) {
format <- dateFormat
} else if(timePart == 1) {
format <- paste(timeFormat, dateFormat)
} else if(timePart == 2) {
format <- paste(dateFormat, timeFormat)
} else stop("cannot parse your time variable")
format
}
parse_dates <- function(x, tz = getOption('pkdata.tz', '')) {
if(inherits(x, "POSIXct")) return(x)
res <- rep(NA, length(x))
x[grepl("NA", x)] <- NA
fmt <- guessDateFormat(x)
if(is.na(fmt)) return(res)
fmt <- gsub("[^ymd ]", "", tolower(fmt))
if(grepl(" ", fmt)) {
fmt <- sub(" .*$", "_HMS", fmt)
x[!grepl(" ", sub('[[:space:]]$', '', x))] <- NA
res <- lubridate::parse_date_time(x, orders = fmt, tz = tz, truncated = 2)
} else {
res <- as.Date(lubridate::parse_date_time(x, orders = fmt, tz = tz))
}
res
}
round_hours <- function(x) {
toAdd <- ifelse(lubridate::minute(x) >= 30, lubridate::dhours(1), lubridate::dhours(0))
lubridate::floor_date(x, unit = 'hour') + toAdd
}
|
claim_frequency <- function(
I = 40, E = 12000, freq = 0.03, simfun, type = c("r", "p"), ...) {
if (!missing(simfun)) {
type <- match.arg(type)
if (type == "r") {
simfun(I, ...)
} else if (type == "p") {
name_as_chr <- deparse(substitute(simfun))
name_contains_pkg <- grepl("::", name_as_chr)
if (name_contains_pkg == TRUE) {
pkg <- unlist(strsplit(name_as_chr, split = "::"))[1]
fun <- unlist(strsplit(name_as_chr, split = "::"))[2]
substr(fun, 1, 1) <- "r"
found_r <- exists(fun, where = asNamespace(pkg), mode = "function")
} else {
fun <- name_as_chr
substr(fun, 1, 1) <- "r"
found_r <- exists(fun, mode = "function")
}
if (found_r == TRUE) {
rfun <- ifelse(exists("pkg"), getExportedValue(pkg, fun), get(fun))
rfun(I, ...)
} else {
simulate_cdf(I, simfun, ...)
}
}
} else {
stats::rpois(I, E * .pkgenv$time_unit * freq)
}
}
claim_occurrence <- function(frequency_vector) {
I <- length(frequency_vector)
occurrence_times <- vector("list", I)
for (i in 1:I) {
occurrence_times[[i]] <- stats::runif(frequency_vector[i], min = i - 1, max = i)
}
occurrence_times
}
|
compare_check.set<-function(RM_set_1,RM_set_2,DM_set_1,DM_set_2,DM_mesh_1,DM_mesh_2){
dim1<-dim(RM_set_1)[1]
dim2<-dim(RM_set_2)[1]
SF1<-cSize(DM_set_1)/cSize(RM_set_1)
SF2<-cSize(DM_set_2)/cSize(RM_set_2)
scale_factor<-(SF1+SF2)/2
RM_set_1_sc<-RM_set_1*scale_factor
RM_set_2_sc<-RM_set_2*scale_factor
AM_mesh_1<-rotmesh.onto(DM_mesh_1, DM_set_1,RM_set_1_sc, adnormals = FALSE, scale = FALSE,
reflection = FALSE)
AM_mesh_2<-rotmesh.onto(DM_mesh_2, DM_set_2,RM_set_2_sc, adnormals = FALSE, scale = FALSE,
reflection = FALSE)
AM_mesh<-mergeMeshes(AM_mesh_1$mesh,AM_mesh_2$mesh)
AM_rot<-rotmesh.onto(AM_mesh,rbind(AM_mesh_1$yrot,AM_mesh_2$yrot),
rbind(RM_set_1_sc,RM_set_2_sc), adnormals = FALSE, scale = FALSE,
reflection = FALSE)
check_dist<-abs(sum(projRead(rbind(RM_set_1_sc,RM_set_2_sc),AM_rot$mesh)$quality))
procr_dist<-vegan::procrustes(AM_rot$yrot,rbind(RM_set_1_sc,RM_set_2_sc))$ss
eucl_dist<-sum(sqrt(rowSums((AM_rot$yrot-rbind(RM_set_1_sc,RM_set_2_sc))^2)))
check_1<-sum(sqrt(rowSums((AM_rot$yrot[1:dim1,]-RM_set_1_sc)^2)))
check_2<-sum(sqrt(rowSums((AM_rot$yrot[(dim1+1):(dim1+dim2),]-RM_set_2_sc)^2)))
procr_dist_1<-vegan::procrustes(AM_rot$yrot[1:dim1,],RM_set_1_sc)$ss
procr_dist_2<-vegan::procrustes(AM_rot$yrot[(dim1+1):(dim1+dim2),],RM_set_2_sc)$ss
single_l_1<-sqrt(rowSums((AM_rot$yrot[1:dim1,]-RM_set_1_sc)^2))
single_l_2<-sqrt(rowSums((AM_rot$yrot[(dim1+1):(dim1+dim2),]-RM_set_2_sc)^2))
out<-list("SF1"=SF1,"SF2"=SF2,"RM_set_1_sc"=RM_set_1_sc,"RM_set_2_sc"=RM_set_2_sc,
"AM_model"=AM_rot,"dist_from_mesh"=check_dist,"eucl_dist_1"=check_1,"eucl_dist_2"=check_2,
"procr_dist"=procr_dist,"procr_dist_1"=procr_dist_1,"procr_dist_2"=procr_dist_2,"eucl_dist"=eucl_dist,"single_l_1"=single_l_1,"single_l_2"=single_l_2)
return(out)
}
|
dataset_mnist_digits <- function(ntrain = 60000L, ntest = 10000L, onehot = TRUE) {
python_path <- system.file("python", package = "rTorch")
tools <- import_from_path("torchtools", path = python_path)
tools$data_util$load_mnist(ntrain, ntest, onehot)
}
|
.TuMadrlsGetvar <- function(a, r){
A.loc <- 1/(2*a*dnorm(a)*(a^2 - 15) + (a^4 - 6*a^2 + 15)*(2*pnorm(a)-1))
h1 <- 2*integrate(f = function(x, a0){ x^2*(a0^2-x^2)^4*dnorm(x) }, lower = 0,
upper = a, rel.tol = .Machine$double.eps^0.5, a0 = a)$value
a.mad <- qnorm(0.75)
b.mad <- 1/(4*a.mad*dnorm(a.mad))
return(A.loc^2*h1 + b.mad^2)
}
.TuMadrlsGetmse <- function(a, r){
A.loc <- 1/(2*a*dnorm(a)*(a^2 - 15) + (a^4 - 6*a^2 + 15)*(2*pnorm(a)-1))
a.mad <- qnorm(0.75)
b.mad <- 1/(4*a.mad*dnorm(a.mad))
b.2 <- sqrt(A.loc^2*(16/25/sqrt(5)*a^5)^2 + b.mad^2)^2
return(.TuMadrlsGetvar(a = a) + r^2*b.2)
}
rlsOptIC.TuMad <- function(r, aUp = 10, delta = 1e-6){
res <- optimize(f = .TuMadrlsGetmse, lower = 1e-4, upper = aUp,
tol = delta, r = r)
a <- res$minimum
A.loc <- 1/(2*a*dnorm(a)*(a^2 - 15) + (a^4 - 6*a^2 + 15)*(2*pnorm(a)-1))
a.mad <- qnorm(0.75)
b.mad <- 1/(4*a.mad*dnorm(a.mad))
bias <- sqrt(A.loc^2*(16/25/sqrt(5)*a^5)^2 + b.mad^2)
fct1 <- function(x){ A.loc*x*(a^2 - x^2)^2*(abs(x) < a) }
body(fct1) <- substitute({ A.loc*x*(a^2 - x^2)^2*(abs(x) < a) },
list(a = a, A.loc = A.loc))
fct2 <- function(x){ b.mad*sign(abs(x) - a.mad) }
body(fct2) <- substitute({ b.mad*sign(abs(x) - a.mad) },
list(a.mad = a.mad, b.mad = b.mad))
return(IC(name = "IC of TuMad type",
Curve = EuclRandVarList(RealRandVariable(Map = list(fct1, fct2), Domain = Reals())),
Risks = list(asMSE = res$objective, asBias = bias, asCov = res$objective - r^2*bias^2),
Infos = matrix(c("rlsOptIC.TuMad", "optimally robust IC for TuMad estimators and 'asMSE'",
"rlsOptIC.TuMad", paste("where a =", round(a, 3))),
ncol=2, byrow = TRUE, dimnames=list(character(0), c("method", "message"))),
CallL2Fam = call("NormLocationScaleFamily")))
}
|
`xport.namestr.header` <- function( nvar )
{
.C("fill_namestr_header",
nvar = sprintf("%04.4d", as.integer(nvar)),
PACKAGE="SASxport"
)
.Call("getRawBuffer", PACKAGE="SASxport")
}
|
`dssaveintersect` <-
function(...,method='averaging'){
x=list(...)
xlo=list();
xhi=list();
n=dim(x[[1]])[1];
m=length(x);
tochecklo=numeric()
tocheckhi=numeric()
for(i in 1:m){
x[[i]]=x[[i]][order(x[[i]][,1]),,drop=FALSE]
xlo[[i]]=cbind(x[[i]],cumsum(x[[i]][,3]));
tochecklo=c(tochecklo,xlo[[i]][,4]);
x[[i]]=x[[i]][order(x[[i]][,2]),,drop=FALSE]
xhi[[i]]=cbind(x[[i]],cumsum(x[[i]][,3]));
tocheckhi=c(tocheckhi,xhi[[i]][,4]);
}
old=0
tocheck=c(tochecklo, tocheckhi)
tocheck=sort(unique(tocheck))
erg=matrix(NA,length(tocheck),3);
for(i in 1:length(tocheck)){
lo=numeric(m);
hi=numeric(m);
for(j in 1:m){
indlo=min(which(xlo[[j]][,4]+1E-10>=tocheck[i]))
lo[j]=xlo[[j]][indlo,1]
indhi=min(which(xhi[[j]][,4]+1E-10>=tocheck[i]))
hi[j]=xhi[[j]][indhi,2]
}
erg[i,]=c(max(lo),min(hi),tocheck[i]-old)
if(erg[i,1]>erg[i,2]){
if(method=='averaging'){
erg[i,1:2]=c(mean(lo),mean(hi))
}else{
erg[i,1:2]=c(min(lo),max(hi))
}
}
old=tocheck[i];
}
erg=dsstruct(erg)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.