code
stringlengths 1
13.8M
|
---|
rgb2alpha <- function(raw_col, alpha) {
raw_col_rgb <- col2rgb(raw_col)
alpha_col <- rgb(
raw_col_rgb[1L, ], raw_col_rgb[2L, ], raw_col_rgb[3L, ],
alpha = alpha * 255L, maxColorValue = 255L
)
alpha_col
}
plot.cv.enpls <- function(
x, xlim = NULL, ylim = NULL, alpha = 0.8,
main = NULL, ...) {
if (!inherits(x, "cv.enpls")) {
stop('This function only works for objects of class "cv.enpls"')
}
df <- as.data.frame(x$"ypred")
xrange <- range(df$"y.real")
yrange <- range(df$"y.pred")
fixrange <- c(min(xrange[1L], yrange[1L]), max(xrange[2L], yrange[2L]))
if (is.null(xlim)) xlim <- fixrange
if (is.null(ylim)) ylim <- fixrange
ggplot(
df,
aes_string(
x = "y.real", y = "y.pred",
xmin = xlim[1L], xmax = xlim[2L],
ymin = ylim[1L], ymax = ylim[2L]
)
) +
geom_abline(slope = 1, intercept = 0, colour = "darkgrey") +
geom_point(size = 3, shape = 1, alpha = alpha) +
coord_fixed(ratio = 1) +
xlab("Observed Response") +
ylab("Predicted Response")
}
plot.enpls.fs <- function(
x, nvar = NULL,
type = c("dotplot", "boxplot"),
limits = c(0, 1),
main = NULL, ...) {
if (!inherits(x, "enpls.fs")) {
stop('This function only works for objects of class "enpls.fs"')
}
type <- match.arg(type)
imp <- x$"variable.importance"
if (is.null(nvar)) nvar <- length(imp)
if (type == "dotplot") {
df <- data.frame(sort(imp, TRUE)[nvar:1])
df[, 2L] <- row.names(df)
names(df) <- c("varimp", "varname")
df$"varname" <- factor(df$"varname", levels = df$"varname")
p <- ggplot(df) +
geom_point(aes_string(x = "varimp", y = "varname")) +
theme(
panel.grid.major.x = element_blank(),
panel.grid.major.y = element_line(linetype = 3, color = "darkgray")
) +
xlab("Variable Importance Score") +
ylab("Variable Name")
}
if (type == "boxplot") {
mat <- x$"coefficient.matrix"
df <- as.data.frame(mat[, names(sort(imp, TRUE)[nvar:1])])
df <- suppressMessages(melt(df))
p <- ggplot(df, aes_string(x = "variable", y = "value")) +
scale_y_continuous(limits = quantile(df$"value", limits)) +
geom_boxplot() + coord_flip() +
xlab("Variable Name") +
ylab("Coefficient")
}
p
}
plot.enpls.od <- function(
x,
criterion = c("quantile", "sd"),
prob = 0.05, sdtimes = 3L,
alpha = 1, main = NULL, ...) {
if (!inherits(x, "enpls.od")) {
stop('This function only works for objects of class "enpls.od"')
}
criterion <- match.arg(criterion)
error.mean <- x$"error.mean"
error.sd <- x$"error.sd"
if (criterion == "quantile") {
vpos <- quantile(error.mean, 1 - prob, na.rm = TRUE)
hpos <- quantile(error.sd, 1 - prob, na.rm = TRUE)
} else {
vpos <- mean(error.mean, na.rm = TRUE) + (sdtimes * sd(error.mean, na.rm = TRUE))
hpos <- mean(error.sd, na.rm = TRUE) + (sdtimes * sd(error.sd, na.rm = TRUE))
}
yout <- intersect(which(error.mean >= vpos), which(error.sd <= hpos))
Xout <- intersect(which(error.mean <= vpos), which(error.sd >= hpos))
abnormal <- intersect(which(error.mean >= vpos), which(error.sd >= hpos))
plot(error.mean, error.sd,
xlab = "Error Mean", ylab = "Error SD",
bty = "n", xaxt = "n", yaxt = "n", main = main, ...
)
rect(par("usr")[1], par("usr")[3],
par("usr")[2], par("usr")[4],
col = "
)
rect(par("usr")[1], par("usr")[3],
par("usr")[2], par("usr")[4],
border = "darkgrey", lwd = 0.5
)
grid(col = "white", lty = 1)
points(error.mean, error.sd, col = rgb2alpha("
axis(side = 1, labels = TRUE, col = "darkgrey", lwd = 0.3, cex.axis = 0.8)
axis(side = 2, labels = TRUE, col = "darkgrey", lwd = 0.3, cex.axis = 0.8)
abline(h = hpos, col = "black", lty = 2)
abline(v = vpos, col = "black", lty = 2)
if (length(yout) != 0L) {
points(error.mean[yout], error.sd[yout],
pch = 21,
col = rgb2alpha("
bg = rgb2alpha("
)
text(error.mean[yout], error.sd[yout],
labels = as.character(yout),
col = "
)
}
if (length(Xout) != 0L) {
points(error.mean[Xout], error.sd[Xout],
pch = 21,
col = rgb2alpha("
bg = rgb2alpha("
)
text(error.mean[Xout], error.sd[Xout],
labels = as.character(Xout),
col = "
)
}
if (length(abnormal) != 0L) {
points(error.mean[abnormal], error.sd[abnormal],
pch = 21,
col = rgb2alpha("
bg = rgb2alpha("
)
text(error.mean[abnormal], error.sd[abnormal],
labels = as.character(abnormal),
col = "
)
}
}
plot.enpls.ad <- function(
x, type = c("static", "interactive"), main = NULL, ...) {
if (!inherits(x, "enpls.ad")) {
stop('This function only works for objects of class "enpls.ad"')
}
type <- match.arg(type)
n.testset <- length(x$"te.error.mean")
nsamp.tr <- length(x$"tr.error.mean")
nsamp.te <- sapply(x$"te.error.mean", length)
tr.df <- data.frame(
"Mean" = x$"tr.error.mean",
"SD" = x$"tr.error.sd",
"Set" = "Train"
)
te.list <- vector("list", n.testset)
for (i in 1L:n.testset) {
te.list[[i]] <- data.frame(
"Mean" = x[["te.error.mean"]][[i]],
"SD" = x[["te.error.sd"]][[i]],
"Set" = paste0("Test.", i)
)
}
df <- rbind(tr.df, Reduce(rbind, te.list))
if (type == "static") {
p <- ggplot(df) +
geom_point(aes_string(
x = "Mean", y = "SD",
color = "Set", shape = "Set"
)) +
scale_shape(solid = FALSE) +
scale_colour_brewer(palette = "Set1") +
xlab("Absolute Mean Prediction Error") +
ylab("Prediction Error SD")
} else {
hovertext <- sprintf("Sample ID: %s", rownames(df))
df <- data.frame(df, "hovertext" = hovertext)
g <- ggplot(df) +
geom_point(aes_string(
x = "Mean", y = "SD",
color = "Set", text = "hovertext"
)) +
scale_colour_brewer(palette = "Set1") +
xlab("Absolute Mean Prediction Error") +
ylab("Prediction Error SD")
p <- ggplotly(g)
}
p
} |
compute_fs = function(fs_time_horizon,T=NA,fs_dates=NA){
if(all(is.na(fs_dates))){
if(is.numeric(fs_time_horizon)){
T_star = rep(fs_time_horizon,T)
}
if(fs_time_horizon %in% c("w","m","q","y")){
if(fs_time_horizon == "w") size = 5
if(fs_time_horizon == "m") size = 25
if(fs_time_horizon == "q") size = 70
if(fs_time_horizon == "y") size = 260
T_star = sample(1:size,T,replace=TRUE,prob=dbinom(1:size,size,0.9)/sum(dbinom(1:size,size,0.9)))
}
} else {
dates_overview = data.frame("w" = as.numeric(strftime(fs_dates,format ="%W")),
"m" = as.numeric(strftime(fs_dates,format ="%m")),
"q" = as.numeric(substr(quarters(fs_dates),2,2)),
"y" = as.numeric(strftime(fs_dates,format ="%Y")))
if(fs_time_horizon == "w"){
T_star = vector()
for(y in unique(dates_overview[["y"]])){
dates_overview_subset = dates_overview[dates_overview[["y"]]==y,]
T_star = c(T_star,as.vector(table(dates_overview_subset[["w"]])))
}
}
if(fs_time_horizon == "m"){
T_star = vector()
for(y in unique(dates_overview[["y"]])){
dates_overview_subset = dates_overview[dates_overview[["y"]]==y,]
T_star = c(T_star,as.vector(table(dates_overview_subset[["m"]])))
}
}
if(fs_time_horizon == "q"){
T_star = vector()
for(y in unique(dates_overview[["y"]])){
dates_overview_subset = dates_overview[dates_overview[["y"]]==y,]
T_star = c(T_star,as.vector(table(dates_overview_subset[["q"]])))
}
}
if(fs_time_horizon == "y"){
T_star = as.vector(table(dates_overview[["y"]]))
}
if(is.numeric(fs_time_horizon)){
T_star = rep(fs_time_horizon,floor(length(fs_dates)/fs_time_horizon))
}
}
return(T_star)
} |
fetchBMdata = function(url = NULL, id = NULL){
if(is.null(url)){
url = "http://www.fbi.gov/about-us/lab/forensic-science-communications/fsc/july1999/dnaloci.txt"
}
if(is.null(id)){
id = "parent-fieldname-text-2baa15a4d877814a4a62588114966028"
}
fetchLines = function(){
webpage = read_html(url)
xpath = paste0('//div[@id="', id, '"]')
data = html_text(html_nodes(webpage, xpath = xpath))
Lines = unlist(strsplit(data, "[\r]+"))
i1 = grep("Table 1.", Lines)
i2 = grep("^3409", Lines)
Lines = Lines[i1:i2]
}
Lines = fetchLines()
Lines = gsub("[&][
Lines = stringr::str_trim(Lines)
Lines = gsub("(<|>)[0-9]+","108.1",Lines)
Lines = Lines[nchar(Lines)>0]
Lines = Lines[-1]
popLocations = which(nchar(Lines) < 50)
popNames = Lines[popLocations]
Loci = unlist(strsplit(Lines[2], "[\t ]+"))[-1]
nLoci = length(Loci)
Alleles = vector(length = nLoci, mode = "list")
allPops = strsplit(Lines[-c(popLocations,popLocations+1)],"[\t ]+")
allPops = lapply(allPops, function(profile){
l = 2 * nLoci + 1 - length(profile)
if(l != 0){
profile = c(profile, rep(NA, l))
}
profile[profile == "0"] = NA
profile
}
)
Alleles = vector(mode = "list", length = nLoci)
apm = do.call("rbind", allPops)
for(loc in 1:nLoci){
i1 = 2 * loc
i2 = i1 + 1
alleles = c(apm[,i1], apm[,i2])
alleles = alleles[!is.na(alleles)]
Alleles[[loc]] = sort(unique(alleles))
if(all(grepl("^[0-9.]+$", Alleles[[loc]]))){
Alleles[[loc]] = as.character(sort(as.numeric(Alleles[[loc]])))
}
}
names(Alleles) = Loci
numPops = length(popNames)
db = vector(length = numPops, mode = "list")
names(db) = popNames
i1 = popLocations + 2
i2 = c(popLocations[-1] - 1, length(Lines))
popSizes = i2 - i1 + 1
start = cumsum(c(1, popSizes[-numPops]))
end = cumsum(popSizes)
for(pop in 1:numPops){
if(pop > 3){
nLoci = 13
Loci = Loci[1:nLoci]
}
db[[pop]] = list(loci = Loci,
profiles = apm[start[pop]:end[pop], 1:(2 * nLoci + 1)],
freqs = vector(mode = "list", length = nLoci))
names(db[[pop]]$freqs) = Loci
for(loc in 1:nLoci){
i1 = 2 * loc
i2 = i1 + 1
a = c(db[[pop]]$profiles[,i1], db[[pop]]$profiles[,i2])
a = factor(a, levels = Alleles[[loc]])
tbl = xtabs(~a)
db[[pop]]$freqs[[loc]] = tbl / sum(tbl)
}
}
return(db)
} |
context("TEST MODELTIME PLOTS")
m750 <- m4_monthly %>% filter(id == "M750")
splits <- initial_time_split(m750, prop = 0.8)
model_spec <- arima_reg(seasonal_period = 12) %>%
set_engine("auto_arima")
model_fit <- model_spec %>%
fit(log(value) ~ date, data = training(splits))
forecast_tbl <- model_fit %>%
modeltime_calibrate(new_data = testing(splits)) %>%
modeltime_forecast(
actual_data = m750,
conf_interval = 0.95)
g <- forecast_tbl %>%
mutate_at(vars(.value:.conf_hi), exp) %>%
plot_modeltime_forecast(.interactive = FALSE)
suppressWarnings({
p <- forecast_tbl %>%
mutate_at(vars(.value:.conf_hi), exp) %>%
plot_modeltime_forecast(.interactive = TRUE)
})
test_that("modeltime plot, Test Static ggplot", {
testthat::expect_s3_class(g, "ggplot")
testthat::expect_s3_class(g$layers[[1]]$geom, "GeomRibbon")
})
test_that("modeltime plot, Test Interactive plotly", {
testthat::expect_s3_class(p, "plotly")
})
g <- forecast_tbl %>%
mutate_at(vars(.value:.conf_hi), exp) %>%
plot_modeltime_forecast(.interactive = FALSE, .conf_interval_show = FALSE)
p <- forecast_tbl %>%
mutate_at(vars(.value:.conf_hi), exp) %>%
plot_modeltime_forecast(.interactive = TRUE, .conf_interval_show = FALSE)
test_that("modeltime plot, Test Static ggplot", {
testthat::expect_s3_class(g, "ggplot")
testthat::expect_s3_class(g$layers[[1]]$geom, "GeomLine")
})
test_that("modeltime plot, Test Interactive plotly", {
testthat::expect_s3_class(p, "plotly")
})
model_spec <- arima_reg(seasonal_period = 12) %>%
set_engine("auto_arima")
recipe_spec <- recipe(value ~ date, data = training(splits)) %>%
step_log(value, skip = FALSE)
wflw <- workflow() %>%
add_recipe(recipe_spec) %>%
add_model(model_spec)
wflw_fit <- wflw %>%
fit(training(splits))
forecast_tbl <- wflw_fit %>%
modeltime_calibrate(testing(splits)) %>%
modeltime_forecast(actual_data = m750, conf_interval = 0.8)
g <- forecast_tbl %>%
mutate_at(vars(.value:.conf_hi), exp) %>%
plot_modeltime_forecast(.conf_interval_show = TRUE, .interactive = FALSE)
p <- forecast_tbl %>%
mutate_at(vars(.value:.conf_hi), exp) %>%
plot_modeltime_forecast(.conf_interval_show = TRUE, .interactive = TRUE)
test_that("modeltime plot - workflow, Test Static ggplot", {
testthat::expect_s3_class(g, "ggplot")
testthat::expect_s3_class(g$layers[[1]]$geom, "GeomRibbon")
})
test_that("modeltime plot - workflow, Test Interactive plotly", {
testthat::expect_s3_class(p, "plotly")
}) |
append.dictionary <- function(...,
dictionary.name = "appendix",
save.location = c("envir","wd","choose","path"),
path = NULL,
textcleaner = FALSE,
package = FALSE)
{
word.list <- list(...)
words <- unlist(word.list)
name <- as.character(substitute(list(...)))
name <- name[-which(name=="list")]
dicts <- grep(".dictionary", name)
if(textcleaner){
if(length(dicts) != 0){
dict.words <- sort(unique(unlist(word.list[dicts])))
new.words <- setdiff(words, dict.words)
}else{new.words <- words}
}
if(package)
{
if(missing(save.location))
{save.location <- "path"}
path <- "D:/R Packages/SemNetDictionaries/data"
updated <- sort(unique(c(unlist(words), load.dictionaries(dictionary.name))))
dictionary <- paste(dictionary.name, ".dictionary", sep = "")
assign(dictionary, updated, envir = environment())
data.path <- paste(path, "/", dictionary, ".Rdata", sep = "")
save(list = dictionary, file = data.path, envir = environment(), version = 2)
return(message(paste(dictionary, ".Rdata was updated.", sep = "")))
}
if(missing(save.location))
{save.location <- "envir"
}else{save.location <- match.arg(save.location)}
if(save.location == "envir")
{
sav.files <- ls(envir = globalenv())
append.data <- paste(dictionary.name,"dictionary",sep=".")
}else if(save.location != "envir")
{
if(save.location == "wd")
{
path <- getwd()
}else if(save.location == "choose")
{
path <- paste(tcltk::tkchooseDirectory(), collapse = " ")
}else if(save.location == "path")
{
if(is.null(path))
{stop("A 'path' must be specified.")}
if(!dir.exists(path))
{stop("'path' does not exist.")}
}
sav.loc <- path
sav.files <- list.files(sav.loc)
append.data <- paste(dictionary.name,"dictionary","rds",sep=".")
}
if(append.data %in% sav.files)
{
if(!textcleaner){
new.words <- unlist(words)
}
new.words <- tolower(new.words)
if(save.location != "envir")
{
append.words <- readRDS(paste(sav.loc,append.data,sep="/"))
}else if(save.location == "envir")
{
if(textcleaner)
{append.words <- dict.words
}else{append.words <- get(paste(dictionary.name,"dictionary",sep="."), envir = globalenv())}
}
comb.words <- c(append.words,new.words)
append.words <- unique(sort(comb.words))
if(save.location == "envir")
{
if(!textcleaner)
{message("Dictionary has been updated")
}else{message(paste("\nResponse was ADDED TO DICTIONARY:", paste("'", new.words, "'", sep = "")))}
return(append.words)
}else if(save.location == "choose")
{
if(!textcleaner){
ans <- yes.no.menu(title = "Update your dictionary")
}else{ans <- 1}
if(ans == 1)
{
saveRDS(append.words, file = file.path(paste(sav.loc,append.data,sep="/")), version = 2)
message(paste("\n", append.data," has been updated.",sep=""))
}else if(ans == 2)
{
message(paste("\n", append.data," was not updated.",sep=""))
}
}else{
saveRDS(append.words, file = file.path(paste(sav.loc,append.data,sep="/")), version = 2)
message(paste("\n", append.data," has been updated.",sep=""))
}
}else{
append.words <- unlist(words)
append.words <- tolower(append.words)
if(textcleaner)
{append.words <- unique(sort(c(append.words, dict.words)))
}else{append.words <- unique(sort(append.words))}
if(save.location == "envir")
{
if(!textcleaner)
{message("Dictionary has been created")
}else{message(paste("\nResponse was ADDED TO DICTIONARY:", paste("'", new.words, "'", sep = "")))}
return(append.words)
}else if(save.location == "choose")
{
if(!textcleaner)
{ans <- yes.no.menu(title = "Save your dictionary")
}else{ans <- 1}
if(ans == 1)
{
saveRDS(append.words, file = file.path(paste(sav.loc,append.data,sep="/")), version = 2)
message(paste("\nA new dictionary file was created in: '",
paste(sav.loc, append.data, sep="/"), "'", sep = ""))
}else if(ans == 2)
{
message(paste("\n",append.data," was not saved.",sep=""))
}
}else{
saveRDS(append.words, file = file.path(paste(sav.loc,append.data,sep="/")), version = 2)
message(paste("\nA new dictionary file was created in: '",
paste(sav.loc, append.data, sep="/"), "'", sep = ""))
}
}
} |
`rda.default` <-
function (X, Y = NULL, Z = NULL, scale = FALSE, ...)
{
if (inherits(X, "dist") || NCOL(X) == NROW(X) &&
isTRUE(all.equal(X, t(X))))
stop("function cannot be used with (dis)similarities")
X <- as.matrix(X)
if (!is.null(Y)) {
if (is.data.frame(Y) || is.factor(Y))
Y <- model.matrix(~ ., as.data.frame(Y))[,-1,drop=FALSE]
Y <- as.matrix(Y)
}
if (!is.null(Z)) {
if (is.data.frame(Z) || is.factor(Z))
Z <- model.matrix(~ ., as.data.frame(Z))[,-1,drop=FALSE]
Z <- as.matrix(Z)
}
sol <- ordConstrained(X, Y, Z, arg = scale, method = "rda")
call <- match.call()
call[[1]] <- as.name("rda")
sol$call <- call
inertia <- if (scale) "correlations" else "variance"
sol <- c(sol,
list("inertia" = inertia))
sol$regularization <- "this is a vegan::rda result object"
class(sol) <- c("rda", "cca")
sol
} |
list_images <- function(start, length, options=NULL, ...) {
args <- pc(list(options = paste0(options, collapse = " ")))
path <- file.path('api/a/image/list', start, length)
phy_GET(path, args, ...)$result
} |
"[.ratetable" <- function(x, ..., drop=TRUE) {
aa <- attributes(x)
attributes(x) <- aa[c("dim", "dimnames")]
y <- NextMethod("[", drop=FALSE)
newdim <- attr(y, 'dim')
if (is.null(newdim)) return(y)
dropped <- (newdim==1)
if (drop) change <- (newdim!=aa$dim & !dropped)
else change <- (newdim!=aa$dim)
if (any(change)) {
newcut <- aa$cutpoints
for (i in (1:length(change))[change])
if (!is.null(newcut[[i]])) newcut[[i]] <-
(newcut[[i]])[match(dimnames(y)[[i]], aa$dimnames[[i]])]
aa$cutpoints <- newcut
}
if (drop && any(dropped)){
if (all(dropped)) as.numeric(y)
else {
attributes(y) <- list( dim = dim(y)[!dropped],
dimnames = dimnames(y)[!dropped],
dimid = aa$dimid[!dropped],
factor = aa$factor[!dropped],
cutpoints =aa$cutpoints[!dropped],
type = aa$type[!dropped])
class(y) <- 'ratetable'
y
}
}
else {
aa$dim <- aa$dimnames <- NULL
attributes(y) <- c(attributes(y), aa)
y
}
}
is.na.ratetable <- function(x)
structure(is.na(as.vector(x)), dim=dim(x), dimnames=dimnames(x))
Math.ratetable <- function(x, ...) {
attributes(x) <- attributes(x)[c("dim", "dimnames")]
NextMethod(.Generic)
}
Ops.ratetable <- function(e1, e2) {
if (nchar(.Method[1])) attributes(e1) <- attributes(e1)[c("dim","dimnames")]
if (nchar(.Method[2])) attributes(e2) <- attributes(e2)[c("dim","dimnames")]
NextMethod(.Generic)
}
as.matrix.ratetable <- function(x, ...) {
attributes(x) <- attributes(x)[c("dim", "dimnames")]
x
} |
checkKey <- function(dfList) {
sapply(dfList, function(x) names(x)[1]=="KEY" & all(is.numeric(x[,1])))
} |
findintercorr_cont_cat <- function(method = c("Fleishman", "Polynomial"),
constants, rho_cont_cat, marginal,
support) {
Sigma_cont_cat <- matrix(1, nrow = nrow(rho_cont_cat),
ncol = ncol(rho_cont_cat))
for (i in 1:nrow(rho_cont_cat)) {
for (j in 1:ncol(rho_cont_cat)) {
Sigma_cont_cat[i, j] <-
(rho_cont_cat[i, j] *
sqrt(var_cat(marginal[[j]],
support[[j]])))/(denom_corr_cat(marginal[[j]],
support[[j]]) *
power_norm_corr(constants[i, ],
method))
}
}
return(Sigma_cont_cat)
} |
onsetissa<-function(kandi,h,delta,minim,
brnode,component,
index,
AtomlistAtom,AtomlistNext){
itis<-F
d<-length(minim)
node<-brnode
compo<-component[node]
ato<-compo
while ((ato>0) && !(itis)){
inde<-index[AtomlistAtom[ato]]
keski<-minim-h+delta*inde
for (din in 1:d){
if ((kandi[din]>=(keski[din]-delta[din]/2)) &&
(kandi[din]<=(keski[din]+delta[din]/2))){
itis<-T
}
}
ato<-AtomlistNext[ato]
}
return(itis)
} |
prepPDE <-
function(fn)
{
pdes = RSEIS::getPDEscreen(fn)
pdelist = RSEIS::PDE2list(pdes)
w1 = which(is.na(pdelist$sec))
zde = data.frame(pdelist)
zde = zde[-w1, ]
pdejsec = RSEIS::JtimL(zde)
ipde = as.list(zde)
ipde$jsec = pdejsec
any(is.na(pdejsec))
return(ipde)
} |
"algoComp" |
library(testthat)
library(text)
library(tibble)
library(dplyr)
context("Training Functions")
test_that("textTrain Regression produces list of results with prediction being numeric", {
skip_on_cran()
x = wordembeddings4[1]
y = Language_based_assessment_data_8[6]
trained_min_halving <- textTrainRegression(wordembeddings4[1],
Language_based_assessment_data_8[6],
cv_method = "cv_folds",
outside_folds = 2,
inside_folds = 2,
outside_strata_y = NULL,
inside_strata_y = NULL,
model = "regression",
eval_measure = "rmse",
penalty = c(1),
mixture = c(0),
preprocess_PCA = 1,
multi_cores = FALSE,
save_output = "only_results"
)
testthat::expect_that(trained_min_halving, is_a("list"))
testthat::expect_is(trained_min_halving$results$statistic[[1]], "numeric")
trained_logistic <- textTrainRegression(
x = wordembeddings4[1],
y = as.factor(Language_based_assessment_data_8$gender),
cv_method = "validation_split",
outside_folds = 2,
inside_folds = 3/4,
outside_strata_y = NULL,
inside_strata_y = NULL,
model = "logistic",
eval_measure = "bal_accuracy",
penalty = c(1),
mixture = c(0),
preprocess_PCA = "min_halving",
multi_cores = "multi_cores_sys_default",
save_output = "only_results"
)
testthat::expect_that(trained_logistic, is_a("list"))
testthat::expect_is(trained_logistic$results_metrics$.estimate[[1]], "numeric")
trained_logistic2 <- textTrainRegression(
x = wordembeddings4[1],
y = as.factor(Language_based_assessment_data_8$gender),
cv_method = "cv_folds",
outside_folds = 2,
inside_folds = 2,
outside_strata_y = NULL,
inside_strata_y = NULL,
model = "logistic",
eval_measure = "accuracy",
penalty = c(1),
mixture = c(0),
preprocess_PCA = 1,
multi_cores = "multi_cores_sys_default",
save_output = "only_results_predictions"
)
testthat::expect_that(trained_logistic2, is_a("list"))
testthat::expect_is(trained_logistic2$results_metrics$.estimate[[1]], "numeric")
trained_logistic_PCA1 <- textTrainRegression(wordembeddings4[1],
as.factor(Language_based_assessment_data_8$gender),
outside_folds = 2,
outside_strata_y = NULL,
inside_strata_y = NULL,
model = "logistic",
eval_measure = "precision",
penalty = c(1),
mixture = c(0),
preprocess_PCA = 1,
multi_cores = "multi_cores_sys_default",
save_output = "all"
)
testthat::expect_that(trained_logistic_PCA1, is_a("list"))
testthat::expect_is(trained_logistic_PCA1$results_metrics$.estimate[[1]], "numeric")
predict_list_form <- text::textPredict(trained_logistic_PCA1, wordembeddings4[1])
testthat::expect_is(predict_list_form$.pred_class[[1]], "factor")
trained_1 <- textTrain(wordembeddings4$harmonytext,
Language_based_assessment_data_8$hilstotal,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
penalty = c(1),
mixture = c(0),
preprocess_PCA = NA,
multi_cores = "multi_cores_sys_default",
force_train_method = "regression",
save_output = "only_results_predictions"
)
testthat::expect_that(trained_1, is_a("list"))
testthat::expect_is(trained_1$prediction$predictions[1], "numeric")
trained_NA <- textTrain(wordembeddings4$harmonytext,
Language_based_assessment_data_8$hilstotal,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
penalty = c(1),
mixture = c(0),
preprocess_PCA = NA,
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(trained_NA, is_a("list"))
testthat::expect_is(trained_NA$prediction$predictions[1], "numeric")
})
test_that("textTrain Random Forest produces list of results with prediction being categorical", {
skip_on_cran()
example_categories <- as.factor(c(
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2
))
trained1 <- textTrain(wordembeddings4$harmonytext,
example_categories,
cv_method = "validation_split",
outside_folds = 2,
inside_folds = 3/4,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
trees = c(1000),
preprocess_PCA = "min_halving",
multi_cores = "multi_cores_sys_default",
eval_measure = "f_measure",
force_train_method = "random_forest"
)
testthat::expect_that(trained1, testthat::is_a("list"))
testthat::expect_is(trained1$truth_predictions$truth[1], "factor")
trained2 <- textTrain(wordembeddings4$harmonytext,
example_categories,
outside_folds = 2,
inside_folds = 3/4,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
trees = c(1000),
preprocess_PCA = 2,
multi_cores = "multi_cores_sys_default",
eval_measure = "sens",
force_train_method = "random_forest"
)
testthat::expect_that(trained2, testthat::is_a("list"))
testthat::expect_is(trained2$truth_predictions$truth[1], "factor")
trained_NA <- textTrain(wordembeddings4$harmonytext,
example_categories,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
force_train_method = "random_forest",
mtry = c(1),
min_n = c(1),
trees = c(1000),
preprocess_PCA = NA,
multi_cores = "multi_cores_sys_default",
eval_measure = "spec"
)
testthat::expect_that(trained_NA, testthat::is_a("list"))
testthat::expect_is(trained_NA$truth_predictions$truth[1], "factor")
})
test_that("textTrainRandomForest with Extremely Randomized Trees produces list of results with prediction being categorical", {
skip_on_cran()
example_categories <- as.factor(c(
1, NA, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2
))
trained_rf_95 <- textTrainRandomForest(
x = wordembeddings4$harmonytext,
y = example_categories,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mode_rf = "classification",
mtry = c(1),
min_n = c(1),
trees = c(1000),
preprocess_PCA = c(0.95),
extremely_randomised_splitrule = NULL,
multi_cores = "multi_cores_sys_default",
eval_measure = "roc_auc",
save_output = "only_results",
event_level = "second"
)
testthat::expect_that(trained_rf_95, testthat::is_a("list"))
testthat::expect_is(trained_rf_95$results$.estimate[1], "numeric")
example_categories <- as.factor(c(
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
1, 2, 1, 2, 1, 2, 1, 2, 1, 2
))
trained_rf_3 <- textTrainRandomForest(wordembeddings4$harmonytext,
example_categories,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
trees = c(1000),
preprocess_PCA = c(3),
extremely_randomised_splitrule = "gini",
multi_cores = FALSE,
eval_measure = "kappa",
save_output = "only_results_predictions"
)
testthat::expect_that(trained_rf_3, testthat::is_a("list"))
testthat::expect_is(trained_rf_3$truth_predictions$truth[1], "factor")
example_categories_tibble <- tibble::as_tibble_col(example_categories)
trained_rf_NA <- textTrainRandomForest(wordembeddings4[1],
example_categories_tibble,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
trees = c(1000),
preprocess_PCA = NA,
extremely_randomised_splitrule = "gini",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(trained_rf_NA, testthat::is_a("list"))
testthat::expect_is(trained_rf_NA$truth_predictions$truth[1], "factor")
})
test_that("textTrainLists Regression produces a list of results with prediction being numeric", {
skip_on_cran()
results_or <- textTrainLists(wordembeddings4$harmonywords,
Language_based_assessment_data_8[5:6],
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = c(0.90),
penalty = c(2),
mixture = c(0),
force_train_method = "regression",
save_output = "only_results",
method_cor = "kendall",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_or, testthat::is_a("list"))
testthat::expect_is(results_or$results$tau_correlation[1], "character")
wordembeddings <- wordembeddings4[1]
ratings_data1 <- Language_based_assessment_data_8[5]
ratings_data2 <- Language_based_assessment_data_8[6]
factors1 <- tibble::as_tibble_col(as.factor(Language_based_assessment_data_8$gender))
ratings_data <- cbind(ratings_data1, ratings_data2, factors1)
results_or_p <- textTrainLists(wordembeddings,
ratings_data,
preprocess_PCA = c(0.90),
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
penalty = c(2),
mixture = c(0),
force_train_method = "automatic",
save_output = "only_results_predictions",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_or_p, testthat::is_a("list"))
testthat::expect_is(results_or_p$results$correlation[1], "character")
results_or_p <- textTrain(x = wordembeddings,
y = ratings_data,
preprocess_PCA = c(0.90),
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
penalty = c(2),
mixture = c(0),
force_train_method = "random_forest",
save_output = "only_results_predictions",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_or_p, testthat::is_a("list"))
testthat::expect_is(results_or_p$results$.estimate[1], "numeric")
factors1 <- as.factor(Language_based_assessment_data_8$gender)
factors2 <- as.factor(Language_based_assessment_data_8$gender)
rating1 <- Language_based_assessment_data_8$hilstotal
ratings_data_factors <- tibble::tibble(factors1, factors2, rating1)
results_list_logistic <- textTrainLists(wordembeddings4[1],
ratings_data_factors,
preprocess_PCA = c(0.90),
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
penalty = c(2),
mixture = c(0),
force_train_method = "automatic",
model = "logistic",
eval_measure = "default",
save_output = "only_results_predictions",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_or_p, testthat::is_a("list"))
testthat::expect_is(results_or_p$results$.estimate[1], "numeric")
results_list_logistic <- textTrain(wordembeddings,
ratings_data_factors,
preprocess_PCA = c(0.90),
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
penalty = c(2),
mixture = c(0),
force_train_method = "regression",
save_output = "only_results_predictions",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_or_p, testthat::is_a("list"))
testthat::expect_is(results_or_p$results$.estimate[1], "numeric")
})
test_that("textTrainLists randomForest produces list of results with prediction being numeric", {
skip_on_cran()
x <- wordembeddings4[1]
y1 <- factor(rep(c("young", "old", "young", "old", "young", "old", "young", "old", "young", "old"), 4))
y2 <- factor(rep(c("young", "old", "young", "old", "young", "old", "young", "old", "young", "old"), 4))
y <- tibble::tibble(y1, y2)
results_rf_et <- textTrain(x,
y,
force_train_method = "automatic",
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
preprocess_PCA = c(0.95),
trees = c(1000),
eval_measure = "accuracy",
extremely_randomised_splitrule = "extratrees",
save_output = "all",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_rf_et, testthat::is_a("list"))
testthat::expect_is(results_rf_et$results$p_value[1], "character")
results_rf <- textTrain(x,
y,
force_train_method = "automatic",
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
preprocess_PCA = NA,
trees = c(1000),
eval_measure = "kappa",
save_output = "all",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_rf, testthat::is_a("list"))
testthat::expect_is(results_rf$results$p_value[1], "character")
results_rf_or_p <- textTrain(x,
y,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
preprocess_PCA = c(0.95),
trees = c(1000),
eval_measure = "precision",
save_output = "only_results_predictions",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_rf_or_p, testthat::is_a("list"))
testthat::expect_is(results_rf_or_p$results$p_value[1], "character")
results_rf_or <- textTrain(x,
y,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
mtry = c(1),
min_n = c(1),
preprocess_PCA = c(0.95),
trees = c(1000),
eval_measure = "precision",
save_output = "only_results",
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(results_rf_or, testthat::is_a("list"))
testthat::expect_is(results_rf_or$results$p_value[1], "character")
})
test_that("textTrainRegression adding wordembeddings together", {
skip_on_cran()
multi_we_PCA_09 <- textTrainRegression(wordembeddings4[1:2],
Language_based_assessment_data_8$hilstotal,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = c(0.9),
penalty = 1,
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(multi_we_PCA_09, testthat::is_a("list"))
testthat::expect_is(multi_we_PCA_09$results[[1]][[1]], "numeric")
predictions_multi <- text::textPredict(multi_we_PCA_09, wordembeddings4[1:2])
testthat::expect_is(predictions_multi$.pred[[1]], "numeric")
multi_we_PCA_3 <- textTrainRegression(wordembeddings4[1:2],
Language_based_assessment_data_8$hilstotal,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = 3,
penalty = 1,
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(multi_we_PCA_3, testthat::is_a("list"))
testthat::expect_is(multi_we_PCA_3$results[[1]][[1]], "numeric")
multi_we_PCA_NA <- textTrainRegression(wordembeddings4[1:2],
Language_based_assessment_data_8$hilstotal,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = NA,
penalty = 1,
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(multi_we_PCA_NA, testthat::is_a("list"))
testthat::expect_is(multi_we_PCA_NA$results[[1]][[1]], "numeric")
})
test_that("textTrainRandomForest adding wordembeddings together", {
y <- as.factor(c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2))
multi_we_RF_PCA_09 <- textTrainRandomForest(wordembeddings4[1:2],
y,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = 0.9,
mtry = c(1),
min_n = c(1),
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(multi_we_RF_PCA_09, testthat::is_a("list"))
testthat::expect_is(multi_we_RF_PCA_09$results$.estimate[[1]], "numeric")
multi_we_RF_PCA_3 <- textTrainRandomForest(wordembeddings4[1:2],
y,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = 3,
mtry = c(1),
min_n = c(1),
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(multi_we_RF_PCA_3, testthat::is_a("list"))
testthat::expect_is(multi_we_RF_PCA_3$results$.estimate[[1]], "numeric")
multi_we_RF_PCA_NA <- textTrainRandomForest(wordembeddings4[1:2],
y,
outside_folds = 2,
inside_folds = 2/3,
outside_strata_y = NULL,
inside_strata_y = NULL,
preprocess_PCA = NA,
mtry = c(1),
min_n = c(1),
multi_cores = "multi_cores_sys_default"
)
testthat::expect_that(multi_we_RF_PCA_NA, testthat::is_a("list"))
testthat::expect_is(multi_we_RF_PCA_NA$results$.estimate[[1]], "numeric")
}) |
visNetMul <- function (g, data, height=7, margin=rep(0.1,4), border.color="
{
if(class(g)=="graphNEL"){
ig <- igraph.from.graphNEL(g)
}else{
ig <- g
}
if (class(ig) != "igraph"){
stop("The function must apply to either 'igraph' or 'graphNEL' object.\n")
}
if(is.null(V(ig)$name)){
V(ig)$name <- as.character(V(ig))
}
if(is.matrix(data) | is.data.frame(data) | is.vector(data)){
data <- as.matrix(data)
}else if(is.null(data)){
stop("The input data must be not NULL.\n")
}
if(is.null(rownames(data))) {
stop("The function must require the row names of the input data.\n")
}else if(any(is.na(rownames(data)))){
warning("Data with NA as row names will be removed")
data <- data[!is.na(rownames(data)),]
}
cnames <- colnames(data)
if(is.null(cnames)){
cnames <- seq(1,ncol(data))
}
ind <- match(rownames(data), V(ig)$name)
nodes_mapped <- V(ig)$name[ind[!is.na(ind)]]
if(length(nodes_mapped)!=vcount(ig)){
stop("The function must require that the row names of input data contain all those in the input graph.\n")
}
data <- as.matrix(data[nodes_mapped,])
vmin <- floor(stats::quantile(data, 0.05))
vmax <- ceiling(stats::quantile(data, 0.95))
if(vmin < 0 & vmax > 0){
vsym <- abs(min(vmin, vmax))
vmin <- -1*vsym
vmax <- vsym
}
if(!is.null(zlim)){
if(zlim[1] < floor(min(data)) | zlim[2] > ceiling(max(data))){
}
}else{
zlim <- c(vmin,vmax)
}
colNum <- ceiling(sqrt(length(cnames))) + 1
rowNum <- ceiling((length(cnames)+1)/colNum) + 1
tolNum <- colNum*rowNum
if(tolNum < length(cnames)+colNum+rowNum-1){
rowNum <- rowNum+1
}
layout_vec <- vector()
k <- 0
t <- 0
for(j in 1:rowNum){
for(i in 1:colNum){
t <- t+1
if(j == 1){
layout_vec[t] <- 0
}else{
if(i == colNum){
if(j == rowNum){
layout_vec[t] <- length(cnames)+1
}else{
layout_vec[t] <- 0
}
}else{
k <- k+1
if(k<=length(cnames)){
layout_vec[t] <- k
}else{
layout_vec[t] <- 0
}
}
}
}
}
layout_matrix <- matrix(layout_vec, rowNum, colNum, byrow=T)
frac <- colorbar.fraction
row_first <- frac*10/rowNum
row_rest <- (10-row_first)/(rowNum-1)
layout_heights <- c(row_first, rep(row_rest, rowNum-1))
col_last <- frac*10/colNum
col_rest <- (10-col_last)/(colNum-1)
layout_widths <- c(rep(col_rest, colNum-1), col_last)
if (newpage){
grDevices::dev.new(width=height*colNum/rowNum, height=height)
}
graphics::par(mfrow=c(rowNum,colNum), mar=margin)
graphics::layout(layout_matrix, widths=layout_widths, heights=layout_heights)
if(is.function(glayout)){
glayout_fix <- glayout(ig)
}else{
glayout_fix <- glayout
}
for(k in 1:length(cnames)){
visNet(ig, glayout=glayout_fix, pattern=data[,k], colormap=colormap, ncolors=ncolors, zlim=zlim, colorbar=F, newpage=F, ...)
graphics::mtext(sprintf("%s",cnames[k]), line=-1.5, side=mtext.side, adj=mtext.adj, cex=mtext.cex, font=mtext.font, col=mtext.col)
graphics::box("figure",col=border.color)
}
if(colorbar){
plot(c(0,1),c(0,1),xlab="", ylab="", axes=F, type="n")
palette.name <- visColormap(colormap=colormap)
colors <- palette.name(ncolors)
lab.scale <- length(colors)/(zlim[2]-zlim[1])
for (i in 1:length(colors)) {
yValue <- (i-1)/ncolors
hValue <- 1/ncolors
xValue <- 0.25
wValue <- 0.25
xleft <- xValue
ybottom <- yValue
xright <- xValue+wValue
ytop <- yValue+hValue
graphics::rect(xleft,ybottom,xright,ytop, col=colors[i], border="transparent")
if(i == 1 | i == 1+length(colors)/2){
tx <- (i-1)/lab.scale + zlim[1]
graphics::text(x=xright+0.1, y=ybottom, labels=tx, cex=1)
}else if(i==length(colors)){
tx <- i/lab.scale + zlim[1]
graphics::text(x=xright+0.2, y=ytop, labels=tx, cex=1)
}
}
}
invisible()
} |
est2SLSCoefCov <- function(d,
poly.mat = NULL,
cov.mat = NULL,
mean.vec = NULL,
acov = NULL,
acov.sat = NULL,
r = NULL){
coef.names <- lapply(d, function(eq) {
paste0(eq$DVlat, "~",if(eq$categorical) eq$IVlat else c("1",eq$IVlat))
})
not.cat <- unlist(lapply(d, function(eq){
rep(!eq$categorical, length(eq$coefficients))
}))
coefCov <- matrix(0, length(unlist(coef.names)),
length(unlist(coef.names)) )
rownames(coefCov) <- colnames(coefCov) <- unlist(coef.names)
if (!is.null(acov.sat)) {
acov.names <- colnames(acov.sat)
K <- buildDeltaK(d, cov.mat, mean.vec, acov.names)
coefCov <- K %*% acov.sat %*% t(K)
rownames(coefCov) <- colnames(coefCov) <- unlist(coef.names)[not.cat]
} else {
d <- lapply(d, function(eq) {
if (eq$categorical){
eq$sigma <- NA
K <- buildCategoricalK(eq, poly.mat)
eq$coefCov <- K %*% acov %*% t(K)
rownames(eq$coefCov) <- colnames(eq$coefCov) <- names(eq$coefficients)
} else {
eq$sigma <-
(cov.mat[eq$DVobs, eq$DVobs] +
(t(eq$coefficients[-1]) %*%
cov.mat[c(eq$IVobs), c(eq$IVobs)] %*%
eq$coefficients[-1]) -
(2 * cov.mat[eq$DVobs, c(eq$IVobs)] %*%
eq$coefficients[-1]))
if (!is.null(r$R)){
eq$coefCov <- NA
} else {
eq$coefCov <- solve(eq$XX1 %*% t(
solve(diag(rep(eq$sigma, length(eq$coefficients))))))
rownames(eq$coefCov) <- colnames(eq$coefCov) <-
paste0(eq$DVlat, "~", c("1",eq$IVlat))
}
}
eq
})
if (is.null(r$R)){
coefCov <- lavaan::lav_matrix_bdiag(lapply(d,"[[","coefCov"))
rownames(coefCov) <- colnames(coefCov) <- unlist(coef.names)
} else {
SIG <- diag(unlist(lapply(d,function(eq){
if (!eq$categorical) rep(eq$sigma,length(eq$coefficients))}))
)
XX1 <- lavaan::lav_matrix_bdiag(lapply(d, function (eq){
if (!eq$categorical) eq$XX1 else matrix(0,0,0)
}))
R0 <- matrix(0, nrow(r$R), nrow(r$R))
R1 <- r$R[,not.cat,drop=FALSE]
coefCovR <- solve(
rbind(cbind(XX1 %*% t(solve(SIG)), t(R1)),cbind(R1,R0))
)[1:nrow(XX1), 1:nrow(XX1)]
colnames(coefCovR) <- rownames(coefCovR) <-
unlist(coef.names)[not.cat]
coefCov[rownames(coefCovR), colnames(coefCovR)] <- coefCovR
for (i in 1:length(d)){
if (d[[i]]$categorical) {
coefCov[ rownames(d[[i]]$coefCov),
colnames(d[[i]]$coefCov) ] <- d[[i]]$coefCov
}
}
}
}
return(coefCov)
} |
knitr::opts_chunk$set(echo=TRUE, collapse=T, comment='
library(MetAlyzer)
library(ggplot2)
library(dplyr)
fpath <- system.file("extdata", "example_data.xlsx", package = "MetAlyzer")
mpath <- system.file("extdata", "example_meta_data.rds", package = "MetAlyzer")
obj <- MetAlyzerDataset(file_path = fpath)
show(obj)
head(metaData(obj))
head(quantStatus(obj), c(5, 5))
obj <- filterMetabolites(obj, class_name = "Metabolism Indicators")
obj <- filterMetaData(obj, column = Group, keep = c(1:6))
summariseQuantData(obj)
meta_df <- readRDS(mpath)
head(meta_df)
obj <- updateMetaData(obj, name = Replicate, new_colum = meta_df$Replicate)
show(obj)
obj <- renameMetaData(obj, Method = Group)
head(metaData(obj))
obj <- createPlottingData(obj, Method, Tissue, ungrouped = Replicate)
gg_df <- plottingData(obj)
head(gg_df)
glu_gg_df <- filter(gg_df, Metabolite == "Glu")
ggplot(glu_gg_df, aes(Method, Concentration, color = Status)) +
geom_point() +
scale_color_manual(values = c("Valid" = "
"LOQ" = "
"LOD" = "
ylab("Concentration [pmol/mg Tissue]") +
facet_grid(~ Tissue)
length(which(gg_df$Concentration == 0))
obj <- imputePlottingData(obj, Tissue, Metabolite)
imp_gg_df <- plottingData(obj)
min(imp_gg_df$imp_Conc, na.rm = TRUE)
obj <- transformPlottingData(obj)
trans_gg_df <- plottingData(obj)
head(trans_gg_df)
trans_glu_gg_df <- filter(trans_gg_df, Metabolite == "Glu")
ggplot(trans_glu_gg_df, aes(Method, transf_Conc, color = Status)) +
geom_point() +
scale_color_manual(values = c("Valid" = "
"LOQ" = "
"LOD" = "
facet_grid(~ Tissue)
obj <- performANOVA(obj, categorical = Method)
anv_gg_df <- plottingData(obj)
head(data.frame(anv_gg_df))
anv_gg_df$optimal <- sapply(anv_gg_df$ANOVA_group, function(g) grepl("A", g))
obj <- setPlottingData(obj, anv_gg_df)
head(data.frame(anv_gg_df)) |
library(knitr)
opts_chunk$set(cache = FALSE, tidy = FALSE, fig.align = "center")
library(biogas)
options(width=65)
data("sludgeTwoBiogas")
dim(sludgeTwoBiogas)
head(sludgeTwoBiogas)
summary(sludgeTwoBiogas)
data("sludgeTwoSetup")
dim(sludgeTwoSetup)
head(sludgeTwoSetup)
summary(sludgeTwoSetup)
cum.prod.lc <- calcBgMan(sludgeTwoBiogas, temp = 30,
time.name = "time.d", comp.name = "xCH4n",
temp.init = 30, pres.init = 0.0,
pres.resid = 0,
headspace = sludgeTwoSetup,
pres.amb = 1013, absolute = FALSE,
unit.pres = "mbar")
head(cum.prod.lc)
dim(cum.prod.lc)
library(ggplot2)
ggplot(cum.prod.lc, aes(time.d, cvCH4, colour = factor(id))) +
geom_point() +
geom_line(aes(group = id)) +
labs(x = "Time [d]", y = "cvCH4 [mL]", colour = "Bottle id") +
theme_bw()
data("strawPressure")
dim(strawPressure)
head(strawPressure)
summary(strawPressure)
data("strawComp")
dim(strawComp)
head(strawComp)
summary(strawComp)
data("strawSetup")
dim(strawSetup)
head(strawSetup)
summary(strawSetup)
cum.prod.l <- calcBgMan(strawPressure, comp = strawComp, temp = 31,
data.struct = "long",
time.name = "time", id.name = "bottle", comp.name = "xCH4",
temp.init = 21.55, pres.resid = "pres.resid",
pres.init = 0.0,
headspace = strawSetup, vol.hs.name = "headspace",
pres.amb = 101.3, absolute = FALSE,
extrap = TRUE,
unit.pres = "kPa")
head(cum.prod.l)
ggplot(cum.prod.l, aes(time, cvCH4, colour = factor(bottle))) +
geom_point() +
geom_line(aes(group = bottle)) +
labs(x = "Time [d]", y = "cvCH4 [mL]", colour = "Bottle id") +
theme_bw() |
context("inequalityConstraint")
test_that("check optimNLOPTR interface (no constraint)", {
res <- optimNLOPTR(,fun = funSphere,lower = c(-10,-20),upper=c(20,8))
expect_equal(length(res$xbest),2)
res
})
test_that("check optimNLOPTR + inequality constraint", {
contr <- list()
contr$eval_g_ineq <- function(x) 1+x[1]-x[2]
res <- optimNLOPTR(,fun = funSphere,lower = c(-10,-20),upper=c(20,8),control=contr)
expect_equal(length(res$xbest),2)
res
contr$opts$algorithm <- "NLOPT_GN_ISRES"
res <- optimNLOPTR(,fun = funSphere,lower = c(-10,-20),upper=c(20,8),control=contr)
expect_equal(length(res$xbest),2)
res
})
test_that("check SPOT+NLOPTR with inequality constraints but with default design", {
contr <- list()
contr$eval_g_ineq <- function(x) 1+x[1]-x[2]
contr$funEvals <- 100
contr$opts$algorithm <- "NLOPT_GN_ISRES"
res <- spot(,fun = funSphere,lower = c(-10,-20),upper=c(20,8),
control=list(
funEvals=15,
modelControl=list(target="ei"),
optimizer=optimNLOPTR,
optimizerControl=contr
)
)
res$xbest
res$ybest
expect_true(!all(apply(res$x,1,contr$eval_g_ineq) <=0))
})
test_that("check SPOT+NLOPTR with inequality constraints also in design", {
contr <- list()
contr$eval_g_ineq <- function(x) 1+x[1]-x[2]
contr$funEvals <- 100
contr$opts$algorithm <- "NLOPT_GN_ISRES"
res <- spot(,fun = funSphere,lower = c(-10,-20),upper=c(20,8),
control=list(
funEvals=15,
modelControl=list(target="ei"),
optimizer=optimNLOPTR,
optimizerControl=contr,
designControl=list(inequalityConstraint=contr$eval_g_ineq)
)
)
res$xbest
res$ybest
expect_true(all(apply(res$x,1,contr$eval_g_ineq) <=0))
}) |
.radial.plot<-function(lengths,radial.pos=NULL,labels=NA,label.pos=NULL,
radlab=FALSE,start=0,clockwise=FALSE,rp.type="r",label.prop=1.1,main="",
xlab="",ylab="",line.col=par("fg"),lty=par("lty"),lwd=par("lwd"),
mar=c(2,2,3,2),show.grid=TRUE,show.grid.labels=4,show.radial.grid=TRUE,
rad.col="gray",grid.col="gray",grid.bg="transparent",grid.left=FALSE,
grid.unit=NULL,point.symbols=1,point.col=par("fg"),show.centroid=FALSE,
radial.lim=NULL,radial.labels=NULL,boxed.radial=FALSE,poly.col=NA,
add=FALSE,...) {
if(is.null(radial.lim)) radial.lim<-range(lengths)
length.dim<-dim(lengths)
if(is.null(length.dim)) {
npoints<-length(lengths)
nsets<-1
lengths<-matrix(lengths,nrow=1)
}
else {
npoints<-length.dim[2]
nsets<-length.dim[1]
lengths<-as.matrix(lengths)
}
lengths<-lengths-radial.lim[1]
lengths[lengths<0]<-NA
if(is.null(radial.pos))
radial.pos<-seq(0,pi*(2 - 2 * (rp.type != "l")/npoints),length.out=npoints)
radial.pos.dim<-dim(radial.pos)
if(is.null(radial.pos.dim))
radial.pos<-matrix(rep(radial.pos,nsets),nrow=nsets,byrow=TRUE)
else radial.pos<-as.matrix(radial.pos)
if(rp.type == "l" && clockwise == TRUE) start<-pi/2
if(clockwise) radial.pos<--radial.pos
if(start) radial.pos<-radial.pos+start
if(show.grid) {
if(length(radial.lim) < 3) grid.pos<-pretty(radial.lim)
else grid.pos<-radial.lim
if(grid.pos[1] < radial.lim[1]) grid.pos<-grid.pos[-1]
maxlength<-max(grid.pos-radial.lim[1])
angles<-seq(0,1.96*pi,by=0.04*pi)
}
else {
grid.pos<-NA
maxlength<-diff(radial.lim)
}
oldpar<-par("xpd","mar","pty")
if(!add) {
par(mar=mar,pty="s")
plot(c(-maxlength,maxlength),c(-maxlength,maxlength),type="n",axes=FALSE,
main=main,xlab=xlab,ylab=ylab)
if(is.null(label.pos)) {
if(is.null(labels)) nlpos<-ifelse(npoints > 8,8,npoints)
else {
if(is.na(labels[1])) nlpos<-ifelse(npoints > 8,8,npoints)
else nlpos<-length(labels)
}
label.pos<-seq(0,pi*(2-2/nlpos),length.out=nlpos)
}
if(show.grid) {
.radial.grid(labels=labels,label.pos=label.pos,radlab=radlab,
radial.lim=radial.lim,start=start,clockwise=clockwise,
label.prop=label.prop,grid.pos=grid.pos,rad.col=rad.col,
grid.col=grid.col,grid.bg=grid.bg,
show.radial.grid=show.radial.grid)
}
}
par(xpd=TRUE)
if(length(line.col) < nsets) line.col<-1:nsets
if(length(rp.type) < nsets) rp.type<-rep(rp.type,length.out=nsets)
if(length(point.symbols) < nsets)
point.symbols<-rep(point.symbols,length.out=nsets)
if(length(point.col) < nsets) point.col<-rep(point.col,length.out=nsets)
if(length(poly.col) < nsets) poly.col<-rep(poly.col,length.out=nsets)
if(length(lty) < nsets) lty<-rep(lty,length.out=nsets)
if(length(lwd) < nsets) lwd<-rep(lwd,length.out=nsets)
for(i in 1:nsets) {
if(nsets > 1) {
linecol<-line.col[i]
polycol<-poly.col[i]
pointcol<-point.col[i]
pointsymbols<-point.symbols[i]
ltype<-lty[i]
lwidth<-lwd[i]
}
else {
linecol<-line.col
polycol<-poly.col
pointcol<-point.col
pointsymbols<-point.symbols
ltype<-lty
lwidth<-lwd
}
rptype<-unlist(strsplit(rp.type[i],""))
if(match("s",rptype,0)) {
if(is.null(pointsymbols)) pointsymbols<-i
if(is.null(pointcol)) pointcol<-i
}
xpos<-cos(radial.pos[i,])*lengths[i,]
ypos<-sin(radial.pos[i,])*lengths[i,]
if(match("r",rptype,0))
segments(0,0,xpos,ypos,col=linecol,lty=ltype,lwd=lwidth,...)
if(match("p",rptype,0))
polygon(xpos,ypos,border=linecol,col=polycol,lty=ltype,
lwd=lwidth,...)
if(match("s",rptype,0))
points(xpos,ypos,pch=pointsymbols,col=pointcol,...)
if(match("l",rptype,0))
lines(xpos,ypos,lty=ltype,lwd=lwidth,col=linecol,...)
if(show.centroid) {
if(match("p",rptype,0)) {
nvertices<-length(xpos)
polygonarea<-xpos[nvertices]*ypos[1] - xpos[1]*ypos[nvertices]
for(vertex in 1:(nvertices-1))
polygonarea<-
polygonarea+xpos[vertex]*ypos[vertex+1]-xpos[vertex+1]*ypos[vertex]
polygonarea<-polygonarea/2
centroidx<-
(xpos[nvertices]+xpos[1])*(xpos[nvertices]*ypos[1]-xpos[1]*ypos[nvertices])
centroidy<-
(ypos[nvertices]+ypos[1])*(xpos[nvertices]*ypos[1]-xpos[1]*ypos[nvertices])
for(vertex in 1:(nvertices-1)) {
centroidx<-centroidx + (xpos[vertex]+xpos[vertex+1])*
(xpos[vertex]*ypos[vertex+1]-xpos[vertex+1]*ypos[vertex])
centroidy<-centroidy + (ypos[vertex]+ypos[vertex+1])*
(xpos[vertex]*ypos[vertex+1]-xpos[vertex+1]*ypos[vertex])
}
points(centroidx/(6*polygonarea),centroidy/(6*polygonarea),
col=point.col[i],pch=point.symbols[i],cex=2,...)
}
else
points(mean(xpos),mean(ypos),col=pointcol,pch=pointsymbols,
cex=2,...)
}
}
if(show.grid.labels && !add) {
if(show.grid.labels%%2) {
ypos<-grid.pos-radial.lim[1]
xpos<-rep(0,length(grid.pos))
if(show.grid.labels==1) ypos<--ypos
}
else {
xpos<-grid.pos-radial.lim[1]
ypos<-rep(0,length(grid.pos))
if(show.grid.labels==2) xpos<--xpos
}
if(is.null(radial.labels)) radial.labels<-grid.pos
if(!is.null(grid.unit))
radial.labels[length(grid.pos)]<-
paste(radial.labels[length(grid.pos)],grid.unit)
if(boxed.radial)
.boxed.labels(xpos,ypos,radial.labels,border=FALSE,
cex=par("cex.lab"))
else text(xpos,ypos,radial.labels,cex=par("cex.lab"))
}
invisible(oldpar)
}
.radial.grid<-function(labels=NA,label.pos=NULL,radlab=FALSE,radial.lim=NULL,
start=0,clockwise=FALSE,label.prop=1.1,grid.pos,rad.col="gray",
grid.col="gray",grid.bg="transparent",show.radial.grid=TRUE,
start.plot=FALSE) {
if(start.plot) {
radial.span<-diff(radial.lim)
plot(0,type="n",xlim=c(-radial.span,radial.span),
ylim=c(-radial.span,radial.span),xlab="",ylab="",axes=FALSE)
}
par(xpd=TRUE)
if(is.null(label.pos)) label.pos<-seq(0,1.8*pi,length=9)
if(!is.null(labels)) {
if(is.na(labels[1])) labels<-as.character(round(label.pos,2))
}
if(clockwise) label.pos<--label.pos
if(start) label.pos<-label.pos+start
angles<-seq(0,1.96*pi,by=0.04* pi)
for(i in seq(length(grid.pos),1,by=-1)) {
xpos<-cos(angles)*(grid.pos[i]-radial.lim[1])
ypos<-sin(angles)*(grid.pos[i]-radial.lim[1])
polygon(xpos,ypos,border=grid.col,col=grid.bg)
}
maxlength<-max(grid.pos)-radial.lim[1]
if(show.radial.grid) {
xpos<-cos(label.pos)*maxlength
ypos<-sin(label.pos)*maxlength
segments(0,0,xpos,ypos,col=rad.col)
xpos<-cos(label.pos)*maxlength
ypos<-sin(label.pos)*maxlength
}
if(!is.null(labels)) {
xpos<-cos(label.pos)*maxlength*label.prop
ypos<-sin(label.pos)*maxlength*label.prop
if(radlab) {
for(label in 1:length(labels)) {
labelsrt<-(180*label.pos[label]/pi)+180*
(label.pos[label] > pi/2 && label.pos[label] < 3*pi/2)
text(xpos[label],ypos[label],labels[label],
cex=par("cex.axis"),srt=labelsrt)
}
}
else
.boxed.labels(x = xpos, y = ypos,labels,ypad=0.7,border=FALSE,cex=par("cex.axis"))
}
par(xpd = FALSE)
}
.boxed.labels<-function (x, y = NA, labels,
bg = ifelse(match(par("bg"), "transparent", 0), "white", par("bg")),
border = TRUE, xpad = 1.2, ypad = 1.2,
srt = 0, cex = 1, adj = 0.5, xlog=FALSE, ylog=FALSE, ...) {
oldpars <- par(c("cex", "xpd"))
par(cex = cex, xpd = TRUE)
box.adj <- adj + (xpad - 1) * cex * (0.5 - adj)
if (srt == 90 || srt == 270) {
bheights <- strwidth(labels)
theights <- bheights * (1 - box.adj)
bheights <- bheights * box.adj
lwidths <- rwidths <- strheight(labels) * 0.5
}
else {
lwidths <- strwidth(labels)
rwidths <- lwidths * (1 - box.adj)
lwidths <- lwidths * box.adj
bheights <- theights <- strheight(labels) * 0.5
}
args <- list(x = x, y = y, labels = labels, srt = srt, adj = adj,
col = ifelse(colSums(col2rgb(bg) * c(1, 1.4, 0.6)) <
350, "white", "black"))
args <- modifyList(args, list(...))
if(xlog){
xpad<-xpad*2
xr<-exp(log(x) - lwidths * xpad)
xl<-exp(log(x) + lwidths * xpad)
}
else{
xr<-x - lwidths * xpad
xl<-x + lwidths * xpad
}
if(ylog){
ypad<-ypad*2
yb<-exp(log(y) - bheights * ypad)
yt<-exp(log(y) + theights * ypad)
}
else{
yb<-y - bheights * ypad
yt<-y + theights * ypad
}
rect(xr, yb, xl, yt, col = bg, border = border)
do.call(text, args)
par(cex = oldpars)
} |
library(BatchExperiments)
library(parallelMap)
library(mlrMBO)
library(eaf)
library(stringr)
library(checkmate)
plotEAF = function(opt.paths, xlim = NULL, ylim = NULL, ...) {
args = list(...)
requirePackages("eaf", why = "plotEAF")
assertList(opt.paths, min.len = 1L, types = "list", names = "unique")
algos = names(opt.paths)
y.names = NULL; minimize = NULL
data = data.frame()
for (i in seq_along(algos)) {
a = algos[i]
runs = opt.paths[[i]]
assertList(runs, types = "OptPath", min.len = 1L)
fronts = lapply(seq_along(runs), function(j) {
run = runs[[j]]
f = as.data.frame(getOptPathParetoFront(run))
cns = colnames(f)
if (length(cns) != 2L)
stop("Must always have 2 objectives in opt path. But found: %i", length(cns))
if (i == 1L && j == 1L) {
y.names <<- cns
minimize <<- run$minimize
}
if (!all(y.names == cns))
stop("Must always have the same 2 objectives in opt path: %s (first ones taken). But found here: %s",
collapse(y.names), collapse(cns))
if (!all(minimize == run$minimize))
stop("Must always have the same 'minimize' settings for objectives in opt path: %s (first one taken). But found here: %s",
collapse(minimize), collapse(run$minimize))
cbind(f, .algo = a, .repl = j)
})
fronts = do.call(rbind, fronts)
data = rbind(data, fronts)
}
yn1 = y.names[1L]; yn2 = y.names[2L]
f = as.formula(sprintf("%s + %s ~ .repl", yn1, yn2))
defaults = list(
xlab = yn1, ylab = yn2,
percentiles = 50
)
args = insert(defaults, args)
args$x = f
args$data = data
args$groups = quote(.algo)
args$maximise = !minimize
args$xlim = xlim
args$ylim = ylim
args$col = c("darkgrey", "darkgrey", "darkgrey", "black", "black", "black")
args$lty = c("solid", "dashed", "dotdash", "solid", "dashed", "dotdash")
do.call(eafplot, args)
return(data)
}
reg = loadRegistry("mco_bench-files", work.dir = ".")
job.info = getJobInfo(reg, pars = TRUE)
job.info$algo2 = paste(job.info$algo, job.info$budget, job.info$prop.points,
job.info$indicator, job.info$crit, sep = "-")
job.info$algo2 = str_replace_all(job.info$algo2, "-NA", "")
pids = c("GOMOP3_3D2M", "GOMOP_2D2M", "GOMOP_5D2M", "dtlz2_5D2M", "zdt1_5D2M", "zdt2_5D2M", "zdt3_5D2M")
aids.base = c("nsga2-ref", "nsga2-normal", "randomSearch-normal")
aids1 = c(aids.base, "dib-1-sms", "dib-1-eps")
aids2 = c(aids.base, "dib-4-sms", "dib-4-eps")
aids3 = c(aids.base, "parego-1-ei", "parego-1-cb")
aids4 = c(aids.base, "parego-4-ei", "parego-4-cb")
aids5 = c(aids.base, "mspot-1-mean", "mspot-1-cb", "mspot-1-ei")
aids6 = c(aids.base, "mspot-4-mean", "mspot-4-cb", "mspot-4-ei")
aids7 = c(aids.base, "dib-1-sms", "parego-4-cb", "mspot-4-ei")
getOptPaths = function(job.info, pids, aids) {
ops = list()
for (pid in pids) {
for (aid in aids) {
jids = job.info[job.info$prob == pid & job.info$algo2 == aid, "id"]
assertInteger(jids, len = 20L, any.missing = FALSE)
ops[[pid]][[aid]] = extractSubList(loadResults(reg, jids), "opt.path", simplify = FALSE)
}
names(ops[[pid]]) = paste(seq_along(aids), aids)
}
return(ops)
}
plotMMBOEAF = function(prob.id, opt.paths, file = NULL, logscale = FALSE,
title = prob.id, xlim = NULL, ylim = NULL, ...) {
if (!logscale) {
log = ""; legend.pos = "topright"
} else {
log = "xy"; legend.pos = "bottomleft"
}
if (!is.null(file)) pdf(file)
d = plotEAF(opt.paths[[prob.id]], legend.pos = "topright", log = log, main = title,
xlab = "y1", ylab = "y2", xlim = xlim, ylim = ylim, ...)
if (!is.null(file)) dev.off()
return(d)
}
xlims = list(c(-3.965, -3.6), c(0, 30), c(-3.5, 0), c(0, 1.25), c(0, 1), c(0, 1), c(0, 1))
ylims = list(c(1, 1e4), c(0, 1), c(30, 100), c(0, 1.25), c(0, 2), c(0, 2), c(-1, 4))
pdf("eafs.pdf")
for(j in 1:7) {
pid = pids[j]
for (i in 1:7) {
aids = get(paste("aids", i, sep = ""))
plotMMBOEAF(pid, getOptPaths(job.info, pid, aids), xlim = xlims[[j]], ylim = ylims[[j]])
}
}
dev.off() |
library(LearnBayes)
data(cancermortality)
fit=laplace(betabinexch,c(-7,6),cancermortality)
betabinexch.cond=function (log.K, data)
{
eta = exp(-6.818793)/(1 + exp(-6.818793))
K = exp(log.K)
y = data[, 1]; n = data[, 2]; N = length(y)
logf=0*log.K
for (j in 1:length(y))
logf = logf + lbeta(K * eta + y[j], K * (1 -
eta) + n[j] - y[j]) - lbeta(K * eta, K * (1 - eta))
val = logf + log.K - 2 * log(1 + K)
return(exp(val-max(val)))
}
I=integrate(betabinexch.cond,2,16,cancermortality)
par(mfrow=c(2,2))
curve(betabinexch.cond(x,cancermortality)/I$value,from=3,to=16,
ylab="Density", xlab="log K",lwd=3, main="Densities")
curve(dnorm(x,8,2),add=TRUE)
legend("topright",legend=c("Exact","Normal"),lwd=c(3,1))
curve(betabinexch.cond(x,cancermortality)/I$value/
dnorm(x,8,2),from=3,to=16, ylab="Weight",xlab="log K",
main="Weight = g/p")
curve(betabinexch.cond(x,cancermortality)/I$value,from=3,to=16,
ylab="Density", xlab="log K",lwd=3, main="Densities")
curve(1/2*dt(x-8,df=2),add=TRUE)
legend("topright",legend=c("Exact","T(2)"),lwd=c(3,1))
curve(betabinexch.cond(x,cancermortality)/I$value/
(1/2*dt(x-8,df=2)),from=3,to=16, ylab="Weight",xlab="log K",
main="Weight = g/p")
tpar=list(m=fit$mode,var=2*fit$var,df=4)
myfunc=function(theta)
return(theta[2])
s=impsampling(betabinexch,tpar,myfunc,10000,cancermortality)
cbind(s$est,s$se) |
computeLogLikInd <-
function (cluster.par, gene.data, n.time, n.rep)
{
cluster.mean = cluster.par[1:n.time]
sdWICluster = cluster.par[n.time+1]
sdTSampling = cluster.par[n.time+2]
sdResidual = cluster.par[n.time+3]
mean.vec = rep (cluster.mean, times=n.rep)
Smatrix = matrix (1, nrow=n.time, ncol=n.time)
Imatrix = matrix (0, nrow=n.time, ncol=n.time)
diag (Imatrix) = 1
diagonal.block = sdWICluster^2 * Smatrix + (sdTSampling^2 + sdResidual^2) * Imatrix
offdiagonal.block = sdWICluster^2 * Smatrix + sdTSampling^2 * Imatrix
cov.matrix = matrix (0, nrow=n.time*n.rep, ncol=n.time*n.rep)
for (r in 1:n.rep)
{
cov.matrix[(n.time * (r-1) + 1:n.time), (n.time * (r-1) + 1:n.time)] = diagonal.block
}
for (r1 in 1:(n.rep-1))
{
for (r2 in (r1+1):n.rep)
{
cov.matrix[(n.time * (r1-1) + 1:n.time), (n.time * (r2-1) + 1:n.time)] = offdiagonal.block
cov.matrix[(n.time * (r2-1) + 1:n.time), (n.time * (r1-1) + 1:n.time)] = offdiagonal.block
}
}
loglik = dMVNorm (gene.data, mean=mean.vec, sigma=cov.matrix, log=TRUE)
return (loglik)
} |
source("ESEUR_config.r")
pal_col=rainbow(4)
posix_dr=read.csv(paste0(ESEUR_dir, "reliability/Austin-group-Jul-17.csv.xz"), as.is=TRUE)
posix_dr$Date.Submitted=as.Date(posix_dr$Date.Submitted)
posix_dr$Updated=as.Date(posix_dr$Updated)
clarif=subset(posix_dr, Type == "Clarification Requested")
enhance=subset(posix_dr, Type == "Enhancement Request")
error=subset(posix_dr, Type == "Error")
omission=subset(posix_dr, Type == "Omission")
plot(sort(error$Date.Submitted), 1:nrow(error), type="l", col=pal_col[1],
xaxs="i", yaxs="i",
xlab="Date", ylab="Reported problems\n")
lines(sort(clarif$Date.Submitted), 1:nrow(clarif), col=pal_col[2])
lines(sort(enhance$Date.Submitted), 1:nrow(enhance), col=pal_col[3])
lines(sort(omission$Date.Submitted), 1:nrow(omission), col=pal_col[4])
legend(x="topleft", legend=c("Error", "Clarification Requested",
"Enhancement Request", "Omission"), bty="n", fill=pal_col, cex=1.2) |
Dpens2 <- function(params, type = "lasso", lambda = 1, w.alasso = NULL, gamma = 1, a = 3.7, eps = 1e-10){
if(type == "lasso"){
f1 <- function(x) sqrt(x^2 + eps)
f2 <- function(x) x/sqrt(x^2 + eps)
f3 <- function(x) 0.5 * (2 * (x^2 + eps)^-0.5 - 2 * x * ((x^2 + eps)^-(0.5 + 1) * (0.5 * (2 * x))))
S2 <- lambda*f1(params)
S1 <- lambda*f2(params)
S <- lambda*f3(params)
}
L <- list(S = S, S1 = S1, S2 = S2)
L
} |
X2RSEIS<-function(nh, g)
{
kix = legitpix(g$sel, g$zloc, g$zenclick)
ypick = kix$ypick
ppick = kix$ppick
if(length(ppick)>0)
{
ipick = g$sel[ypick]
ipick = ipick[length(ipick)]
if(g$zenclick>2)
{
pickwin = range( c(g$zloc$x[(g$zenclick-1)], g$zloc$x[(g$zenclick-2)]))
}
else
{
pickwin = g$WIN
}
GH = WINGH(nh, WIN = pickwin )
pstamp = Zdate(GH$info)
outfile = pstamp[1]
cat(paste("Creating RSEIS GH file:", outfile ), sep="\n")
save(file=paste(outfile, "GH.RDATA", sep="."), GH)
g$zloc = list(x=NULL, y=NULL)
g$action="donothing"
invisible(list(RETX =NULL , global.vars=g))
}
else
{
cat("X_R WARNING: no window or trace has been selected:", sep="\n")
RETX=NULL
g$zloc = list(x=NULL, y=NULL)
g$action="donothing"
invisible(list(global.vars=g))
}
} |
rdd_coef <- function(object, allInfo = FALSE, allCo = FALSE, ...) UseMethod("rdd_coef")
rdd_coef.default <- function(object, allInfo = FALSE, allCo = FALSE, ...) {
res <- coef(summary(object))
if (!allCo)
res <- res["D", , drop = FALSE]
if (!allInfo)
res <- res[, "Estimate"]
res
}
rdd_coef.rdd_reg_np <- function(object, allInfo = FALSE, allCo = FALSE, ...) {
res <- object$coefMat
if (!allCo)
res <- res["D", , drop = FALSE]
if (!allInfo)
res <- res[, "Estimate"]
res
}
|
library(magrittr)
library(dplyr)
n_samples <- 6
test_that("We can read all sections of the MultiQC example WGS file", {
report <- load_multiqc(
system.file("extdata", "wgs/multiqc_data.json", package = "TidyMultiqc"),
sections = c("plot", "general", "raw"),
plots = "fastqc_per_sequence_quality_scores_plot"
)
expect_equal(
report$metadata.sample_id %>% unique() %>% length(),
report$metadata.sample_id %>% length()
)
expect_equal(nrow(report), n_samples)
expect_true(ncol(report) > 100)
expect_type(report$plot.fastqc_per_sequence_quality_scores_plot, "list")
report$plot.fastqc_per_sequence_quality_scores_plot %>% purrr::map(function(df) {
expect_equal(ncol(df), 2)
})
expect_true(colnames(report[, 1]) %>% stringr::str_starts("metadata"))
expect_true(report %>% dplyr::select(last_col()) %>% colnames() %>% stringr::str_starts("raw"))
})
test_that("We can parse the general stats section", {
report <- load_multiqc(
system.file("extdata", "wgs/multiqc_data.json", package = "TidyMultiqc"),
sections = "general"
)
expect_equal(nrow(report), n_samples)
expect_true(ncol(report) > 100)
expect_true(all(
c(
"general.avg_gc",
"general.high",
"general.3_prime_utr_variant",
"general.sequence_feature",
"general.intergenic",
"general.insertions",
"general.percent_gc"
) %in% colnames(report)
))
})
test_that("We can parse the qualimap coverage histogram", {
report <- load_multiqc(
system.file("extdata", "wgs/multiqc_data.json", package = "TidyMultiqc"),
sections = "plot",
plots = "qualimap_coverage_histogram"
)
expect_true("plot.qualimap_coverage_histogram" %in% colnames(report))
expect_equal(
report %>%
filter(metadata.sample_id == "P4107_1001") %>%
pull(plot.qualimap_coverage_histogram) %>%
purrr::flatten_df() %>%
{
HistDat::HistDat(vals = .$x, counts = .$y)
} %>%
HistDat::median(),
35,
tolerance = 1
)
expect_equal(nrow(report), n_samples)
expect_equal(ncol(dplyr::select(report, where(is.list))), 1)
})
test_that("We can parse the qualimap cumulative coverage histogram", {
report <- load_multiqc(
system.file("extdata", "wgs/multiqc_data.json", package = "TidyMultiqc"),
sections = "plot",
plots = "qualimap_genome_fraction"
)
expect_true("plot.qualimap_genome_fraction" %in% colnames(report))
expect_equal(
report %>%
filter(metadata.sample_id == "P4107_1001") %>%
pull("plot.qualimap_genome_fraction") %>%
purrr::flatten_df() %>%
dplyr::filter(x == 30) %>%
dplyr::pull(y),
74.66,
tolerance = 0.01
)
expect_equal(nrow(report), n_samples)
expect_equal(ncol(dplyr::select(report, where(is.list))), 1)
})
test_that("We can parse the snpeff bar chart", {
report <- load_multiqc(
system.file("extdata", "wgs/multiqc_data.json", package = "TidyMultiqc"),
sections = "plot",
plots = "snpeff_variant_effects_region"
)
expect_equal(nrow(report), n_samples)
expect_equal(ncol(report), 2)
expect_true("plot.snpeff_variant_effects_region" %in% colnames(report))
report <- tidyr::unnest(report, cols = plot.snpeff_variant_effects_region, names_sep = ".")
expect_equal(ncol(dplyr::select(report, where(is.numeric))), 13)
expect_true(all(c(
"plot.snpeff_variant_effects_region.exon",
"plot.snpeff_variant_effects_region.utr_3_prime",
"plot.snpeff_variant_effects_region.splice_site_acceptor"
) %in% colnames(report)))
expect_equal(
report %>% filter(metadata.sample_id == "P4107_1001") %>% pull("plot.snpeff_variant_effects_region.exon"),
191454
)
}) |
extract.mark.output <-
function(out,model,adjust,realvcv=FALSE,vcvfile)
{
os=R.Version()$os
locate=function(x)
{
loc=regexpr("} = ",out[x])
if(length(loc)==0)return(NULL)
if(loc[1]==-1)loc=regexpr(" = ",out[x])-1
return(loc)
}
design.matrix=model$simplify$design.matrix
links=model$links
model_def=setup.model(model$model,model$nocc)
if(model_def$derived)
derived_labels=model_def$derived_labels[[1]]
else
derived_labels=NULL
outfile=tempfile("markxxx",tmpdir=getwd(),fileext=".tmp")
nreal=dim(design.matrix)[1]
nbeta=dim(design.matrix)[2]
x=grep("Effective sample size ",out,ignore.case=TRUE)
if(length(x)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
n=type.convert(substr(out[x],regexpr("=",out[x])+1,nchar(out[x])))
x=grep("-2logL {",out,fixed=TRUE)
if(length(x)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
lnl=type.convert(substr(out[x],locate(x)+4,nchar(out[x])))
x=grep("Number of Estimated",out,ignore.case=TRUE)
if(length(x)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
npar=type.convert(substr(out[x],locate(x)+4,nchar(out[x])))
x=grep("DEVIANCE ",out,ignore.case=TRUE)
if(length(x)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
deviance=type.convert(substr(out[x],locate(x)+4,nchar(out[x])))[1]
x = grep("DEVIANCE Degrees of Freedom ", out, ignore.case = TRUE)
if(length(x)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
deviance.df = type.convert(substr(out[x], locate(x)+4, nchar(out[x])))[1]
x=grep("AICc",out,ignore.case=TRUE)
if(length(x)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
AICc=type.convert(substr(out[x],locate(x)+4,nchar(out[x])))
if(length(links)==1)
x1=grep(paste(links,"link"),out,ignore.case=TRUE)
else
x1=grep("parm-specific link",out,ignore.case=TRUE)
if(length(x1)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
x2=grep("Real Function Parameters",out,ignore.case=TRUE)
if(length(x2)==0)
{
message(paste("MARK did not run properly. If error message was not shown, look at most recent .out file"))
return(NULL)
}
x3=length(out)
if(length(grep("proc stop",out,ignore.case=TRUE))==0)
message("\nWarning: output from MARK was not complete\n")
x4=grep("Variable Value",out,ignore.case=FALSE)+1
if(length(x4)==0)x4=x2
if(x4>x2)
{
ff <- tempfile()
cat(file=ff, out[(x4+1):(x4+length(model$covariates))],sep="\n")
covariate.values=read.fwf(file=ff,widths=c(20,15),col.names=c("Variable","Value"))
}
else
covariate.values=NULL
j=1
save=NULL
for(i in x1:(x2-1))
{
if(j<=nbeta)
{
ind=regexpr(paste(" ",j,":",sep=""),out[i])
if(ind!=-1 & ind<=20)
{
save=c(save,out[i])
j=j+1
}
}
}
write(save,outfile)
x=read.fwf(file=outfile,widths=c(26,16,16,16,16),col.names=c("","estimate","se","lcl","ucl"))
dimx=dim(x)[2]
beta=as.data.frame(x[,((dimx-4+1):dimx)])
names(beta)=c("estimate","se","lcl","ucl")
row.names(beta)= colnames(model$simplify$design.matrix)
nbeta=length(beta$estimate[beta$estimate!=0.000000])
singular=NULL
if(nbeta!=npar)
{
x=grep("Attempted ordering of parameters",out,ignore.case=TRUE)
if(length(x)==0)
warning("\nNot all parameters were estimated but not able to find non-estimable parameters\n")
else
{
nlines=ceiling(nbeta/25)
par.indices=NULL
for (i in (x+1):(x+nlines))
{
ii=strsplit(out[i]," ")[[1]]
par.indices=c(par.indices,as.numeric(ii[ii!=""]))
}
singular=par.indices[(npar+1):nbeta]
}
}
if(nbeta!=npar & adjust)
{
message("\nNote: only ",npar," parameters counted of ",nbeta," specified parameters\n")
message("AICc and parameter count have been adjusted upward\n")
AICc.unadjusted=AICc
npar.unadjusted=npar
AICc=lnl+ 2*nbeta +2*nbeta*(nbeta+1)/(n - nbeta -1)
npar=nbeta
}
else
npar.unadjusted=NULL
unlink(outfile)
j=1
if(x4>x2)x2=x4+length(model$covariates)+1
for(i in x2:(x3-1))
{
if(j<=nreal)
{
ind=regexpr(paste(" ",j,":",sep=""),out[i])
if(ind==-1)
ind= regexpr("\\*\\*\\*\\*:",out[i])
if(ind!=-1& ind<=20)
{
write(out[i],file=outfile,append=TRUE)
j=j+1
}
}
}
x=read.fwf(file=outfile,widths=c(27,16,16,16,16,20),col.names=c("","estimate","se","lcl","ucl","fixed"),
as.is=TRUE)
unlink(outfile)
x$note=""
x$fixed[is.na(x$fixed)]= " "
x$note[substr(as.character(x$fixed),3,7)!="Fixed"]=x$fixed[substr(as.character(x$fixed),3,7)!="Fixed"]
x$fixed[substr(as.character(x$fixed),3,7)!="Fixed"]=" "
x$fixed[substr(as.character(x$fixed),3,7)=="Fixed"]="Fixed"
x$fixed[is.na(x$fixed)]= " "
real=data.frame(estimate=as.numeric(x$estimate),se=as.numeric(x$se),lcl=as.numeric(x$lcl),ucl=as.numeric(x$ucl),fixed=x$fixed,note=x$note)
if(is.null(model$simplify))
row.names(real) = row.names(design.matrix)
else
row.names(real)=row.names(model$simplify$design.matrix)
if(!is.factor(real$note))real$note=""
if(file.exists(vcvfile))
if(os=="mingw32")
param=read.mark.binary(vcvfile,derived_labels)
else
param=read.mark.binary.linux(vcvfile,derived_labels)
else
{
param=NULL
message("\nV-C file is missing. Skipping over it.\n")
}
if(realvcv)
real.vcv=param$real.vcv
else
real.vcv=NULL
if(is.null(npar.unadjusted))
return(list(lnl=lnl,deviance=deviance,deviance.df=deviance.df,npar=npar,n=n,AICc=AICc,beta=beta,real=real,beta.vcv=param$beta.vcv,derived=param$derived,derived.vcv=param$derived.vcv,
covariate.values=covariate.values,singular=singular,real.vcv=real.vcv))
else
return(list(lnl=lnl,deviance=deviance,deviance.df=deviance.df,npar=npar,npar.unadjusted=npar.unadjusted,n=n,AICc=AICc,AICc.unadjusted=AICc.unadjusted,
beta=beta,real=real,beta.vcv=param$beta.vcv,derived=param$derived,derived.vcv=param$derived.vcv,
covariate.values=covariate.values,singular=singular,real.vcv=real.vcv))
} |
tabPanel( "Generate possible time points" ,
tags$br() ,
sidebarLayout(
sidebarPanel( width = 5 ,
h3( "Time constraints" ) ,
actionLink(inputId = "helpTimeConstraints" , label = "Time constraints", icon = icon("question-circle") ) ,
conditionalPanel( "input.helpTimeConstraints % 2 == 1" ,
wellPanel(
"Table containing number of user specified time points per time zone.
Each row is a time zone." ,
HTML('<ul type="disc">
<li> <em>startTime</em> the start time of each time zone assumed to be included in
that zone</li>
<li> <em>endTime</em> the end time of the zone. It is not part of the current zone
but the start time of the next zone</li>
<li> <em>nPointsPerZone</em> the number of time points to be chosen within each zone</li>
<li> <em>timeInterval</em> mimimum time difference between time points</li>
</ul>') ,
"the last time point is always included and not specified in time constraints"
) ,
tags$br()
) ,
rHandsontableOutput( "tableTimeConstraints" ) ,
actionButton( "clearTimeConstraints", "clear time constraints") ,
tags$br() ,
h3( "Generate time points" ) ,
actionButton( inputId = "calcTimePoints" , label = "Generate time points" , icon = icon("gears") )
) ,
mainPanel( width = 5 ,
h3("Possible time points") ,
wellPanel( textOutput( "textFullTimePoints" ) ) ,
tags$br() ,
h3("Time point combinations meeting constraints") ,
h4("Number of combinations") ,
wellPanel(
textOutput( "nTimePoints" )
) ,
h4("Time point combinations") ,
addSpinner( DT::dataTableOutput( "tableSetOfTimePoints" ) )
)
)
) |
pseudo.absence <- function(x, n, window = "hull", Mask = NULL, s = NULL, sigma = "Scott",
wts = NULL, KDE = FALSE, gradient = 1, p = NULL, edge = FALSE) {
if (!class(x)[1] == "SpatialPointsDataFrame" & !class(x) == "SpatialPoints")
stop(deparse(substitute(x)), " MUST BE A sp POINTS OBJECT")
if (!is.null(Mask)) {
if (!class(Mask)[1] == "RasterLayer")
stop(deparse(substitute(Mask)), " MUST BE A RasterLayer OBJECT")
}
if (is.null(p)) p <- 1e-09
a <- 10000
raster.as.im <- function(im) {
r <- raster::res(im)
orig <- sp::bbox(im)[, 1] + 0.5 * r
dm <- dim(im)[2:1]
xx <- unname(orig[1] + cumsum(c(0, rep(r[1], dm[1] - 1))))
yy <- unname(orig[2] + cumsum(c(0, rep(r[2], dm[2] - 1))))
return(spatstat.geom::im(matrix(raster::values(im), ncol = dm[1],
nrow = dm[2], byrow = TRUE)[dm[2]:1, ],
xcol = xx, yrow = yy))
}
if (is.null(Mask)) {
if (window == "hull") {
win <- spatstat.geom::convexhull.xy(sp::coordinates(x))
win <- spatstat.geom::as.mask(win, eps = s)
}
if (window == "extent") {
e <- as.vector(sp::bbox(x))
win <- spatstat.geom::as.owin(c(e[1], e[3], e[2], e[4]))
win <- spatstat.geom::as.mask(win, eps = s)
}
} else {
win <- raster.as.im(Mask)
win <- spatstat.geom::as.mask(win, eps = raster::res(Mask)[1])
}
x.ppp <- spatstat.geom::as.ppp(sp::coordinates(x), win)
bw.Scott <- function(X) {
stopifnot(spatstat.geom::is.ppp(X))
n <- spatstat.geom::npoints(X)
sdx <- sqrt(stats::var(X$x))
sdy <- sqrt(stats::var(X$y))
return(c(sdx, sdy) * n^(-1/6))
}
bw.Stoyan <- function(X, co = 0.15) {
stopifnot(spatstat.geom::is.ppp(X))
n <- spatstat.geom::npoints(X)
W <- spatstat.geom::as.owin(X)
a <- spatstat.geom::area.owin(W)
stoyan <- co/sqrt(5 * n/a)
return(stoyan)
}
bw.geometry <- function(X, f = 1/4) {
X <- spatstat.geom::as.owin(X)
g <- spatstat.core::distcdf(X)
r <- with(g, .x)
Fr <- with(g, .y)
iopt <- min(which(Fr >= f))
return(r[iopt])
}
bw.likelihood <- function(X, srange = NULL, ns = 16) {
check.range <- function (x, fatal = TRUE) {
xname <- deparse(substitute(x))
if (is.numeric(x) && identical(x, range(x, na.rm = TRUE)))
return(TRUE)
if (fatal)
stop(paste(xname, "should be a vector of length 2 giving (min, max)"))
return(FALSE)
}
stopifnot(spatstat.geom::is.ppp(X))
if (!is.null(srange))
check.range(srange) else {
nnd <- spatstat.geom::nndist(X)
srange <- c(min(nnd[nnd > 0]), spatstat.geom::diameter(spatstat.geom::as.owin(X))/2)
}
sigma <- exp(seq(log(srange[1]), log(srange[2]), length = ns))
cv <- numeric(ns)
for (i in 1:ns) {
si <- sigma[i]
lamx <- spatstat.core::density.ppp(X, sigma = si, at = "points", leaveoneout = TRUE)
lam <- spatstat.core::density.ppp(X, sigma = si)
cv[i] <- sum(log(lamx)) - spatstat.geom::integral.im(lam)
}
result <- spatstat.core::bw.optim(cv, sigma, iopt = which.max(cv),
criterion = "Likelihood Cross-Validation")
return(result)
}
if (sigma == "Diggle") {
bw <- spatstat.core::bw.diggle(x.ppp)
} else if(sigma == "Scott") {
bw <- bw.Scott(x.ppp)
} else if(sigma == "Stoyan") {
bw <- bw.Stoyan(x.ppp)
} else if(sigma == "geometry") {
bw <- bw.geometry(x.ppp)
} else if(sigma == "likelihood") {
bw <- bw.likelihood(x.ppp)
} else if(is.numeric(sigma)) {
bw = sigma
} else {
stop("Not a valid bandwidth option")
}
den <- raster::raster(spatstat.core::density.ppp(x.ppp, weights = wts, sigma = bw,
adjust = gradient, diggle = edge)) * a
den <- 1 - (den/raster::maxValue(den))
den[den <= p] <- p
den.sp <- raster::rasterToPoints(den, spatial=TRUE)
names(den.sp@data)[1] <- "KDE"
den.sp <- den.sp[sample(1:nrow(den.sp@data), size = n, prob = den.sp@data$KDE), ]
if (KDE == TRUE) {
return(list(sample = den.sp, kde = den, sigma = bw))
} else {
return(list(sample = den.sp, sigma = bw) )
}
} |
remove.redundant.vertices <- function(H,
check.empty=TRUE
)
{
if(!hypergraph.is.connected(H)) stop("H is disconnected")
f <- function(guess,h,v,check.empty){
inds <- v[(1:guess)]
myHype <- hypergraph.delete.vertices(h, inds)
if(check.empty && has.empty.hyperedges(myHype)) return(-1)
if(hypergraph.is.connected(myHype))
{
if(guess>1){
inds <- inds[-length(inds)]
myHype <- hypergraph.delete.vertices(h,inds)
if(check.empty && has.empty.hyperedges(myHype)){
return(1)
}
if(!hypergraph.is.connected(myHype)){
return(0)
}
}
return(1)
}
else
{
return(-1)
}
}
vorder <- order(hdegree(H),decreasing=TRUE)
suppressWarnings(
z <- gtools::binsearch(f,c(1,horder(H)),h=H,
v=vorder,
check.empty=check.empty)
)
h1 <- hypergraph.delete.vertices(H,vorder[1:z$where[1]])
if(length(z$where)==2){
h2 <- hypergraph.delete.vertices(H,vorder[1:z$where[2]])
if(!hypergraph.is.connected(h1) ||
(check.empty && has.empty.hyperedges(h1))){
h1 <- h2
} else if(horder(h2)<horder(h1)){
if(hypergraph.is.connected(h2) &&
!(check.empty && has.empty.hyperedges(h2))){
h1 <- h2
}
}
} else if((z$flag=="Upper Boundary") && (z$value==(-1))){
h1 <- H
}
h1
} |
.d <- function(bs, s=length(bs)) {
if (s == 1) return(bs)
if (is.matrix(bs)) sqrt(rowSums(bs*bs)) else sqrt(sum(bs*bs))
}
.d2 <- function(sbs2, s) {
if (s == 1) stop("s must be larger than 1")
sqrt(sbs2)
}
.Dd2 <- function(sbs2, s) {
1/.d2(sbs2,s)
}
.zeroB <- function(object, pp = object@pp)
if (inherits(pp, "rlmerPredD_test")) pp$zeroB else pp$zeroB()
lchol <- function(x) {
r <- try(chol.default(x), silent=TRUE)
if (is(r, "try-error")) {
Diagonal(x = sqrt(diag(x)))
} else r
}
calcE.D.re <- function(s, rho) {
if (s == 1) return(rho@EDpsi())
tfun <- function(v) rho@Dwgt(.d2(v,s))*.Dd2(v,s)*v*dchisq(v, s)
tfun2 <- function(v) rho@wgt(.d2(v,s))*dchisq(v, s)
integrate(tfun, 0, Inf)$value / s + integrate(tfun2, 0, Inf)$value
}
calcE.D.re2 <- function(rho, s) calcE.D.re(s, rho)
calcE.psi_bbt <- function(rho, s) {
if (s == 1) {
Matrix(rho@EDpsi())
} else {
wgt <- rho@wgt
fun <- function(v) wgt(.d2(v,s))*v*dchisq(v,s)
tmp <- integrate(fun, 0, Inf)$value / s
Diagonal(x=rep(tmp, s))
}
}
calcE.psi_bpsi_bt <- function(rho, s) {
if (s == 1) {
Matrix(rho@Epsi2())
} else {
wgt <- rho@wgt
fun <- function(v) wgt(.d2(v,s))^2*v*dchisq(v, s)
tmp <- integrate(fun, 0, Inf)$value / s
Diagonal(x=rep(tmp, s))
}
}
.s <- function(object, theta = FALSE, pp = object@pp) {
if (theta) {
M1 <- pp$K()
M2 <- pp$L
diag(M2) <- 0
} else {
M1 <- pp$A
diag(M1) <- 0
M2 <- pp$B()
}
M1[is.na(M1)] <- 0
M2[is.na(M2)] <- 0
ret <- pp$rho_e@Epsi2() * rowSums(M1^2)
if (any(!.zeroB(pp = pp))) ret <- ret + drop(M2^2 %*% diag(pp$Epsi_bpsi_bt))
sqrt(ret)
}
.S <- function(object) {
ret <- list()
idx <- !.zeroB(object)
tmpEL <- object@pp$L() %*% object@pp$Epsi_bpsi_bt()
for (k in 1:max(object@k)) {
ind <- object@k == k
if (any(idx[ind])) {
ret <- c(ret, list(drop(lchol(symmpart(
[email protected]@Epsi2() * crossprod(object@pp$Kt()[, ind, drop=FALSE]) +
tcrossprod(object@pp$L()[ind, !ind, drop=FALSE],
tmpEL[ind, !ind, drop=FALSE])
)))))
} else {
ret <- c(ret, list(matrix(0, sum(ind), sum(ind))))
}
}
ret
}
calcKappaTau <- function(rho, s=1) {
if (s > 38) return(1)
psi <- rho@psi
if (s == 1) {
wgt <- rho@wgt
tfun <- function(e) psi(e)*e*dnorm(e)
tfun2 <- function(e) wgt(e)*dnorm(e)
integrate(tfun, -Inf, Inf)$value / integrate(tfun2, -Inf, Inf)$value
} else {
tfun3 <- function(v, kappa) psi(v-s*kappa)*dchisq(v, s)
tfun4 <- function(kappa) integrate(tfun3, 0, Inf, kappa=kappa)$value
uniroot(tfun4, c(0, 1), tol = .Machine$double.eps^0.5)$root
}
}
calcKappaTauB <- function(object, pp = object@pp, rhoSigmaB = [email protected]) {
pp$btapply(rhoSigmaB, calcKappaTau)
}
.sigma <- robustlmm:::.sigma
uArranged <- robustlmm:::uArranged
rho.b <- robustlmm:::rho.b
rho.e <- robustlmm:::rho.e
b.s <- robustlmm:::b.s
.kappa_b <- robustlmm:::.kappa_b
std.b <- function(object, sigma = .sigma(object), matrix, drop=TRUE, t=FALSE)
object@pp$stdB(sigma, matrix, drop, t)
std.e <- function(object, sigma = .sigma(object), matrix, drop=TRUE) {
if (missing(matrix)) return(object@resp$wtres / sigma)
if (drop) matrix <- drop(matrix)
matrix/sigma
}
.dk <- function(object, sigma, center, bs = b.s(object), ...) {
ua <- uArranged(object, bs/sigma)
unlist(lapply(seq_along(object@blocks), function(bt) {
us <- ua[[bt]]
s <- ncol(us)
if (s == 1) return(us)
ret <- rowSums(us*us)
if (center) ret <- ret - .kappa_b(object)[bt]*s
ret
}))
}
dist.b <- function(object, sigma = .sigma(object), center=FALSE, ...) {
db <- .dk(object, sigma, center, ...)
if (!center && any(object@dim > 1)) {
bidx <- object@ind %in% which(object@dim > 1)
db[bidx] <- sqrt(db[bidx])
}
db[object@k]
}
dist.e <- function(object, sigma = .sigma(object)) {
std.e(object, sigma)
}
wgt.b <- function(object, sigma = .sigma(object), center = FALSE) {
db <- dist.b(object, sigma, center)
rho <- rho.b(object, if (center) "sigma" else "default")
ret <- numeric()
for (bt in seq_along(object@blocks)) {
bind <- as.vector(object@idx[[bt]])
ret <- c(ret, rho[[bt]]@wgt(db[bind]))
}
ret
}
wgt.e <- function(object, sigma = .sigma(object), use.rho.sigma = FALSE)
if (use.rho.sigma) [email protected]@wgt(dist.e(object, sigma)) else
[email protected]@wgt(dist.e(object, sigma))
calcTau <- function(a, s, rho.e, rho.sigma.e, pp,
kappa, tau = rep(1, length(a)), method="DAStau",
rel.tol = 1e-6, max.it = 200) {
stopifnot(length(a) == length(s))
if (method == "DASvar" || !is.numeric(tau) || length(tau) != length(a)) {
Tau <- with(pp, V_e - EDpsi_e * (t(A) + A) + Epsi2_e * tcrossprod(A) +
B() %*% tcrossprod(Epsi_bpsi_bt, B()))
tau <- sqrt(diag(Tau))
if (method == "DASvar") return(tau)
}
psiZ <- rho.e@psi(pp$ghZ)
fun <- function(tau, a, s) {
t <- (pp$ghZ-a*psiZ-s*pp$ghZt)/tau
numerator <- sum(rho.sigma.e@psi(t)*t*(tau*tau)*pp$ghW)
denominator <- sum(rho.sigma.e@wgt(t)*pp$ghW)*kappa
newValue = sqrt(numerator /denominator)
newValue
}
for (i in seq_along(a)) {
check <- FALSE
a_i <- a[i]
s_i <- s[i]
j <- 0
while ((j <- j + 1) < i) {
if( abs(a_i - a[j]) < 1e-8 && abs(s_i - s[j]) < 1e-8 ) {
check <- TRUE
tau[i] <- tau[j]
break
}
}
if (!check) {
it <- 0
conv <- FALSE
while(!conv && (it <- it + 1) < max.it && tau[i] <= 1) {
tau0 <- tau[i]
tau[i] <- fun(tau0, a_i, s_i)
conv <- abs(tau[i] - tau0) < rel.tol * max(rel.tol, tau0)
}
if (it >= max.it) {
warning("calculation of tau[", i, "] reached max.it")
}
if (tau[i] > 1) {
tau[i] <- 1
warning("tau[", i, "] > 1, setting it to 1")
}
}
}
tau
}
calcTau.nondiag <- function(object, ghZ, ghw, skbs, kappas, max.iter,
rel.tol = 1e-4, verbose = 0, pp = object@pp) {
T <- pp$T()
TkbsI <- list()
for (type in seq_along(object@blocks)) {
bidx <- object@idx[[type]]
for (k in 1:ncol(bidx))
TkbsI <- c(TkbsI, list(as.matrix(T[bidx[,k],bidx[,k]])))
}
Tbks <- list()
for (type in seq_along(object@blocks)) {
if (verbose > 5)
cat("computing tau for blocktype", type, "...\n")
bidx <- object@idx[[type]]
s <- nrow(bidx)
ind <- which(object@ind == type)
idx <- !.zeroB(pp=pp)
if (!any(idx[bidx])) {
Tbks <- c(Tbks, rep(list(matrix(0, s, s)), length(ind)))
next
}
if (s == 1) {
bidx <- drop(bidx)
tmp <- calcTau(diag(pp$L)[bidx], unlist(skbs[ind]),
[email protected][[type]], [email protected][[type]],
pp, kappas[type])
Tbks <- c(Tbks, as.list(tmp*tmp))
} else if (s == 2) {
wgt <- [email protected][[type]]@wgt
wgt.sigma <- [email protected][[type]]@wgt
psi.sigma <- [email protected][[type]]@psi
skappa <- s*pp$kappa_b[type]
if (verbose > 6) {
cat("type = ", type, "\n")
cat("skappa = ", format(skappa, digits = 15), "\n")
}
wgtDelta <- function(u) (psi.sigma(u) - psi.sigma(u-skappa))/s
lastSk <- lastLkk <- matrix()
lastRet <- NA
for (k in 1:ncol(bidx)) {
lTbk <- as.matrix(TkbsI[[ind[k]]])
lbidx <- bidx[,k]
Lkk <- as.matrix(pp$L[lbidx, lbidx])
Sk <- as.matrix(skbs[[ind[k]]])
diff <- if (any(dim(lastSk) != dim(Sk))) 1 else
abs(c(lastSk - Sk, lastLkk - Lkk))
if (any(diff >= rel.tol * max(diff, rel.tol))) {
lastSk <- Sk
lastLkk <- Lkk
if (verbose > 5)
cat("TbkI for k =", k, ":", lTbk, "\n")
if (verbose > 6) {
cat("Lkk = ", format(Lkk, digits = 15), "\n")
cat("Sk = ", format(Sk, digits = 15), "\n")
}
conv <- FALSE
iter <- 0
while (!conv && (iter <- iter + 1) < max.iter) {
lUTbk <- try(chol(lTbk), silent=TRUE)
if (is(lUTbk, "try-error")) {
warning("chol(lTbk) failed: ", lUTbk, "\nlTbk was: ", paste(lTbk),
"\nSetting it to Tb()\n")
conv <- TRUE
lTbk <- as.matrix(TkbsI[[ind[k]]])
} else {
if (FALSE) {
funA <- function(u) {
btilde <- u[1:2] - wgt(.d(u[1:2],2)) * Lkk %*% u[1:2] - crossprod(Sk, u[3:4])
wgtDelta(drop(crossprod(backsolve(lUTbk, btilde))))
}
a <- int4d(funA)
funB <- function(u) {
btilde <- u[1:2] - wgt(.d(u[1:2],2)) * Lkk %*% u[1:2] -
crossprod(Sk, u[3:4])
wgt.sigma(drop(crossprod(backsolve(lUTbk, btilde))))*tcrossprod(btilde)
}
B <- matrix(int4d(funB), s)
}
btilde <- ghZ[,1:2] - wgt(.d(ghZ[,1:2],2)) * ghZ[, 1:2] %*% Lkk -
ghZ[, 3:4] %*% Sk
tmp1 <- colSums(backsolve(lUTbk, t(btilde))^2)
tmp2 <- btilde[,1] * btilde[,2]
a <- sum(wgtDelta(tmp1) * ghw)
if (abs(a) < 1e-7) {
a <- lasta
} else {
lasta <- a
}
B <- matrix(colSums(wgt.sigma(tmp1) * ghw *
matrix(c(btilde[,1]*btilde[,1], tmp2, tmp2,
btilde[,2]*btilde[,2]), length(ghw))),2)
lTbk1 <- B/a
diff <- abs(c(lTbk - lTbk1))
conv <- all(diff < rel.tol * max(diff, rel.tol))
if (verbose > 5) {
cat(sprintf("k=%i, iter=%i, conv=%s\n", k, iter, conv))
if (verbose > 6) {
cat("B:", B, "\n")
cat("a:", a, "\n")
}
cat("Tbk:", lTbk1, "\n")
}
lTbk <- lTbk1
}
}
lastRet <- lTbk
}
Tbks <- c(Tbks, list(lastRet))
}
} else {
warning("DAStau for blocks of dimension > 2 not defined, falling back to DASvar")
stop("yes, do as promised")
}
}
out <- bdiag(Tbks)
return(out)
} |
correlation <- function(data,
data2 = NULL,
select = NULL,
select2 = NULL,
rename = NULL,
method = "pearson",
p_adjust = "holm",
ci = 0.95,
bayesian = FALSE,
bayesian_prior = "medium",
bayesian_ci_method = "hdi",
bayesian_test = c("pd", "rope", "bf"),
redundant = FALSE,
include_factors = FALSE,
partial = FALSE,
partial_bayesian = FALSE,
multilevel = FALSE,
ranktransform = FALSE,
winsorize = FALSE,
verbose = TRUE,
standardize_names = getOption("easystats.standardize_names", FALSE),
...) {
if (partial == FALSE & multilevel) {
partial <- TRUE
convert_back_to_r <- TRUE
} else {
convert_back_to_r <- FALSE
}
if (bayesian == TRUE) {
p_adjust <- "none"
}
if (ci == "default") {
ci <- 0.95
}
if (is.null(data2) && !is.null(select)) {
all_selected <- c(select, select2)
not_in_data <- !all_selected %in% colnames(data)
if (any(not_in_data)) {
stop(paste0("Following variables are not in the data: ", all_selected[not_in_data], collapse = ", "))
}
if (inherits(data, "grouped_df")) {
grp_df <- attributes(data)$groups
grp_var <- setdiff(colnames(grp_df), ".rows")
select <- unique(c(select, grp_var))
select2 <- if (!is.null(select2)) unique(c(select2, grp_var))
} else {
grp_df <- NULL
}
data2 <- if (!is.null(select2)) data[select2]
data <- data[select]
attr(data, "groups") <- grp_df
attr(data2, "groups") <- if (!is.null(select2)) grp_df
}
if (!is.null(rename)) {
if (length(data) != length(rename)) {
warning("Mismatch between number of variables and names.")
} else {
colnames(data) <- rename
}
}
if (inherits(data, "grouped_df")) {
rez <- .correlation_grouped_df(
data,
data2 = data2,
method = method,
p_adjust = p_adjust,
ci = ci,
bayesian = bayesian,
bayesian_prior = bayesian_prior,
bayesian_ci_method = bayesian_ci_method,
bayesian_test = bayesian_test,
redundant = redundant,
include_factors = include_factors,
partial = partial,
partial_bayesian = partial_bayesian,
multilevel = multilevel,
ranktransform = ranktransform,
winsorize = winsorize,
verbose = verbose,
...
)
} else {
rez <- .correlation(
data,
data2 = data2,
method = method,
p_adjust = p_adjust,
ci = ci,
bayesian = bayesian,
bayesian_prior = bayesian_prior,
bayesian_ci_method = bayesian_ci_method,
bayesian_test = bayesian_test,
redundant = redundant,
include_factors = include_factors,
partial = partial,
partial_bayesian = partial_bayesian,
multilevel = multilevel,
ranktransform = ranktransform,
winsorize = winsorize,
verbose = verbose,
...
)
}
out <- rez$params
attributes(out) <- c(
attributes(out),
list(
"data" = data,
"data2" = data2,
"modelframe" = rez$data,
"ci" = ci,
"n" = nrow(data),
"method" = method,
"bayesian" = bayesian,
"p_adjust" = p_adjust,
"partial" = partial,
"multilevel" = multilevel,
"partial_bayesian" = partial_bayesian,
"bayesian_prior" = bayesian_prior,
"include_factors" = include_factors
)
)
attr(out, "additional_arguments") <- list(...)
if (inherits(data, "grouped_df")) {
class(out) <- unique(c("easycorrelation", "see_easycorrelation", "grouped_easycorrelation", "parameters_model", class(out)))
} else {
class(out) <- unique(c("easycorrelation", "see_easycorrelation", "parameters_model", class(out)))
}
if (convert_back_to_r) out <- pcor_to_cor(pcor = out)
if (standardize_names) insight::standardize_names(out, ...)
out
}
.correlation_grouped_df <- function(data,
data2 = NULL,
method = "pearson",
p_adjust = "holm",
ci = "default",
bayesian = FALSE,
bayesian_prior = "medium",
bayesian_ci_method = "hdi",
bayesian_test = c("pd", "rope", "bf"),
redundant = FALSE,
include_factors = TRUE,
partial = FALSE,
partial_bayesian = FALSE,
multilevel = FALSE,
ranktransform = FALSE,
winsorize = FALSE,
verbose = TRUE,
...) {
groups <- setdiff(colnames(attributes(data)$groups), ".rows")
ungrouped_x <- as.data.frame(data)
xlist <- split(ungrouped_x, ungrouped_x[groups], sep = " - ")
if (!is.null(data2)) {
if (inherits(data2, "grouped_df")) {
groups2 <- setdiff(colnames(attributes(data2)$groups), ".rows")
if (all.equal(groups, groups2)) {
ungrouped_y <- as.data.frame(data2)
ylist <- split(ungrouped_y, ungrouped_y[groups], sep = " - ")
modelframe <- data.frame()
out <- data.frame()
for (i in names(xlist)) {
xlist[[i]][groups] <- NULL
ylist[[i]][groups] <- NULL
rez <- .correlation(
xlist[[i]],
data2 = ylist[[i]],
method = method,
p_adjust = p_adjust,
ci = ci,
bayesian = bayesian,
bayesian_prior = bayesian_prior,
bayesian_ci_method = bayesian_ci_method,
bayesian_test = bayesian_test,
redundant = redundant,
include_factors = include_factors,
partial = partial,
partial_bayesian = partial_bayesian,
multilevel = multilevel,
ranktransform = ranktransform,
winsorize = winsorize
)
modelframe_current <- rez$data
rez$params$Group <- modelframe_current$Group <- i
out <- rbind(out, rez$params)
modelframe <- rbind(modelframe, modelframe_current)
}
} else {
stop("'data2' should have the same grouping characteristics as data.")
}
}
} else {
modelframe <- data.frame()
out <- data.frame()
for (i in names(xlist)) {
xlist[[i]][groups] <- NULL
rez <- .correlation(
xlist[[i]],
data2,
method = method,
p_adjust = p_adjust,
ci = ci,
bayesian = bayesian,
bayesian_prior = bayesian_prior,
bayesian_ci_method = bayesian_ci_method,
bayesian_test = bayesian_test,
redundant = redundant,
include_factors = include_factors,
partial = partial,
partial_bayesian = partial_bayesian,
multilevel = multilevel,
ranktransform = ranktransform,
winsorize = winsorize
)
modelframe_current <- rez$data
rez$params$Group <- modelframe_current$Group <- i
out <- rbind(out, rez$params)
modelframe <- rbind(modelframe, modelframe_current)
}
}
out <- out[c("Group", names(out)[names(out) != "Group"])]
list(params = out, data = modelframe)
}
.correlation <- function(data,
data2 = NULL,
method = "pearson",
p_adjust = "holm",
ci = "default",
bayesian = FALSE,
bayesian_prior = "medium",
bayesian_ci_method = "hdi",
bayesian_test = c("pd", "rope", "bf"),
redundant = FALSE,
include_factors = FALSE,
partial = FALSE,
partial_bayesian = FALSE,
multilevel = FALSE,
ranktransform = FALSE,
winsorize = FALSE,
verbose = TRUE,
...) {
if (!is.null(data2)) {
data <- cbind(data, data2)
}
if (ncol(data) <= 2 & any(sapply(data, is.factor)) & include_factors == FALSE) {
if (isTRUE(verbose)) {
warning("It seems like there is not enough continuous variables in your data. Maybe you want to include the factors? We're setting `include_factors=TRUE` for you.", call. = FALSE)
}
include_factors <- TRUE
}
if (sum(sapply(if (is.null(data2)) data else cbind(data, data2), is.numeric)) == 0) {
include_factors <- TRUE
}
if (method == "polychoric") multilevel <- TRUE
combinations <- .get_combinations(
data,
data2 = NULL,
redundant = FALSE,
include_factors = include_factors,
multilevel = multilevel,
method = method
)
data <- .clean_data(data, include_factors = include_factors, multilevel = multilevel)
for (i in 1:nrow(combinations)) {
x <- as.character(combinations[i, "Parameter1"])
y <- as.character(combinations[i, "Parameter2"])
if (i > 1) {
verbose <- FALSE
}
result <- cor_test(
data,
x = x,
y = y,
ci = ci,
method = method,
bayesian = bayesian,
bayesian_prior = bayesian_prior,
bayesian_ci_method = bayesian_ci_method,
bayesian_test = bayesian_test,
partial = partial,
multilevel = multilevel,
ranktransform = ranktransform,
winsorize = winsorize,
verbose = verbose,
...
)
if (i == 1) {
params <- result
} else {
if (!all(names(result) %in% names(params))) {
if ("r" %in% names(params) & !"r" %in% names(result)) {
names(result)[names(result) %in% c("rho", "tau")] <- "r"
}
if ("r" %in% names(result) & !"r" %in% names(params)) {
names(params)[names(params) %in% c("rho", "tau")] <- "r"
}
if (!"r" %in% names(params) & any(c("rho", "tau") %in% names(result))) {
names(params)[names(params) %in% c("rho", "tau")] <- "r"
names(result)[names(result) %in% c("rho", "tau")] <- "r"
}
result[names(params)[!names(params) %in% names(result)]] <- NA
}
params <- rbind(params, result)
}
}
if ("Method" %in% names(params)) {
params$Method <- paste0(params$Method, " correlation")
if (!isFALSE(winsorize) && !is.null(winsorize)) {
params$Method <- paste0("Winsorized ", params$Method)
}
}
if (!is.null(data2)) {
params <- params[!params$Parameter1 %in% names(data2), ]
params <- params[params$Parameter2 %in% names(data2), ]
}
if ("p" %in% names(params)) {
params$p <- stats::p.adjust(params$p, method = p_adjust)
}
if (redundant) {
params <- .add_redundant(params, data)
}
list(params = params, data = data)
}
plot.easycorrelation <- function(x, ...) {
insight::check_if_installed("see", "to plot correlation graphs")
NextMethod()
} |
touchi.boundary<-function(rec1,rec2,rho=0)
{
d<-length(rec1)/2
if (length(rho)==1) rho<-rep(rho,d)
tulos<-1
i<-1
while ((i<=d) && (tulos==1)){
ala<-max(rec1[2*i-1],rec2[2*i-1])
yla<-min(rec1[2*i],rec2[2*i])
ala2<-min(rec1[2*i-1],rec2[2*i-1])
yla2<-max(rec1[2*i],rec2[2*i])
if ((ala2==0)&&(yla2==2*pi)) isboundary<-TRUE
else isboundary<-FALSE
if ((!isboundary)&&(yla+2*rho[i]<ala)) tulos<-0
i<-i+1
}
return(tulos)
} |
context("obs_cor")
test_that("obs_cor endpoint", {
skip_on_cran()
url <- getOption("epigraphdb.api.url")
trait <- "body mass index"
r <- httr::RETRY("GET", glue::glue("{url}/obs-cor"),
query = list(
trait = trait
),
config = httr::add_headers(.headers = c("client-type" = "R", "ci" = "true"))
)
expect_equal(httr::status_code(r), 200)
expect_true(length(httr::content(r)) > 0)
})
test_that("obs_cor mode = \"table\"", {
skip_on_cran()
trait <- "body mass index"
expect_error(
df <- obs_cor(
trait = trait
),
NA
)
expect_is(df, "tbl_df")
})
test_that("obs_cor mode = \"raw\"", {
skip_on_cran()
trait <- "body mass index"
expect_error(
response <- obs_cor(
trait = trait,
mode = "raw"
),
NA
)
expect_equal(length(response), 2L)
})
test_that("obs_cor cor_coef_threshold", {
skip_on_cran()
trait <- "Body mass index"
expect_error(
response <- obs_cor(
trait = trait,
cor_coef_threshold = 0.8
),
NA
)
expect_error(
response <- obs_cor(
trait = trait,
cor_coef_threshold = 0.6
),
NA
)
expect_error(
response <- obs_cor(
trait = trait,
cor_coef_threshold = 0.4
),
NA
)
}) |
hMeanChiSq <- function(z, w = rep(1, length(z)),
alternative = c("greater", "less", "two.sided", "none"),
bound = FALSE){
stopifnot(is.numeric(z),
length(z) > 0,
is.finite(z),
is.numeric(w),
length(w) == length(z),
is.finite(w),
min(w) > 0,
!is.null(alternative))
alternative <- match.arg(alternative)
stopifnot(is.logical(bound),
length(bound) == 1,
is.finite(bound))
n <- length(z)
zH2 <- sum(sqrt(w))^2 / sum(w / z^2)
res <- pchisq(zH2, df = 1, lower.tail = FALSE)
check_greater <- min(z) >= 0
check_less <- max(z) <= 0
break_p <- 1 / (2^n)
if(alternative == "greater"){
if(bound)
res <- if(check_greater) res / (2^n) else paste(">", format(break_p, scientific = FALSE))
else
res <- if(check_greater) res / (2^n) else NaN
}
if(alternative == "less"){
if(bound)
res <- if(check_less) res / (2^n) else paste(">", format(break_p, scientific = FALSE))
else
res <- if(check_less) res / (2^n) else NaN
}
if(alternative == "two.sided"){
if(bound)
res <- if(check_greater || check_less) res / (2^(n - 1)) else
paste(">", format(2*break_p, scientific = FALSE))
else
res <- if(check_greater || check_less) res / (2^(n - 1)) else NaN
}
return(res)
}
hMeanChiSqMu <- function(thetahat, se, w = rep(1, length(thetahat)), mu = 0,
alternative = c("greater", "less", "two.sided", "none"),
bound = FALSE){
stopifnot(is.numeric(thetahat),
length(thetahat) > 0,
is.finite(thetahat),
is.numeric(se),
length(se) == 1 || length(se) == length(thetahat),
is.finite(se),
min(se) > 0,
is.numeric(w),
length(w) == length(thetahat),
is.finite(w),
min(w) > 0,
is.numeric(mu),
length(mu) > 0,
is.finite(mu),
!is.null(alternative))
alternative <- match.arg(alternative)
stopifnot(is.logical(bound),
length(bound) == 1,
is.finite(bound))
n <- length(thetahat)
m <- length(mu)
if(alternative != "none"){
z <- (thetahat - mu) / se
zH2 <- sum(sqrt(w))^2 / sum(w / z^2)
res <- pchisq(zH2, df = 1, lower.tail = FALSE)
check_greater <- min(z) >= 0
check_less <- max(z) <= 0
break_p <- 1 / (2^n)
if(alternative == "greater"){
if(bound)
res <- if(check_greater) res / (2^n) else paste(">", format(break_p, scientific = FALSE))
else
res <- if(check_greater || check_less) res/(2^n) else NaN
}
if(alternative == "less"){
if(bound)
res <- if(check_less) res / (2^n) else paste(">", format(break_p, scientific = FALSE))
else
res <- if(check_greater || check_less) res / (2^n) else NaN
}
if(alternative == "two.sided"){
if(bound)
res <- if(check_greater || check_less) res / (2^(n - 1)) else
paste(">", format(2*break_p, scientific = FALSE))
else
res <- if(check_greater || check_less) res / (2^(n - 1)) else NaN
}
}
if(alternative == "none"){
zH2 <- numeric(m)
sw <- sum(sqrt(w))^2
for(i in 1:m){
z <- (thetahat - mu[i]) / se
zH2[i] <- sw / sum(w / z^2)
}
res <- pchisq(q = zH2, df = 1, lower.tail = FALSE)
}
return(res)
}
hMeanChiSqCI <- function(thetahat, se, w = rep(1, length(thetahat)),
alternative = c("two.sided", "greater", "less", "none"),
level = 0.95, wGamma = rep(1, length(unique(thetahat)) - 1)){
stopifnot(is.numeric(thetahat),
length(thetahat) > 0,
is.finite(thetahat))
stopifnot(is.numeric(se),
length(se) == 1 || length(se) == length(thetahat),
is.finite(se),
min(se) > 0,
is.numeric(w),
length(w) == length(thetahat),
is.finite(w),
min(w) > 0,
!is.null(alternative))
alternative <- match.arg(alternative)
stopifnot(is.numeric(level),
length(level) == 1,
is.finite(level),
0 < level, level < 1,
is.numeric(wGamma),
length(wGamma) == length(unique(thetahat)) -1,
is.finite(w),
min(w) > 0)
target <- function(limit){
hMeanChiSqMu(thetahat = thetahat, se = se, w = w, mu = limit,
alternative = alternative, bound = FALSE) - alpha
}
indOrd <- order(thetahat)
thetahat <- thetahat[indOrd]; se <- se[indOrd]; w <- w[indOrd]
thetahatUnique <- unique(thetahat)
nThetahatUnique <- length(thetahatUnique)
mini <- which.min(thetahat)
maxi <- which.max(thetahat)
mint <- thetahat[mini]
maxt <- thetahat[maxi]
minse <- se[mini]
maxse <- se[maxi]
alpha <- 1 - level
z1 <- max(-qnorm(alpha), 1)
eps <- 1e-6
factor <- 5
if(alternative == "none"){
lower <- mint - z1 * minse
while(target(lower) > 0)
lower <- lower - minse
CIlower <- uniroot(f = target, lower = lower, upper = thetahat[1])$root
CImiddle <- matrix(NA, nrow = 2, ncol = nThetahatUnique - 1)
gam <- matrix(NA, nrow = nThetahatUnique - 1, ncol = 2)
colnames(gam) <- c("minimum", "pvalue_fun/gamma")
for(i in 1:(nThetahatUnique - 1)){
opt <- optimize(f = target, lower = thetahatUnique[i],
upper = thetahatUnique[i + 1])
gam[i,] <- c(opt$minimum, opt$objective + alpha)
if(opt$objective <= 0){
CImiddle[1, i] <- uniroot(f = target, lower = thetahatUnique[i],
upper = opt$minimum)$root
CImiddle[2, i] <- uniroot(f = target, lower = opt$minimum,
upper = thetahatUnique[i + 1])$root
}
}
CImiddle <- CImiddle[!is.na(CImiddle)]
upper <- maxt + maxse
while(target(upper) > 0)
upper <- upper + z1 * maxse
CIupper <- uniroot(f = target, lower = thetahat[length(thetahat)],
upper = upper)$root
CI <- matrix(c(CIlower, CImiddle, CIupper), ncol = 2, byrow = TRUE)
colnames(CI) <- c("lower", "upper")
return(list(CI = CI,
gamma = gam,
gammaMean = weighted.mean(x = gam[,"pvalue_fun/gamma"], w = wGamma),
gammaHMean = sum(wGamma) / sum(wGamma / gam[,"pvalue_fun/gamma"])))
}
if(alternative == "two.sided"){
lower <- uniroot(f = target,
lower = mint - factor * z1 * minse,
upper = mint - eps * minse)$root
upper <- uniroot(f = target, lower = maxt + eps * maxse,
upper = maxt + factor * z1 * maxse)$root
return(list(CI = cbind(lower, upper)))
}
if(alternative == "greater"){
lower <- uniroot(f = target,
lower = mint - factor * z1 * minse,
upper = mint - eps * minse)$root
upper <- Inf
return(list(CI = cbind(lower, upper)))
}
if(alternative == "less"){
lower <- -Inf
upper <- uniroot(f = target,
lower = maxt + eps * maxse,
upper = maxt + factor * z1 * maxse)$root
return(list(CI = cbind(lower, upper)))
}
stop("function not get here.")
}
unirootAll <- function(f, interval, lower = min(interval), upper = max(interval),
n = 1000,
tol = .Machine$double.eps^0.2,
maxiter = 1000, trace = 0,
...)
{
stopifnot(is.function(f), length(formals(f)) >= 1,
is.numeric(lower), length(lower) == 1, is.finite(lower),
is.numeric(upper), length(upper) == 1, is.finite(upper),
lower < upper,
is.numeric(n), length(n) == 1, is.finite(n), n >= 2)
n <- round(n)
xseq <- seq(lower, upper, length.out = n + 1)
mod <- f(xseq, ...)
index <- which(mod[1:n] * mod[2:(n + 1)] < 0)
rootsOffGrid <- numeric(length = length(index))
for (i in seq_along(index))
rootsOffGrid[i] <- uniroot(f = f, lower = xseq[index[i]],
upper = xseq[index[i] + 1], maxiter = maxiter,
tol = tol, trace = trace, ...)$root
rootsGrid <- xseq[which(mod == 0)]
if(length(rootsGrid) > 0)
return(sort(c(rootsGrid, rootsOffGrid)))
rootsOffGrid
} |
ui_params <- function() {
ns <- NS("params")
tabPanel(
"Parameters",
value = "parameters",
verticalLayout(
fluidRow(
column(2, style = "margin-top: 25px; margin-bottom: 25px",
actionButton(ns("configs_save"), "Save parameters")),
column(2, style = "margin-top: 25px; margin-bottom: 25px",
actionButton(ns("configs_load"), "Load selected"))
) %>% shinyhelper::helper(type = "markdown", content = "params_help"),
fluidRow(DT::DTOutput(ns("configs_table")))
)
)
}
server_params <- function(id, distance_method, linkage_method, nclusters) {
moduleServer(id, function(input, output, session) {
saved_configurations <- reactiveVal(list())
output$configs_table <- DT::renderDT({
validate(need(length(saved_configurations()) > 0, "No states saved"))
do.call(rbind, saved_configurations())
},
rownames = TRUE,
caption = "Click on a row to select parameters to load them again",
selection = "single",
options = list(ordering = FALSE))
observeEvent(input$configs_save, {
idx <- length(saved_configurations()) + 1
current_config <- list(
distance_method = distance_method(),
linkage_method = linkage_method(),
nclusters = nclusters()
)
config_list <- saved_configurations()
config_list[[idx]] <- current_config
saved_configurations(config_list)
})
selected_config <- eventReactive(input$configs_load, {
req(input$configs_table_rows_selected)
saved_configurations()[[input$configs_table_rows_selected]]
})
selected_config
})
} |
Level2RegularNodeBP <- function(level, organism = NULL){
Organism <- organism
if(is.null(level) || !is.numeric(level)){
stop("The argument \"level\" is missing with no default or is non numeric")
}
x <- level + 1
if(!is.null(Organism) && !(toupper(Organism) %in% SupportedOrganism)){
print(SupportedOrganismv2)
stop("The \"organism\" argument should be given from the list above")
}
if(is.null(Organism)){
tryCatch({
nonLeafNode <- GOgeneralbp$df[x,][2]
if(nonLeafNode != 0){
return(GOgeneralbp$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for the General GO BP tree, the highest level is", 19 , sep = " "))
})
}else if(toupper(Organism) == "HOMO SAPIENS" || toupper(Organism) == "HUMAN"){
tryCatch({
nonLeafNode <- BPHuman$df[x,][2]
if(nonLeafNode != 0){
return(BPHuman$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for the General GO BP tree, the highest level is", length(BPHuman$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "RATTUS NORVEGICUS" || toupper(Organism) == "RAT"){
tryCatch({
nonLeafNode <- gontr::BPRat$df[x,][2]
if(nonLeafNode != 0){
return(gontr::BPRat$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Rat, the highest level is", length(gontr::BPRat$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "MUS MUSCULUS" || toupper(Organism) == "MOUSE"){
tryCatch({
nonLeafNode <- gontr::BPMouse$df[x,][2]
if(nonLeafNode != 0){
return(gontr::BPMouse$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Mouse, the highest level is", length(gontr::BPMouse$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "DANIO RERIO" || toupper(Organism) == "ZEBRAFISH"){
tryCatch({
nonLeafNode <- BPZebrafish$df[x,][2]
if(nonLeafNode != 0){
return(BPZebrafish$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Zebrafish, the highest level is", length(BPZebrafish$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "CAENORHABDITIS ELEGANS" || toupper(Organism) == "WORM"){
tryCatch({
nonLeafNode <- BPElegan$df[x,][2]
if(nonLeafNode != 0){
return(BPElegan$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Caenorhabditis elegans, the highest level is", length(BPElegan$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "ARABIDOPSIS THALIANA" || toupper(Organism) == "CRESS"){
tryCatch({
nonLeafNode <- BPTair$df[x,][2]
if(nonLeafNode != 0){
return(BPTair$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Arabidopsis thaliana, the highest level is", length(BPTair$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "SACCHAROMYCES CEREVISIAE" || toupper(Organism) == "YEAST"){
tryCatch({
nonLeafNode <- BPYeast$df[x,][2]
if(nonLeafNode != 0){
return(BPYeast$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Saccharomyces cerevisiae, the highest level is", length(BPYeast$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "SCHIZOSACCHAROMYCES POMBE" || toupper(Organism) == "FISSION YEAST"){
tryCatch({
nonLeafNode <- BPPombe$df[x,][2]
if(nonLeafNode != 0){
return(BPPombe$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Schizosaccharomyces pombe, the highest level is", length(BPPombe$df[,1]) - 1, sep = " "))
})
}
else if(toupper(Organism) == "DROSOPHILA MELANOGASTER" || toupper(Organism) == "FRUIT FLY"){
tryCatch({
nonLeafNode <- BPDrosophila$df[x,][2]
if(nonLeafNode != 0){
return(BPDrosophila$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Drosophila melanogaster, the highest level is", length(BPDrosophila$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "ESCHERICHIA COLI" || toupper(Organism) == "E.COLI"){
tryCatch({
nonLeafNode <- BPEcoli$df[x,][2]
if(nonLeafNode != 0){
return(BPEcoli$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Escherichia coli, the highest level is", length(BPEcoli$df[,1]) - 1, sep = " "))
})
}
}
Level2RegularNodeMF <- function(level, organism = NULL){
Organism <- organism
if(is.null(level) || !is.numeric(level)){
stop("The argument \"level\" is missing with no default or is non numeric")
}
x <- level + 1
if(!is.null(Organism) && !(toupper(Organism) %in% SupportedOrganism)){
print(SupportedOrganismv2)
stop("The \"organism\" argument should be given from the list above")
}
if(is.null(Organism)){
tryCatch({
nonLeafNode <- GOgeneralmf$df[x,][2]
if(nonLeafNode != 0){
return(GOgeneralmf$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for the General GO MF tree, the highest level is", 16 , sep = " "))
})
}else if(toupper(Organism) == "HOMO SAPIENS" || toupper(Organism) == "HUMAN"){
tryCatch({
nonLeafNode <- MFHuman$df[x,][2]
if(nonLeafNode != 0){
return(MFHuman$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Human, the highest level is", length(MFHuman$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "RATTUS NORVEGICUS" || toupper(Organism) == "RAT"){
tryCatch({
nonLeafNode <- gontr::MFRat$df[x,][2]
if(nonLeafNode != 0){
return(gontr::MFRat$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Rat, the highest level is", length(gontr::MFRat$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "MUS MUSCULUS" || toupper(Organism) == "MOUSE"){
tryCatch({
nonLeafNode <- gontr::MFMouse$df[x,][2]
if(nonLeafNode != 0){
return(gontr::MFMouse$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Mouse, the highest level is", length(gontr::MFMouse$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "DANIO RERIO" || toupper(Organism) == "ZEBRAFISH"){
tryCatch({
nonLeafNode <- MFZebrafish$df[x,][2]
if(nonLeafNode != 0){
return(MFZebrafish$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Zebrafish, the highest level is", length(MFZebrafish$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "CAENORHABDITIS ELEGANS" || toupper(Organism) == "WORM"){
tryCatch({
nonLeafNode <- MFElegan$df[x,][2]
if(nonLeafNode != 0){
return(MFElegan$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Caenorhabditis elegans, the highest level is", length(MFElegan$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "ARABIDOPSIS THALIANA" || toupper(Organism) == "CRESS"){
tryCatch({
nonLeafNode <- MFTair$df[x,][2]
if(nonLeafNode != 0){
return(MFTair$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Arabidopsis thaliana, the highest level is", length(MFTair$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "SACCHAROMYCES CEREVISIAE" || toupper(Organism) == "YEAST"){
tryCatch({
nonLeafNode <- MFYeast$df[x,][2]
if(nonLeafNode != 0){
return(MFYeast$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Saccharomyces cerevisiae, the highest level is", length(MFYeast$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "SCHIZOSACCHAROMYCES POMBE" || toupper(Organism) == "FISSION YEAST"){
tryCatch({
nonLeafNode <- MFPombe$df[x,][2]
if(nonLeafNode != 0){
return(MFPombe$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Schizosaccharomyces pombe, the highest level is", length(MFPombe$df[,1]) - 1, sep = " "))
})
}
else if(toupper(Organism) == "DROSOPHILA MELANOGASTER" || toupper(Organism) == "FRUIT FLY"){
tryCatch({
nonLeafNode <- MFDrosophila$df[x,][2]
if(nonLeafNode != 0){
return(MFDrosophila$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Drosophila melanogaster, the highest level is", length(MFDrosophila$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "ESCHERICHIA COLI" || toupper(Organism) == "E.COLI"){
tryCatch({
nonLeafNode <- MFEcoli$df[x,][2]
if(nonLeafNode != 0){
return(MFEcoli$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Escherichia coli, the highest level is", length(MFEcoli$df[,1]) - 1, sep = " "))
})
}
}
Level2RegularNodeCC <- function(level, organism = NULL){
Organism <- organism
if(is.null(level) || !is.numeric(level)){
stop("The argument \"level\" is missing with no default or is non numeric")
}
x <- level + 1
if(!is.null(Organism) && !(toupper(Organism) %in% SupportedOrganism)){
print(SupportedOrganismv2)
stop("The \"organism\" argument should be given from the list above")
}
if(is.null(Organism)){
tryCatch({
nonLeafNode <- GOgeneralcc$df[x,][2]
if(nonLeafNode != 0){
return(GOgeneralcc$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for the General GO CC tree, the highest level is", 17 , sep = " "))
})
}else if(toupper(Organism) == "HOMO SAPIENS" || toupper(Organism) == "HUMAN"){
tryCatch({
nonLeafNode <- CCHuman$df[x,][2]
if(nonLeafNode != 0){
return(CCHuman$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Human, the highest level is", length(CCHuman$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "RATTUS NORVEGICUS" || toupper(Organism) == "RAT"){
tryCatch({
nonLeafNode <- gontr::CCRat$df[x,][2]
if(nonLeafNode != 0){
return(gontr::CCRat$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Rat, the highest level is", length(gontr::CCRat$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "MUS MUSCULUS" || toupper(Organism) == "MOUSE"){
tryCatch({
nonLeafNode <- gontr::CCMouse$df[x,][2]
if(nonLeafNode != 0){
return(gontr::CCMouse$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Mouse, the highest level is", length(gontr::CCMouse$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "DANIO RERIO" || toupper(Organism) == "ZEBRAFISH"){
tryCatch({
nonLeafNode <- CCZebrafish$df[x,][2]
if(nonLeafNode != 0){
return(CCZebrafish$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Zebrafish, the highest level is", length(CCZebrafish$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "CAENORHABDITIS ELEGANS" || toupper(Organism) == "WORM"){
tryCatch({
nonLeafNode <- CCElegan$df[x,][2]
if(nonLeafNode != 0){
return(CCElegan$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Caenorhabditis elegans, the highest level is", length(CCElegan$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "ARABIDOPSIS THALIANA" || toupper(Organism) == "CRESS"){
tryCatch({
nonLeafNode <- CCTair$df[x,][2]
if(nonLeafNode != 0){
return(CCTair$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Arabidopsis thaliana, the highest level is", length(CCTair$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "SACCHAROMYCES CEREVISIAE" || toupper(Organism) == "YEAST"){
tryCatch({
nonLeafNode <- CCYeast$df[x,][2]
if(nonLeafNode != 0){
return(CCYeast$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Saccharomyces cerevisiae, the highest level is", length(CCYeast$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "SCHIZOSACCHAROMYCES POMBE" || toupper(Organism) == "FISSION YEAST"){
tryCatch({
nonLeafNode <- CCPombe$df[x,][2]
if(nonLeafNode != 0){
return(CCPombe$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Schizosaccharomyces pombe, the highest level is", length(CCPombe$df[,1]) - 1, sep = " "))
})
}
else if(toupper(Organism) == "DROSOPHILA MELANOGASTER" || toupper(Organism) == "FRUIT FLY"){
tryCatch({
nonLeafNode <- CCDrosophila$df[x,][2]
if(nonLeafNode != 0){
return(CCDrosophila$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Drosophila melanogaster, the highest level is", length(CCDrosophila$df[,1]) - 1, sep = " "))
})
}else if(toupper(Organism) == "ESCHERICHIA COLI" || toupper(Organism) == "E.COLI"){
tryCatch({
nonLeafNode <- CCEcoli$df[x,][2]
if(nonLeafNode != 0){
return(CCEcoli$v[[as.character(nonLeafNode)]])
}
else{
return(NULL)
}
}, error = function(e){
print(paste("No such level exist for Escherichia coli, the highest level is", length(CCEcoli$df[,1]) - 1, sep = " "))
})
}
} |
.parse_draftpick_url <-
function(url = "https://data.nba.net/data/5s/prod/draft/2017/draft_pick.json") {
data <- url %>% fromJSON(simplifyDataFrame = T) %>% as_tibble()
data
} |
context("spec (responses): 1.26")
test_sample_responses("1.26") |
BASiCSEstimate <- function(counts, spike.info = NULL, batch = NULL,
n = 20000, thin = 10, burn = 5000,
regression = TRUE,
params = newBASiCSParams(), verbose = TRUE,
progress = TRUE, ...) {
UseMethod("BASiCSEstimate")
}
BASiCSEstimate.SingleCellExperiment <- function(counts, spike.info = NULL,
batch = NULL, n = 20000,
thin = 10, burn = 5000,
regression = TRUE,
params = newBASiCSParams(),
verbose = TRUE, progress = TRUE,
...) {
counts <- getCounts(counts)
BASiCSEstimate(counts, spike.info, batch, n, thin, burn, regression,
params, verbose, progress, ...)
}
BASiCSEstimate.matrix <- function(counts, spike.info = NULL, batch = NULL,
n = 20000, thin = 10, burn = 5000,
regression = TRUE,
params = newBASiCSParams(), verbose = TRUE,
progress = TRUE, ...) {
checkmate::assertClass(params, "BASiCSParams")
checkmate::assertMatrix(counts, mode = "numeric", any.missing = FALSE,
min.rows = 1, min.cols = 1, row.names = "unique",
col.names = "unique")
if (is.null(spike.info) && is.null(batch)) {
stop("At least one of spike.info and batch must be provided")
}
if (!is.null(spike.info)) {
checkmate::assertDataFrame(spike.info, any.missing = FALSE,
min.rows = 1, ncols = 2)
if (!all(colnames(spike.info) == c("Name", "Input"))) {
stop("spike.info must have columns named 'Name' and 'Input'")
}
checkmate::assertCharacter(spike.info$Name, min.chars = 1,
unique = TRUE)
checkmate::assertNumeric(spike.info$Input, lower = 0, finite = TRUE)
}
if (!is.null(batch)) {
checkmate::assertIntegerish(batch, lower = 0, any.missing = FALSE,
len = ncol(counts))
if (is.null(spike.info) && length(unique(batch)) == 1) {
stop("If spike.info is not provided there must be at least two ",
"batches")
}
} else {
batch <- rep(1, ncol(counts))
}
checkmate::assertInt(thin, lower = 2)
checkmate::assertInt(n, lower = max(4, thin))
if ((n %% thin) != 0) {
stop("'n' must be a multiple of 'thin'")
}
checkmate::assertInt(burn, lower = 1, upper = n - 1)
if ((burn %% thin) != 0) {
stop("'burn' must be a multiple of 'thin'")
}
checkmate::assertFlag(regression)
is.spike <- rownames(counts) %in% spike.info$Name
BASiCS.data <- suppressMessages(
BASiCS::newBASiCS_Data(counts, is.spike, spike.info,
batch)
)
with.spikes <- sum(is.spike) > 1
if (verbose) {
mcmc <- BASiCS::BASiCS_MCMC(Data = BASiCS.data, N = n, Thin = thin,
Burn = burn, Regression = regression,
PrintProgress = progress,
WithSpikes = with.spikes, ...)
} else {
mcmc <- suppressMessages(
BASiCS::BASiCS_MCMC(Data = BASiCS.data, N = n, Thin = thin,
Burn = burn, Regression = regression,
PrintProgress = progress,
WithSpikes = with.spikes, ...)
)
}
mcmc.summ <- BASiCS::Summary(mcmc)
means <- BASiCS::displaySummaryBASiCS(mcmc.summ, Param = "mu")[, 1]
deltas <- BASiCS::displaySummaryBASiCS(mcmc.summ, Param = "delta")[, 1]
if (!is.null(spike.info)) {
phis <- BASiCS::displaySummaryBASiCS(mcmc.summ, Param = "phi")[, 1]
} else {
phis <- rep(1, ncol(counts))
}
ss <- BASiCS::displaySummaryBASiCS(mcmc.summ, Param = "s")[, 1]
thetas <- BASiCS::displaySummaryBASiCS(mcmc.summ, Param = "theta")[, 1]
params <- setParams(params,
nGenes = sum(!is.spike),
batchCells = as.vector(table(batch)),
gene.params = data.frame(Mean = means, Delta = deltas),
nSpikes = sum(is.spike),
spike.means = ifelse(!is.null(spike.info),
spike.info$Input, numeric()),
cell.params = data.frame(Phi = phis, S = ss),
theta = thetas)
return(params)
} |
library(revdepcheck)
revdep_check(quiet = FALSE, num_workers = 2, pkg = ".", timeout = as.difftime(120, units = "mins")) |
plotDistractorAnalysis <- function(Data, key, num.groups = 3, item = 1, item.name, multiple.answers = TRUE,
criterion = NULL, crit.discrete = FALSE, cut.points, data, matching, match.discrete) {
if (!missing(data)) {
warning("Argument 'data' is deprecated; please use 'Data' instead.",
call. = FALSE
)
Data <- data
}
if (!missing(matching)) {
warning("Argument 'matching' is deprecated; please use 'criterion' instead.",
call. = FALSE
)
criterion <- matching
}
if (!missing(match.discrete)) {
warning("Argument 'match.discrete' is deprecated; please use 'crit.discrete' instead.",
call. = FALSE
)
crit.discrete <- match.discrete
}
if (missing(key)) {
if (all(sapply(Data, is.numeric))) {
warning("Answer key is not provided. Maximum value is used as key.", call. = FALSE)
key <- sapply(Data, max, na.rm = TRUE)
} else if (missing(criterion)) {
stop("Answer key is not provided. Please, specify key to be able to calculate total score or provide criterion. ",
call. = FALSE
)
} else {
key <- NULL
}
} else {
if (!length(key) == ncol(Data)) {
stop("Answer key is not provided or some item keys are missing.", call. = FALSE)
}
key <- unlist(key)
}
tabDA <- DistractorAnalysis(
Data = Data, key = key, p.table = TRUE, num.groups = num.groups, criterion = criterion,
crit.discrete = crit.discrete, cut.points = cut.points
)
x <- tabDA[[item]]
if (dim(x)[2] != 1) {
x <- x[!(apply(x, 1, function(y) all(y == 0))), ]
}
x <- as.data.frame(x)
colnames(x)[colnames(x) == "Freq"] <- "value"
x <- x[complete.cases(x), ]
x$response <- as.factor(x$response)
levels(x$response)[which(levels(x$response) == "")] <- "NaN"
if (!is.null(key)) {
x$response <- relevel(x$response, as.character(key[item]))
}
if (multiple.answers) {
df <- x
CA <- CAall <- as.character(key[item])
col <- rainbow(n = length(levels(df$response)))
names(col) <- levels(df$response)
} else {
levels(x$response)[which(levels(x$response) == "NaN")] <- "x"
y <- x[rep(1:nrow(x), nchar(as.character(x$response))), ]
y$response <- as.factor(unlist(strsplit(as.character(x$response), "")))
df <- aggregate(value ~ response + score.level, data = y, sum)
CAdf <- x[x$response == as.character(key[item]), ]
CAdf$response <- paste(key[item], "-correct", sep = "")
df <- rbind(df, CAdf)
CA <- unique(CAdf$response)
levels(df$response)[which(levels(df$response) == "x")] <- "NaN"
col <- rainbow(n = (length(levels(df$response)) + 1))
names(col) <- levels(df$response)
col[CA] <- "black"
df$response <- relevel(df$response, CA)
CAall <- c(CA, unlist(strsplit(as.character(key[item]), "")))
}
if (missing(item.name)) {
item.name <- paste("Item", item)
}
if (is.null(key)) {
linetype <- rep(1, length(levels(df$response)))
shape <- rep(19, length(levels(df$response)))
names(linetype) <- names(shape) <- levels(df$response)
} else {
linetype <- rep(2, length(levels(df$response)))
shape <- rep(1, length(levels(df$response)))
names(linetype) <- names(shape) <- levels(df$response)
linetype[CAall] <- 1
shape[CAall] <- 19
}
xlab <- ifelse(is.null(criterion), "Group by total score", "Group by criterion variable")
df$score.level <- as.factor(df$score.level)
num.groups <- length(unique(df$score.level))
colnames(df) <- c("Response", "Group", "Proportion")
levels(df$Group) <- 1:length(levels(df$Group))
g <- ggplot(df, aes_string(
x = "Group",
y = "Proportion",
group = "Response",
colour = "Response",
linetype = "Response",
shape = "Response"
)) +
geom_line(size = 0.8) +
geom_point(size = 3) +
xlab(xlab) +
ylab("Option selection proportion") +
scale_y_continuous(limits = c(0, 1)) +
scale_x_discrete(labels = 1:num.groups, expand = c(0, 0.15)) +
scale_linetype_manual(values = linetype) +
scale_shape_manual(values = shape) +
scale_color_manual(values = col) +
theme_app() +
theme(
legend.position = c(0.01, 0.98),
legend.justification = c(0, 1),
legend.key.width = unit(1, "cm")
) +
ggtitle(item.name)
if (length(col) > 11) {
g <- g + guides(
linetype = guide_legend(ncol = 2),
shape = guide_legend(ncol = 2),
color = guide_legend(ncol = 2)
)
}
return(g)
} |
expandedLinkTable <- function( Links, Coordinates ){
if( is.null(Links) ) {
return(NA)
} else {
ept <- merge( x = Links, by.x = "Node1", all.x = TRUE, sort = FALSE,
y = Coordinates, by.y = "Node" )
names(ept)[ grep("X.coord", names(ept)) ] <- "x1"
names(ept)[ grep("Y.coord", names(ept)) ] <- "y1"
ept <- merge( x = ept, by.x = "Node2", all.x = TRUE, sort = FALSE,
y = Coordinates, by.y = "Node" )
names(ept)[ grep("X.coord", names(ept)) ] <- "x2"
names(ept)[ grep("Y.coord", names(ept)) ] <- "y2"
ept$midx <- (ept$x1 + ept$x2) / 2
ept$midy <- (ept$y1 + ept$y2) / 2
ept <- ept[ ,c( names(Links), 'x1', 'y1', 'x2', 'y2', 'midx', 'midy') ]
}
class(ept) <- c("expandedLinkTable", "data.frame")
return(ept)
}
plot.expandedLinkTable <- function(x, add=FALSE, label=FALSE, linewidths = 3, color = 'black', ...){
if( add == FALSE ){
graphics::plot( range( c(x$x1, x$x2) ),
range( c(x$y1, x$y2) ),
type = 'n',
xlab = "", xaxt = 'n',
ylab = "", yaxt = 'n'
)
}
graphics::segments( x0 = x$x1, y0 = x$y1,
x1 = x$x2, y1 = x$y2,
lwd = linewidths, col = color, ... )
if( label == TRUE ){
graphics::text( x$midx, x$midy, x$ID)
}
}
is.expandedLinkTable <- function( x ){
inherits( x, "expandedLinkTable")
} |
source("incl/start.R")
if (require(future.batchtools, character.only = TRUE)) {
message("*** doFuture + future.batchtools ...")
strategies <- c("batchtools_local", "batchtools_interactive")
res0 <- NULL
for (strategy in strategies) {
message(sprintf("- plan('%s') ...", strategy))
plan(strategy)
message("- Explicitly exporting globals ...")
mu <- 1.0
sigma <- 2.0
res1 <- foreach(i = 1:3, .export = c("mu", "sigma"),
.packages = "stats") %dopar% {
dnorm(i, mean = mu, sd = sigma)
}
print(res1)
if (is.null(res0)) {
res0 <- res1
} else {
stopifnot(all.equal(res1, res0))
}
message("- Explicitly exporting globals ... DONE")
message("- Implicitly exporting globals (via future) ...")
mu <- 1.0
sigma <- 2.0
res2 <- foreach(i = 1:3, .packages = "stats") %dopar% {
dnorm(i, mean = mu, sd = sigma)
}
print(res2)
stopifnot(all.equal(res2, res0))
library("tools")
my_ext <- function(x) file_ext(x)
y_truth <- lapply("abc.txt", FUN = my_ext)
y <- foreach(f = "abc.txt") %dopar% { file_ext(f) }
stopifnot(identical(y, y_truth))
message("- Implicitly exporting globals (via future) ... DONE")
if (require(plyr, character.only = TRUE)) {
message("*** dplyr w / doFuture + future.batchtools ...")
print(sessionInfo())
x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE, FALSE, FALSE, TRUE))
y0 <- llply(x, quantile, probs = (1:3) / 4, .parallel = FALSE)
print(y0)
y1 <- llply(x, quantile, probs = (1:3) / 4, .parallel = TRUE)
print(y1)
stopifnot(all.equal(y1, y0))
message("*** dplyr w / doFuture + future.batchtools ... DONE")
}
if (require(BiocParallel, character.only = TRUE) &&
packageVersion("BiocParallel") >= "1.2.22") {
message("*** BiocParallel w / doFuture + future.batchtools ...")
print(sessionInfo())
y0 <- list()
p <- SerialParam()
y0$a <- bplapply(1:5, sqrt, BPPARAM = p)
y0$b <- bpvec(1:5, sqrt, BPPARAM = p)
str(y0)
register(SerialParam(), default = TRUE)
p <- DoparParam()
y1 <- list()
y1$a <- bplapply(1:5, sqrt, BPPARAM = p)
y1$b <- bpvec(1:5, sqrt, BPPARAM = p)
stopifnot(identical(y1, y0))
register(DoparParam(), default = TRUE)
y2 <- list()
y2$a <- bplapply(1:5, sqrt, BPPARAM = p)
y2$b <- bpvec(1:5, sqrt, BPPARAM = p)
stopifnot(identical(y2, y0))
message("*** BiocParallel w / doFuture + future.batchtools ... DONE")
}
message(sprintf("- plan('%s') ... DONE", strategy))
}
print(sessionInfo())
message("*** doFuture + future.batchtools ... DONE")
}
source("incl/end.R") |
.getAdjustedE <- function(r, tr, i, e) {
startcell <- cellFromRowCol(r, tr$row[i] , 1)
len <- cellFromRowCol(r, tr$row[i] + (tr$nrows[i]-1), ncol(r)) - startcell + 1
n <- (startcell / length(e)) %% 1
if (n > 0 ) {
start <- round(n * length(e))
} else {
start <- 1
}
out <- c(e[start:length(e)], rep(e, floor(len/length(e))))
out[1:len]
}
.asLogical <- function(x) {
x[x!=0] <- 1
return(x)
}
setMethod('==', signature(e1='BasicRaster', e2='BasicRaster'),
function(e1,e2){
cond <- compareRaster(c(e1, e2), extent=TRUE, rowcol=TRUE, crs=TRUE, tolerance=0.05, stopiffalse=FALSE)
return(cond)
}
)
setMethod('!=', signature(e1='BasicRaster', e2='BasicRaster'),
function(e1,e2){
cond <- compareRaster(c(e1, e2), extent=TRUE, rowcol=TRUE, crs=TRUE, tolerance=0.05, stopiffalse=FALSE)
return(!cond)
}
)
setMethod('!', signature(x='Raster'),
function(x){
if (nlayers(x) > 1) {
r <- brick(x, values=FALSE)
} else {
r <- raster(x)
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
return(setValues(r, ! getValues(x)))
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- ! .asLogical(getValues(x, row=tr$row[i], nrows=tr$nrows[i]))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
return(r)
}
}
)
setMethod("Compare", signature(e1='Raster', e2='logical'),
function(e1,e2){
nl <- nlayers(e1)
if (nl > 1) {
r <- brick(e1, values=FALSE)
} else {
r <- raster(e1)
}
if (length(e2) > 1 & nl > 1) {
if (length(e2) != nl) {
a <- rep(NA, nl)
a[] <- e2
e2 <- a
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
r <- setValues(r, values=t(methods::callGeneric(t(getValues(e1)), e2 ) ) )
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- t(methods::callGeneric( t(getValues(e1, row=tr$row[i], nrows=tr$nrows[i])), e2))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
}
} else {
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
if (length(e2) > ncell(r)) {
e2 <- e2[1:ncell(r)]
}
r <- setValues(r, values=methods::callGeneric(getValues(e1), e2 ) )
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
if (length(e2) > 0) {
for (i in 1:tr$n) {
e <- .getAdjustedE(r, tr, i, e2)
v <- methods::callGeneric(getValues(e1, row=tr$row[i], nrows=tr$nrows[i]), e)
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
} else {
for (i in 1:tr$n) {
v <- methods::callGeneric(getValues(e1, row=tr$row[i], nrows=tr$nrows[i]), e2)
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
}
r <- writeStop(r)
pbClose(pb)
}
}
return(r)
}
)
setMethod("Compare", signature(e1='logical', e2='Raster'),
function(e1,e2){
nl <- nlayers(e2)
if (nl > 1) {
r <- brick(e2, values=FALSE)
} else {
r <- raster(e2)
}
if (length(e1) > 1 & nl > 1) {
if (length(e1) != nl) {
a <- rep(NA, nl)
a[] <- e1
e1 <- a
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
r <- setValues(r, values=t(methods::callGeneric(e1, t(getValues(e2)) ) ) )
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- t(methods::callGeneric(e1, t(getValues(e2, row=tr$row[i], nrows=tr$nrows[i]))))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
}
} else {
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
if (length(e1) > ncell(r)) {
e1 <- e1[1:ncell(r)]
}
r <- setValues(r, values=methods::callGeneric(e1, getValues(e2) ) )
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
if (length(e1) > 0) {
for (i in 1:tr$n) {
e <- .getAdjustedE(r, tr, i, e1)
v <- methods::callGeneric(e1, getValues(e, row=tr$row[i], nrows=tr$nrows[i]))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
} else {
for (i in 1:tr$n) {
v <- methods::callGeneric(e1, getValues(e2, row=tr$row[i], nrows=tr$nrows[i]))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
}
r <- writeStop(r)
pbClose(pb)
}
}
return(r)
}
)
setMethod("Compare", signature(e1='Raster', e2='numeric'),
function(e1, e2){
nl <- nlayers(e1)
if (nl > 1) {
r <- brick(e1, values=FALSE)
} else {
r <- raster(e1)
}
if (length(e2) > 1 & nl > 1) {
if (length(e2) != nl) {
a <- rep(NA, nl)
a[] <- e2
e2 <- a
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
r <- setValues(r, values=t(methods::callGeneric(t(getValues(e1)), e2 ) ) )
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- t(methods::callGeneric( t(getValues(e1, row=tr$row[i], nrows=tr$nrows[i])), e2))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
}
} else {
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
if (length(e2) > ncell(r)) {
e2 <- e2[1:ncell(r)]
}
r <- setValues(r, values=methods::callGeneric(getValues(e1), e2))
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
if (length(e2) > 0) {
for (i in 1:tr$n) {
e <- .getAdjustedE(r, tr, i, e2)
v <- methods::callGeneric(getValues(e1, row=tr$row[i], nrows=tr$nrows[i]), e)
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
} else {
for (i in 1:tr$n) {
v <- methods::callGeneric(getValues(e1, row=tr$row[i], nrows=tr$nrows[i]), e2)
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
}
r <- writeStop(r)
pbClose(pb)
}
}
return(r)
}
)
setMethod("Compare", signature(e1='numeric', e2='Raster'),
function(e1, e2){
nl <- nlayers(e2)
if (nl > 1) {
r <- brick(e2, values=FALSE)
} else {
r <- raster(e2)
}
if (length(e1) > 1 & nl > 1) {
if (length(e1) != nl) {
a <- rep(NA, nl)
a[] <- e1
e1 <- a
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
r <- setValues(r, values=t(methods::callGeneric(e1, t(getValues(e2))) ) )
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- t(methods::callGeneric(e1, t(getValues(e2, row=tr$row[i], nrows=tr$nrows[i]))))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
}
} else {
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
if (length(e1) > ncell(r)) {
e1 <- e1[1:ncell(r)]
}
r <- setValues(r, values=methods::callGeneric(e1, getValues(e2)))
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
if (length(e2) > 0) {
for (i in 1:tr$n) {
e <- .getAdjustedE(r, tr, i, e1)
v <- methods::callGeneric(e, getValues(e2, row=tr$row[i], nrows=tr$nrows[i]))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
} else {
for (i in 1:tr$n) {
v <- methods::callGeneric(e1, getValues(e2, row=tr$row[i], nrows=tr$nrows[i]))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
}
r <- writeStop(r)
pbClose(pb)
}
}
return(r)
}
)
setMethod("Compare", signature(e1='Raster', e2='Raster'),
function(e1, e2){
if (nlayers(e1) > 1) {
if (nlayers(e2) > 1 & nlayers(e2) != nlayers(e1)) {
stop('number of layers of objects do not match')
}
r <- brick(e1, values=FALSE)
} else if (nlayers(e2) > 1) {
r <- brick(e2, values=FALSE)
} else {
r <- raster(e1)
}
cond <- compareRaster(c(r, e2), extent=TRUE, rowcol=TRUE, crs=TRUE, tolerance=0.05, stopiffalse=FALSE)
if (!cond) {
stop("Cannot compare Rasters that have different BasicRaster attributes. See compareRaster()")
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
r <- setValues(r, methods::callGeneric(getValues(e1), getValues(e2)))
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- methods::callGeneric(getValues(e1, row=tr$row[i], nrows=tr$nrows[i]), getValues(e2, row=tr$row[i], nrows=tr$nrows[i]))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
}
return(r)
}
)
setMethod("Logic", signature(e1='Raster', e2='Raster'),
function(e1, e2){
if (nlayers(e1) > 1) {
r <- brick(e1, values=FALSE)
if (nlayers(e2) > 1 & nlayers(e2) != nlayers(e1)) {
stop('number of layers of objects do not match')
}
} else if (nlayers(e2) > 1) {
r <- brick(e2, values=FALSE)
} else {
r <- raster(e1)
}
cond <- compareRaster(c(r, e2), extent=TRUE, rowcol=TRUE, crs=TRUE, tolerance=0.05, stopiffalse=FALSE)
if (!cond) {
stop("Cannot compare Rasters that have different BasicRaster attributes. See compareRaster()")
}
if (canProcessInMemory(r, 3)) {
dataType(r) <- 'LOG1S'
r <- setValues(r, methods::callGeneric(.asLogical(getValues(e1)), .asLogical(getValues(e2))))
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), datatype='LOG1S', overwrite=TRUE )
for (i in 1:tr$n) {
v <- methods::callGeneric(.asLogical(getValues(e1, row=tr$row[i], nrows=tr$nrows[i])), .asLogical(getValues(e2, row=tr$row[i], nrows=tr$nrows[i])))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
}
return(r)
}
)
setMethod("Compare", signature(e1='Extent', e2='Extent'),
function(e1,e2){
a <- methods::callGeneric(e2@xmin, e1@xmin)
b <- methods::callGeneric(e1@xmax, e2@xmax)
c <- methods::callGeneric(e2@ymin, e1@ymin)
d <- methods::callGeneric(e1@ymax, e2@ymax)
a & b & c & d
}
) |
test_that("regr_frbs", {
requirePackagesOrSkip("frbs", default.method = "load")
parset.list = list(
list(num.labels = 2L, type.mf = "TRAPEZOID")
)
old.predicts.list = list()
for (i in seq_along(parset.list)) {
pars = parset.list[[i]]
method.arg = names(pars) == "method"
if (any(method.arg)) {
pars = list(method = pars$method, control = pars[!method.arg])
} else {
pars = list(control = pars)
}
pars$data.train = regr.num.train
m = do.call(frbs::frbs.learn, pars)
ind = setdiff(names(regr.num.test), regr.num.target)
p = suppressWarnings(predict(m, newdata = regr.num.test[, ind])[, 1])
old.predicts.list[[i]] = p
}
suppressWarnings(
testSimpleParsets("regr.frbs", regr.num.df, regr.num.target,
regr.num.train.inds, old.predicts.list, parset.list)
)
}) |
removeSource <- function(fn) {
stopifnot(is.function(fn))
if (is.primitive(fn)) return(fn)
attr(fn, "srcref") <- NULL
attr(body(fn), "wholeSrcref") <- NULL
attr(body(fn), "srcfile") <- NULL
recurse <- function(part) {
if (is.name(part)) return(part)
attr(part, "srcref") <- NULL
attr(part, "wholeSrcref") <- NULL
attr(part, "srcfile") <- NULL
if (is.language(part) && is.recursive(part)) {
for (i in seq_along(part))
part[i] <- list(recurse(part[[i]]))
}
part
}
body(fn) <- recurse(body(fn))
fn
}
getSrcFilename <- function(x, full.names=FALSE, unique=TRUE) {
srcref <- getSrcref(x)
if (is.list(srcref))
result <- sapply(srcref, getSrcFilename, full.names, unique)
else {
srcfile <- attr(srcref, "srcfile")
if (is.null(srcfile)) result <- character()
else result <- srcfile$filename
}
result <- if (full.names) result
else basename(result)
if (unique) unique(result)
else result
}
getSrcDirectory <- function(x, unique=TRUE) {
result <- dirname(getSrcFilename(x, full.names=TRUE, unique=unique))
if (unique) unique(result)
else result
}
getSrcref <- function(x) {
if (inherits(x, "srcref")) return(x)
if (!is.null(srcref <- attr(x, "srcref"))) return(srcref)
if (is.function(x) && !is.null(srcref <- getSrcref(body(x))))
return(srcref)
if (methods::is(x, "MethodDefinition"))
return(getSrcref(unclass(methods::unRematchDefinition(x))))
NULL
}
getSrcLocation <- function(x, which=c("line", "column", "byte", "parse"), first=TRUE) {
srcref <- getSrcref(x)
if (is.null(srcref)) return(NULL)
if (is.list(srcref)) sapply(srcref, getSrcLocation, which, first)
else {
if (length(srcref) == 6L) srcref <- c(srcref, srcref[c(1L,3L)])
which <- match.arg(which)
if (first) index <- c(line=1L, column=5L, byte=2L, parse=7L)[which]
else index <- c(line=3L, column=6L, byte=4L, parse=8L)[which]
srcref[index]
}
}
getSrcfile <- function(x) {
result <- attr(x, "srcfile")
if (!is.null(result)) return(result)
srcref <- attr(x, "wholeSrcref")
if (is.null(srcref)) {
srcref <- getSrcref(x)
if (is.list(srcref) && length(srcref))
srcref <- srcref[[length(srcref)]]
}
attr(srcref, "srcfile")
}
substr_with_tabs <- function(x, start, stop, tabsize = 8) {
widths <- rep_len(1, nchar(x))
tabs <- which(strsplit(x,"")[[1]] == "\t")
for (i in tabs) {
cols <- cumsum(widths)
widths[i] <- tabsize - (cols[i] - 1) %% tabsize
}
cols <- cumsum(widths)
start <- which(cols >= start)
if (!length(start))
return("")
start <- start[1]
stop <- which(cols <= stop)
if (length(stop)) {
stop <- stop[length(stop)]
substr(x, start, stop)
} else
""
}
getParseData <- function(x, includeText = NA) {
if (inherits(x, "srcfile"))
srcfile <- x
else
srcfile <- getSrcfile(x)
if (is.null(srcfile))
return(NULL)
else
data <- srcfile$parseData
if (!is.null(data)) {
tokens <- attr(data, "tokens")
data <- t(unclass(data))
colnames(data) <- c( "line1", "col1",
"line2", "col2",
"terminal", "token.num", "id", "parent" )
data <- data.frame(data[, -c(5,6), drop = FALSE], token = tokens,
terminal = as.logical(data[,"terminal"]),
text = attr(data, "text"),
stringsAsFactors = FALSE)
o <- order(data[,1], data[,2], -data[,3], -data[,4])
data <- data[o,]
rownames(data) <- data$id
attr(data, "srcfile") <- srcfile
if (isTRUE(includeText)) gettext <- which(!nzchar(data$text))
else if (is.na(includeText)) gettext <- which(!nzchar(data$text) & data$terminal)
else {
gettext <- integer(0)
data$text <- NULL
}
if (length(gettext))
data$text[gettext] <- getParseText(data, data$id[gettext])
}
data
}
getParseText <- function(parseData, id) {
srcfile <- attr(parseData, "srcfile")
d <- parseData[as.character(id),]
text <- d$text
if (is.null(text)) {
text <- character(nrow(d))
blank <- seq_along(text)
} else
blank <- which(!nzchar(text) | (d$token == "STR_CONST" & startsWith(text, "[")))
for (i in blank) {
lines <- getSrcLines(srcfile, d$line1[i], d$line2[i])
n <- length(lines)
lines[n] <- substr_with_tabs(lines[n], 1, d$col2[i])
lines[1] <- substr_with_tabs(lines[1], d$col1[i], Inf)
text[i] <- paste(lines, collapse="\n")
}
text
} |
plot_cps <- function(titan.out, taxa.dist = T, z.weights = T, taxaID = NULL,
cp.med = F, cp.trace = F, cp.hist = T, stacked = F, xlabel = "Environmental Gradient",
xmin = min(titan.out$env), xmax = max(titan.out$envcls) * 1.25,
tck = 0.025, bty = "u", ntick = 6, cex = 1.75, cex.axis = 1.75,
cex.leg = 1.5, cex.lab = 1.75, write = F, leg.x = 0.8, leg.y = 0.8,
leg = TRUE, ...) {
minSplt <- titan.out$arguments[[1]]
boot <- titan.out$arguments[[3]] > 0.5
imax <- titan.out$arguments[[5]] > 0.5
if (boot == F) {
stop("Bootstrap Output Required for this TITAN plot")
}
numUnit <- length(titan.out$env)
selTaxa <- which(titan.out$sppmax[, 16] > 0)
subsel1 <- titan.out$sppmax[selTaxa, 16] == 1
subsel2 <- titan.out$sppmax[selTaxa, 16] == 2
numTxa <- length(selTaxa)
cp.eden <- matrix(0, numTxa, numUnit)
cp.edenz <- matrix(0, numTxa, numUnit)
cp.eden.zmd <- matrix(0, numTxa, numUnit)
envseq <- seq(from = 0, to = ceiling(max(titan.out$srtEnv)), by = 0.5)
zmed <- titan.out$sppmax[selTaxa, 15]
for (i in 1:numTxa) {
fe <- round(sort(titan.out$metricArray[selTaxa[i], 2, ]), digits = 2)
dens <- table(fe)/length(fe)
edfe <- approxfun(unique(fe), dens)
for (j in 1:numUnit) {
if (is.na(edfe(titan.out$srtEnv[j]))) {
cp.eden[i, j] <- 0
cp.edenz[i, j] <- 0
} else {
cp.eden[i, j] <- edfe(titan.out$srtEnv[j])
cp.eden.zmd[i, j] <- edfe(titan.out$srtEnv[j]) * zmed[i]
}
}
}
if (taxa.dist) {
maxZmed <- apply(cp.eden.zmd, 1, which.max)
txaDens <- matrix(NA, nrow(cp.eden), 5)
colnames(txaDens) <- c("env.max.cp", "which.env", "EDF.max",
"z.median", "zEDF.max")
rownames(txaDens) <- rownames(titan.out$sppmax[selTaxa,
])
for (i in 1:nrow(cp.eden)) {
txaDens[i, 1] <- round((titan.out$srtEnv[maxZmed[i] - 1] + titan.out$srtEnv[maxZmed[i]])/2, digits = 2)
txaDens[i, 2] <- maxZmed[i]
txaDens[i, 3] <- round(cp.eden[i, maxZmed[i]], digits = 2)
txaDens[i, 4] <- round(zmed[i], digits = 2)
txaDens[i, 5] <- round(cp.eden.zmd[i, maxZmed[i]], digits = 2)
}
if (!(is.null(taxaID))) {
if (is.numeric(taxaID)) {
taxNum <- taxaID
} else {
taxNum <- which(taxaID == rownames(titan.out$sppmax))
}
if (titan.out$sppmax[taxNum, 16] < 1) {
stop("This taxon is either impure or unreliable, try a robust taxon")
}
tag <- rep(0, nrow(titan.out$sppmax))
tag[taxNum] <- 1
tagNum <- which(tag[selTaxa] > 0)
par(mar = c(5, 5, 4, 2), oma = c(0, 0, 0, 3))
plot(titan.out$env, titan.out$taxa[, taxNum], xlab = xlabel,
ylab = "Abundance", axes = T, col = "black", cex.axis = cex.axis,
cex = cex, cex.lab = cex.lab, tck = tck)
segments(titan.out$sppmax[taxNum, 8], max(titan.out$taxa[, taxNum], na.rm = T), titan.out$sppmax[taxNum, 12],
max(titan.out$taxa[, taxNum], na.rm = T), col = "red",
lwd = 2)
if (cp.med) {
cp.choice <- titan.out$sppmax[taxNum, 10]
} else {
if (imax) {
cp.choice <- titan.out$sppmax[taxNum, 1]
} else {
cp.choice <- titan.out$sppmax[taxNum, 2]
}
}
symbols(cp.choice, max(titan.out$taxa[, taxNum], na.rm = T),
circles = titan.out$sppmax[taxNum, 15], inches = 0.1,
add = TRUE, fg = "red", bg = "white", lwd = 2)
if (cp.trace) {
par(new = T)
plot(titan.out$srtEnv, c(rep(NA, minSplt), titan.out$ivzScores[nrow(titan.out$sppmax) +
taxNum, ], rep(NA, minSplt - 1)), type = "l",
axes = F, xlab = "", ylab = "", col = "red",
lty = 2, ylim = c(0, max(titan.out$ivzScores[nrow(titan.out$sppmax) +
taxNum, ], na.rm = T)))
par(new = T)
plot(titan.out$srtEnv, c(rep(NA, minSplt), titan.out$ivzScores[(nrow(titan.out$sppmax) * 2) + taxNum, ], rep(NA, minSplt - 1)), type = "l",
axes = F, xlab = "", ylab = "", col = "grey80",
lty = 2, ylim = c(0, max(titan.out$ivzScores[(nrow(titan.out$sppmax) *
2) + taxNum, ], na.rm = T)))
}
if (cp.hist) {
par(new = T)
plot(titan.out$srtEnv, cp.eden[tagNum, ], type = "h",
axes = F, xlab = "", ylab = "", col = "blue",
main = rownames(titan.out$sppmax)[taxNum], ylim = c(0,
max(cp.eden[tagNum, ], na.rm = T)))
axis(4, pretty(c(0, max(cp.eden[tagNum, ], na.rm = T)),
6), cex.axis = cex.axis, tck = tck, mgp = c(2.5,
0.5, 0))
mtext("Density", side = 4, line = 3, cex = cex.lab)
}
} else {
par(mfrow = c(ceiling(sqrt(length(selTaxa))), ceiling(sqrt(length(selTaxa)))),
mar = c(2, 2, 2, 2))
if (z.weights) {
if (sum(subsel1, na.rm = T) > 0) {
for (i in 1:nrow(cp.eden[subsel1, ])) {
plot(titan.out$srtEnv, cp.eden.zmd[subsel1, ][i, ], type = "h", axes = T, xlab = "",
ylab = "", col = "blue", main = rownames(titan.out$sppmax)[selTaxa[subsel1]][i],
ylim = c(0, 1.5))
}
}
if (sum(subsel2, na.rm = T) > 0) {
for (i in 1:nrow(cp.eden[subsel2, ])) {
plot(titan.out$srtEnv, cp.eden.zmd[subsel2, ][i, ], type = "h", axes = T, xlab = "",
ylab = "", col = "red", main = rownames(titan.out$sppmax)[selTaxa[subsel2]][i],
ylim = c(0, 1.5))
}
}
} else {
if (sum(subsel1, na.rm = T) > 0) {
for (i in 1:nrow(cp.eden[subsel1, ])) {
plot(titan.out$srtEnv, cp.eden[subsel1, ][i, ], type = "h", axes = T, xlab = "", ylab = "",
col = "blue", main = rownames(titan.out$sppmax)[selTaxa[subsel1]][i],
ylim = c(0, 0.3))
}
}
if (sum(subsel2, na.rm = T) > 0) {
for (i in 1:nrow(cp.eden[subsel2, ])) {
plot(titan.out$srtEnv, cp.eden[subsel2, ][i, ], type = "h", axes = T, xlab = "", ylab = "",
col = "red", main = rownames(titan.out$sppmax)[selTaxa[subsel2]][i],
ylim = c(0, 0.3))
}
}
}
if (sum(subsel1, na.rm = T) > 0 & write) {
print("Group 1 Pure and Reliable Taxa")
print(txaDens[subsel1, ])
}
if (sum(subsel2, na.rm = T) > 0 & write) {
print("Group 2 Pure and Reliable Taxa")
print(txaDens[subsel2, ])
}
}
} else {
sumDen1 <- colSums(cp.eden[subsel1, ], na.rm = T)
sumDen2 <- colSums(cp.eden[subsel2, ], na.rm = T)
sumDen <- colSums(cp.eden, na.rm = T)
sumDenzd1 <- colSums(cp.eden.zmd[subsel1, ], na.rm = T)
sumDenzd2 <- colSums(cp.eden.zmd[subsel2, ], na.rm = T)
sumDenzd <- colSums(cp.eden.zmd, na.rm = T)
sumTab <- matrix(NA, 3, 4)
rownames(sumTab) <- c("Group 1", "Group 2", "P&R Taxa")
colnames(sumTab) <- c("uw.env", "uw.max", "zw.env", "zw.max")
maxDen1 <- which.max(sumDen1)
maxDen2 <- which.max(sumDen2)
maxDen <- which.max(sumDen)
maxZden1 <- which.max(sumDenzd1)
maxZden2 <- which.max(sumDenzd2)
maxZden <- which.max(sumDenzd)
if (sum(subsel1, na.rm = T) > 0) {
if (maxDen1 > 1) {
sumTab[1, 1] <- round((titan.out$srtEnv[maxDen1 - 1] + titan.out$srtEnv[maxDen1])/2, digits = 2)
} else {
sumTab[1, 1] <- titan.out$srtEnv[maxDen1]
}
sumTab[1, 2] <- round(sumDen1[maxDen1], digits = 2)
if (maxDen1 > 1) {
sumTab[1, 3] <- round((titan.out$srtEnv[maxZden1 - 1] + titan.out$srtEnv[maxZden1])/2, digits = 2)
} else {
sumTab[1, 3] <- titan.out$srtEnv[maxZden1]
}
sumTab[1, 4] <- round(sumDenzd1[maxZden1], digits = 2)
}
if (sum(subsel2, na.rm = T) > 0) {
sumTab[2, 1] <- round((titan.out$srtEnv[maxDen2 - 1] + titan.out$srtEnv[maxDen2])/2, digits = 2)
sumTab[2, 2] <- round(sumDen2[maxDen2], digits = 2)
sumTab[2, 3] <- round((titan.out$srtEnv[maxZden2 - 1] + titan.out$srtEnv[maxZden2])/2, digits = 2)
sumTab[2, 4] <- round(sumDenzd2[maxZden2], digits = 2)
}
if (maxDen > 1) {
sumTab[3, 1] <- round((titan.out$srtEnv[maxDen - 1] + titan.out$srtEnv[maxDen])/2, digits = 2)
} else {
sumTab[3, 1] <- titan.out$srtEnv[maxDen]
}
sumTab[3, 2] <- round(sumDen[maxDen], digits = 2)
if (maxZden > 1) {
sumTab[3, 3] <- round((titan.out$srtEnv[maxZden - 1] + titan.out$srtEnv[maxZden])/2, digits = 2)
} else {
sumTab[3, 3] <- titan.out$srtEnv[maxZden]
}
sumTab[3, 4] <- round(sumDenzd[maxZden], digits = 2)
print("Summary of Summed Density Functions")
print(sumTab)
plot.stacked <- function(x, y, order.method = "as.is",
ylab = "", xlab = "", border = NULL, lwd = 0.5, col = c("blue",
"red"), ylim = NULL, ...) {
if (sum(y < 0) > 0)
warning("Y cannot contain negative numbers")
if (is.null(border))
border <- par("fg")
border <- as.vector(matrix(border, nrow = ncol(y),
ncol = 1))
col <- as.vector(matrix(col, nrow = ncol(y), ncol = 1))
lwd <- as.vector(matrix(lwd, nrow = ncol(y), ncol = 1))
if (order.method == "max") {
ord <- order(apply(y, 2, which.max))
y <- y[, ord]
col <- col[ord]
border <- border[ord]
}
top.old <- x * 0
polys <- vector(mode = "list", ncol(y))
for (i in seq(polys)) {
top.new <- top.old + y[, i]
polys[[i]] <- list(x = c(x, rev(x)), y = c(top.old,
rev(top.new)))
top.old <- top.new
}
if (is.null(ylim))
ylim <- range(sapply(polys, function(x) range(x$y,
na.rm = TRUE)), na.rm = TRUE)
plot(x, y[, 1], ylab = ylab, xlab = xlab, ylim = ylim,
t = "n", col = "blue", ...)
for (i in seq(polys)) {
polygon(polys[[i]], border = col[i], col = col[i],
lwd = lwd[i])
}
}
par(mar = c(5, 5, 4, 2), oma = c(0, 0, 0, 3))
if (z.weights) {
if (stacked) {
plot.stacked(titan.out$srtEnv, cbind(sumDenzd1,
sumDenzd2), xlab = xlabel, ylab = "Summed z-Weighted Probability Densities",
sub = "pure and reliable taxa only", xlim = c(xmin,
xmax), cex = 1.75, cex.axis = 1.75, tck = 0.025,
cex.lab = 1.5)
points(titan.out$srtEnv[which.max(sumDenzd1)],
max(sumDenzd1, na.rm = T), pch = 19, col = "blue")
points(titan.out$srtEnv[which.max(sumDenzd2)],
max(sumDenzd2, na.rm = T), pch = 19, col = "red")
} else {
plot(titan.out$srtEnv, sumDenzd, xlab = xlabel,
ylab = "Summed z-Weighted Probability Densities",
ty = "b", col = "gray", lty = 1, sub = "pure and reliable taxa only",
xlim = c(xmin, xmax), cex = 1.75, cex.axis = 1.75,
tck = 0.025, cex.lab = 1.75)
points(titan.out$srtEnv, sumDenzd2, ty = "b", col = "red",
pch = 19)
points(titan.out$srtEnv, sumDenzd1, ty = "b", col = "blue",
pch = 19)
}
} else {
if (stacked) {
plot.stacked(titan.out$srtEnv, cbind(sumDen1, sumDen2),
xlab = xlabel, ylab = "Summed Unweighted Probability Densities",
sub = "pure and reliable taxa only", xlim = c(xmin,
xmax), cex = 1.75, cex.axis = 1.75, tck = 0.025,
cex.lab = 1.5)
points(titan.out$srtEnv[which.max(sumDen1)], max(sumDen1,
na.rm = T), pch = 19, col = "blue")
points(titan.out$srtEnv[which.max(sumDen2)], max(sumDen2,
na.rm = T), pch = 19, col = "red")
} else {
plot(titan.out$srtEnv, sumDen, xlab = xlabel, ylab = "Summed Unweighted Probability Densities",
ty = "b", col = "gray", lty = 1, sub = "pure and reliable taxa only",
xlim = c(xmin, xmax), cex = 1.75, cex.axis = 1.75,
tck = 0.025, cex.lab = 1.75)
points(titan.out$srtEnv, sumDen2, ty = "b", col = "red",
pch = 19)
points(titan.out$srtEnv, sumDen1, ty = "b", col = "blue",
pch = 19)
}
}
}
if (leg) {
if (stacked) {
legend("topright", legend = c("z- max", "z+ max"),
col = c("blue", "red"), pch = 19)
} else {
if (!taxa.dist) {
legend("topright", legend = c("all z", "z-", "z+"),
col = c("gray", "blue", "red"), pch = 19)
}
}
}
}
plotCPs <- function(...) {
.Deprecated("plot_cps")
plot_cps(...)
} |
Delta.the.cc <- function(para, map, ref, Delta){
the <- para[map$the]
fx <- as.matrix(ref[, names(the), drop = FALSE])
fx * Delta
} |
source("ESEUR_config.r")
library("plyr")
params=read.csv(paste0(ESEUR_dir, "ecosystems/param-cnt.csv.xz"), as.is=TRUE)
pal_col=rainbow(3)
cbook=subset(params, source == "cbook")
cbook$int_p=round(cbook$percent)
cb_cp=rep(0:(nrow(cbook)-1), cbook$int_p)
embed=subset(params, source == "Embedded")
embed$int_p=round(embed$percent)
embed_pc=rep(0:(nrow(embed)-1), embed$int_p)
plot(params$params, params$percent, type="n",
xaxs="i", yaxs="i",
xlim=c(-0.05, 10),
xlab="Number of parameters", ylab="Function definitions (percentage)\n")
lines(embed$params, embed$percent, col=pal_col[2])
lines(cbook$params, cbook$percent, col=pal_col[2])
embed_pois=glm(embed_pc ~ 1, family=poisson(link="identity"))
points(0:8, dpois(0:8, coef(embed_pois)[1])*100, col=pal_col[1])
cbook_pois=glm(cb_cp ~ 1, family=poisson(link="identity"))
points(0:8, dpois(0:8, coef(cbook_pois)[1])*100, col=pal_col[3])
legend(x="topright", legend=c("C book", "Fitted model", "Embedded"), bty="n", fill=pal_col, cex=1.2) |
check_itemscale <- function(x) {
if (!inherits(x, "parameters_pca")) {
stop(insight::format_message("'x' must be an object of class 'parameters_pca', as returned by 'parameters::principal_components()'."), call. = FALSE)
}
insight::check_if_installed("parameters")
data_set <- attributes(x)$data_set
subscales <- parameters::closest_component(x)
out <- lapply(sort(unique(subscales)), function(.subscale) {
columns <- names(subscales)[subscales == .subscale]
items <- data_set[columns]
reliability <- item_reliability(items)
.item_discr <- reliability$item_discrimination
if (is.null(.item_discr)) .item_discr <- NA
.item_alpha <- reliability$alpha_if_deleted
if (is.null(.item_alpha)) .item_alpha <- NA
s_out <- data.frame(
Item = columns,
Missings = sapply(items, function(i) sum(is.na(i)) / nrow(items)),
Mean = sapply(items, mean, na.rm = TRUE),
SD = sapply(items, stats::sd, na.rm = TRUE),
Skewness = sapply(items, function(i) as.numeric(datawizard::skewness(i))),
"Difficulty" = item_difficulty(items)$difficulty,
"Discrimination" = .item_discr,
"alpha if deleted" = .item_alpha,
stringsAsFactors = FALSE,
check.names = FALSE
)
attr(s_out, "item_intercorrelation") <- item_intercor(items)
attr(s_out, "cronbachs_alpha") <- cronbachs_alpha(items)
s_out
})
class(out) <- unique(c("check_itemscale", class(out)))
out
} |
predictor <- function(tree, register) {
ti <- 1
while (tree[[ti]][["SL"]] != -1) {
if (register[tree[[ti]][["xi"]]] < as.data.frame(tree[[ti]][["s"]])) {
ti <- posIdNode(tree, tree[[ti]][["SL"]])
} else {
ti <- posIdNode(tree, tree[[ti]][["SR"]])
}
}
return(tree[[ti]][["y"]])
}
posIdNode <- function(tree, idNode) {
for (i in 1:length(tree)) {
if (tree[[i]][["id"]] == idNode) {
return(i)
}
}
return(-1)
} |
new_geodesic_path <- function(name, generator, frozen = NULL, ...) {
tries <- 1
tour_path <- function(current, data, ...) {
if (is.null(current)) {
return(generator(NULL, data, tries, ...))
}
dist <- 0
while (dist < 1e-3) {
if (name %in% c("guided", "frozen-guided")) tries <<- tries + 1
gen <- generator(current, data, tries, ...)
target <- gen$target
if (is.null(target)) {
return(NULL)
}
dist <- proj_dist(current, target)
if (dist < 1e-2) {
return(NULL)
}
cat("generation: dist = ", dist, "\n")
}
list(ingred = geodesic_path(current, target, frozen, ...), index = gen$index, tries = tries)
}
structure(
tour_path,
name = name,
class = c("tour_path", "function")
)
}
"print.tour_path" <- function(x, ...) {
cat("Tour path:", attr(x, "name"), "\n")
} |
NULL
expfpInit <- function(mCall, LHS, data, ...){
xy <- sortedXyData(mCall[["x"]], LHS, data)
if(nrow(xy) < 3){
stop("Too few distinct input values to fit an exponential-plateau.")
}
if(any(xy[,"y"] < 0)) stop("negative values in y are not allowed.")
xy1 <- xy[1:floor(nrow(xy)/2),]
fit <- try(stats::lm(log(xy1[,"y"]) ~ xy1[,"x"]), silent = TRUE)
if(class(fit) == "try-error"){
a <- xy1[1,"y"]
c <- (xy1[nrow(xy1),"y"] - xy1[1,"y"])/(xy1[nrow(xy1),"x"] - xy1[1,"x"])
}else{
a <- exp(coef(fit)[1])
c <- coef(fit)[2]
}
objfun <- function(cfs){
pred <- expfp(xy[,"x"], a=cfs[1], c=cfs[2], xs=cfs[3])
ans <- sum((xy[,"y"] - pred)^2)
ans
}
cfs <- c(a,c,mean(xy[,"x"]))
op <- try(stats::optim(cfs, objfun, method = "L-BFGS-B",
upper = c(Inf, Inf, max(xy[,"x"])),
lower = c(-Inf, -Inf, min(xy[,"x"]))), silent = TRUE)
if(class(op) != "try-error"){
a <- op$par[1]
c <- op$par[2]
xs <- op$par[3]
}else{
xs <- mean(xy[,"x"])
}
value <- c(a, c, xs)
names(value) <- mCall[c("a","c","xs")]
value
}
expfp <- function(x, a, c, xs){
.value <- (x < xs) * a * exp(c * x) + (x >= xs) * (a * exp(c * xs))
.exp1 <- ifelse(x < xs, exp(c * x), exp(c * xs))
.exp2 <- ifelse(x < xs, a * (exp(c * x) * x), a * (exp(c * xs) * xs))
.exp3 <- ifelse(x < xs, 0, a * (exp(c * xs) * c))
.actualArgs <- as.list(match.call()[c("a","c","xs")])
if (all(unlist(lapply(.actualArgs, is.name)))) {
.grad <- array(0, c(length(.value), 3L), list(NULL, c("a", "c", "xs")))
.grad[, "a"] <- .exp1
.grad[, "c"] <- .exp2
.grad[, "xs"] <- .exp3
dimnames(.grad) <- list(NULL, .actualArgs)
attr(.value, "gradient") <- .grad
}
.value
}
SSexpfp <- selfStart(expfp, initial = expfpInit, c("a", "c", "xs")) |
write_ref_output <- FALSE
test_that("kraken input works", {
res <- read_report("read_report/input/kraken-report.txt")
if (write_ref_output)
saveRDS(res, "read_report/ref_output/kraken-report-res.rds")
expect_equal(res, readRDS("read_report/ref_output/kraken-report-res.rds"))
})
test_that("krakenuniq input works", {
res <- read_report("read_report/input/krakenuniq-report.txt")
if (write_ref_output)
saveRDS(res, "read_report/ref_output/krakenuniq-report-res.rds")
expect_equal(res, readRDS("read_report/ref_output/krakenuniq-report-res.rds"))
})
test_that("kraken2uniq input works", {
res <- read_report("read_report/input/k2uniq-report.txt")
if (write_ref_output)
saveRDS(res, "read_report/ref_output/k2uniq-report-res.rds")
expect_equal(res, readRDS("read_report/ref_output/k2uniq-report-res.rds"))
})
test_that("metaphlan2 input works", {
res <- read_report("read_report/input/metaphlan2-report.txt")
if (write_ref_output)
saveRDS(res, "read_report/ref_output/metaphlan2-report-res.rds")
expect_equal(res, readRDS("read_report/ref_output/metaphlan2-report-res.rds"))
})
test_that("metaphlan3 input works", {
res <- read_report("read_report/input/metaphlan3-report.txt")
if (write_ref_output)
saveRDS(res, "read_report/ref_output/metaphlan3-report-res.rds")
expect_equal(res, readRDS("read_report/ref_output/metaphlan3-report-res.rds"))
}) |
set_parvec <- function(TXT2, partable, dp, cp, lv.x.wish, lv.names.x, target="jags"){
t1 <- paste(rep(" ", 2L), collapse="")
t2 <- paste(rep(" ", 4L), collapse="")
t3 <- paste(rep(" ", 6L), collapse="")
eqop <- ifelse(target == "stan", "=", "<-")
commop <- ifelse(target == "stan", "// ", "
eolop <- ifelse(target == "stan", ";", "")
TXT3 <- paste("\n", t1, commop, "Priors", sep="")
wishpars <- NULL
if(lv.x.wish & length(lv.names.x) > 1){
wishpars <- which(partable$lhs %in% lv.names.x &
partable$rhs %in% lv.names.x &
partable$op == "~~")
}
partable$freeparnums <- rep(0, length(partable$parnums))
parvecnum <- 0
for(i in 1:nrow(partable)){
miscignore <- (partable$mat[i] == "") | (i %in% wishpars)
eqpar <- which(partable$rhs == partable$plabel[i] &
partable$op == "==")
defeq <- partable$op[i] %in% c("==", ":=") &
grepl("\\+|-|/|\\*|\\(|\\)|\\^", partable$rhs[i])
compeq <- which((partable$lhs == partable$plabel[i] |
partable$lhs == partable$label[i]) &
partable$op %in% c("==", ":=") &
grepl("\\+|-|/|\\*|\\(|\\)|\\^", partable$rhs))
fixed <- partable$free[i] == 0 & partable$op[i] != ":="
if(length(eqpar) > 0 | defeq | length(compeq) > 0 | fixed |
miscignore){
next
} else {
parvecnum <- parvecnum + 1
partable$freeparnums[i] <- parvecnum
}
}
for(i in 1:nrow(partable)){
if((partable$mat[i] != "" & !(i %in% wishpars)) | partable$op[i] == ":="){
eqpar <- which(partable$rhs == partable$plabel[i] &
partable$op == "==")
defeq <- partable$op[i] %in% c("==", ":=") &
grepl("\\+|-|/|\\*|\\(|\\)|\\^", partable$rhs[i])
compeq <- which((partable$lhs == partable$plabel[i] |
partable$lhs == partable$label[i]) &
partable$op %in% c("==", ":=") &
grepl("\\+|-|/|\\*|\\(|\\)|\\^", partable$rhs))
if(grepl("rho", partable$id[i])){
rhoinf <- strsplit(partable$id[i], "[, \\[^\\]]+", perl=TRUE)
partable$mat[i] <- rhoinf[[1]][1]
partable$row[i] <- rhoinf[[1]][2]
partable$col[i] <- rhoinf[[1]][3]
}
TXT2 <- paste(TXT2, "\n", t1, partable$mat[i], "[",
partable$row[i], ",", partable$col[i],
",", partable$group[i], "] ", eqop,
" ", sep="")
if(grepl("rho", partable$id[i]) & partable$free[i] > 0){
TXT2 <- paste(TXT2, "-1 + 2*", sep="")
}
if(partable$free[i] == 0 & partable$op[i] != ":="){
if(is.na(partable$ustart[i])){
TXT2 <- paste(TXT2, partable$start[i], eolop,
sep="")
} else {
TXT2 <- paste(TXT2, partable$ustart[i], eolop,
sep="")
}
} else if(length(eqpar) > 0){
eqpar <- which(partable$plabel == partable$lhs[eqpar])
if(length(eqpar) > 1){
if(length(eqpar) > 2) stop("blavaan ERROR: problem with parameter equality constraints")
eqpar <- eqpar[which(partable$freeparnums[eqpar] > 0)]
}
if(partable$freeparnums[eqpar] == 0){
eqtxt <- paste(partable$mat[eqpar], "[",
partable$row[eqpar], ",",
partable$col[eqpar], ",",
partable$group[eqpar], "]",
eolop, sep="")
} else {
eqtxt <- paste("parvec[",
partable$freeparnums[eqpar],
"]", eolop, sep="")
}
vpri <- grepl("\\[var\\]", partable$prior[eqpar])
spri <- grepl("\\[sd\\]", partable$prior[eqpar])
if(!vpri & (grepl("theta", partable$mat[i]) | grepl("psi", partable$mat[i]))){
sq <- ifelse(spri, "2", "-1")
TXT2 <- paste(TXT2, "pow(", eqtxt, ",", sq,
")", eolop, sep="")
} else {
TXT2 <- paste(TXT2, eqtxt, sep="")
}
} else if(defeq | length(compeq) > 0){
if(length(compeq) == 0) compeq <- i
rhsvars <- all.vars(parse(file="",
text=partable$rhs[compeq]))
if(compeq == i){
pvnum <- match(rhsvars, partable$label)
} else {
pvnum <- match(rhsvars, partable$plabel)
if(is.na(pvnum[1])) pvnum <- match(rhsvars, partable$label)
}
rhstrans <- paste(partable$mat[pvnum], "[",
partable$row[pvnum], ",",
partable$col[pvnum], ",",
partable$group[pvnum], "]",
sep="")
oldjageq <- partable$rhs[compeq]
transtab <- as.list(rhstrans)
names(transtab) <- rhsvars
jagexpr <- parse(text=oldjageq)[[1]]
jageq <- do.call("substitute", list(jagexpr,
transtab))
jageq <- paste(deparse(jageq, width.cutoff = 500), collapse="")
jageq <- gsub('\"', '', jageq)
TXT2 <- paste(TXT2, jageq, eolop, sep="")
} else {
TXT3 <- paste(TXT3, "\n", t1, "parvec[",
partable$freeparnums[i], "]", sep="")
if(partable$prior[i] == ""){
if(partable$mat[i] == "lvrho"){
partype <- grep("rho", names(dp))
} else if(grepl("star", partable$mat[i])){
pname <- paste("i", strsplit(partable$mat[i], "star")[[1]][1], sep="")
partype <- grep(pname, names(dp))
} else {
partype <- grep(partable$mat[i], names(dp))
}
if(length(partype) > 1) partype <- partype[1]
partable$prior[i] <- dp[partype]
}
if(grepl(")[", partable$prior[i], fixed=TRUE)){
jagpri <- paste0(strsplit(partable$prior[i], ")[", fixed=TRUE)[[1]][1], ")")
} else {
jagpri <- partable$prior[i]
}
vpri <- grepl("\\[var\\]", partable$prior[i])
spri <- grepl("\\[sd\\]", partable$prior[i])
if(!vpri & (grepl("theta", partable$mat[i]) | grepl("psi", partable$mat[i]))){
sq <- ifelse(spri, "2", "-1")
TXT2 <- paste(TXT2, "pow(parvec[",
partable$freeparnums[i], "],", sq,
")", eolop, sep="")
} else {
TXT2 <- paste(TXT2, "parvec[",
partable$freeparnums[i],
"]", eolop, sep="")
}
TXT3 <- paste(TXT3, " ~ ", jagpri, eolop, sep="")
}
}
}
if(lv.x.wish & length(lv.names.x) > 1){
nlvx <- length(lv.names.x)
ngroups <- max(partable$group, na.rm = TRUE)
TXT3 <- paste(TXT3, "\n", t1, "for(k in 1:", ngroups,
") {\n", t2, "ibpsi[1:", nlvx, ",1:", nlvx,
",k] ~ dwish(iden,", nlvx+1, ")\n", sep="")
TXT3 <- paste(TXT3, t2, "bpsi[1:", nlvx, ",1:", nlvx, ",k] <- inverse(ibpsi[1:",
nlvx, ",1:", nlvx, ",k])\n", t1, "}\n", sep="")
for(i in 1:length(wishpars)){
tmppar <- wishpars[i]
wishrow <- which(lv.names.x == partable$lhs[tmppar])
wishcol <- which(lv.names.x == partable$rhs[tmppar])
partable$prior[tmppar] <- dp[["ibpsi"]]
TXT2 <- paste(TXT2, "\n", t1, partable$mat[tmppar], "[",
partable$row[tmppar], ",", partable$col[tmppar],
",", partable$group[tmppar], "] ", eqop,
" bpsi[", wishrow, ",", wishcol, ",",
partable$group[tmppar], "]", eolop, sep="")
}
}
covs <- unique(partable$lhs[grep(".phant", partable$lhs)])
if(length(covs) > 0){
TXT2 <- paste(TXT2, "\n\n", t1, commop, "Inferential covariances", sep="")
for(i in 1:length(covs)){
for(k in 1:max(partable$group)){
varlocs <- which(((partable$lhs == covs[i] &
partable$op == "=~") |
(partable$rhs == covs[i] &
partable$op == "~")) &
partable$group == k)
vartxt <- "star"
vars <- partable$rhs[varlocs]
lhsvars <- grepl(".phant", vars)
if(any(lhsvars)){
vars[lhsvars] <- partable$lhs[varlocs[lhsvars]]
}
if(length(varlocs) == 0){
varlocs <- which(partable$rhs == covs[i] &
partable$op == "~" &
partable$group == k)
vars <- partable$lhs[varlocs]
}
var1 <- which(partable$lhs == vars[1] &
partable$lhs == partable$rhs &
partable$group == partable$group[varlocs[1]] &
grepl(vartxt, partable$mat))
var2 <- which(partable$lhs == vars[2] &
partable$lhs == partable$rhs &
partable$group == partable$group[varlocs[1]] &
grepl(vartxt, partable$mat))
matname <- ifelse(grepl("theta", partable$mat[var1]), "theta", "psi")
phpars <- which((partable$lhs == covs[i] |
partable$rhs == covs[i]) &
partable$group == k)
if(length(phpars) == 1){
phpars <- which(partable$rhs == covs[i] &
partable$group == k)
}
TXT2 <- paste(TXT2, "\n", t1, matname, "[", partable$row[var1],
",", partable$row[var2], ",", partable$group[varlocs[1]], "] ", eqop, " ",
partable$mat[phpars[1]], "[", partable$row[phpars[1]], ",",
partable$col[phpars[1]], ",", partable$group[phpars[1]], "]*",
partable$mat[phpars[2]], "[", partable$row[phpars[2]], ",",
partable$col[phpars[2]], ",", partable$group[phpars[2]], "]*",
partable$mat[phpars[3]], "[", partable$row[phpars[3]], ",",
partable$col[phpars[3]], ",", partable$group[phpars[3]], "]",
eolop, sep="")
}
}
TXT2 <- paste(TXT2, "\n", sep="")
}
list(TXT2 = TXT2, TXT3 = TXT3, partable = partable)
} |
do.crda <- function(X,ndim=2,type=c("proportion",0.1),symmetric="union",weight=TRUE,
lambda=1.0,alpha=1.0,maxiter=1000,tolerance=1e-6){
vlnum = 1e+10
aux.typecheck(X)
ndim = as.integer(ndim)
if(!check_NumMM(ndim,1,ncol(X),compact=FALSE)){stop("* do.crda : 'ndim' is a positive integer in (1,
lambda = as.double(lambda)
if(!check_NumMM(lambda,0,vlnum,compact=FALSE)){stop("* do.crda : 'lambda' should be a positive real number.")}
alpha = as.double(alpha)
if(!check_NumMM(alpha,0,vlnum,compact=FALSE)){stop("* do.crda : 'alpha' should be a positive real number.")}
maxiter = as.integer(maxiter)
if(!check_NumMM(maxiter,1,vlnum,compact=FALSE)){stop("* do.crda : 'maxiter' should be a not-so-small positive integer.")}
tolerance = as.double(tolerance)
if(!check_NumMM(alpha,0,vlnum,compact=FALSE)){stop("* do.crda : 'tolerance' should be a positive real number.")}
nbdtype = type
nbdsymmetric = symmetric
if (!is.element(nbdsymmetric,c("union","intersect","asymmetric"))){
stop("* do.crda : 'symmetric' should have one of three values.")
}
algweight = weight
if (!is.logical(algweight)){
stop("* do.crda : 'weight' should be a logical value.")
}
nbdstruct = aux.graphnbd(X,method="euclidean",
type=nbdtype,symmetric=nbdsymmetric)
D = nbdstruct$dist
Dmask = nbdstruct$mask
nD = ncol(D)
if (algweight){
wD = Dmask*D
idnan = is.na(wD)
wD[idnan] = 0
} else {
wD = matrix(as.double(Dmask),nrow=nD)
}
Xij = aux.shortestpath(wD)
Yinit = do.pca(X, ndim=ndim)$Y
vecselector = as.vector(sample(0:(nrow(X)-1), maxiter, replace=TRUE))
Youtput = method_crca(Xij,Yinit,lambda,alpha,maxiter,tolerance,vecselector)
trfinfo = list()
trfinfo$type = "null"
trfinfo$algtype = "nonlinear"
result = list()
result$Y = Youtput$Y
result$niter = Youtput$niter
result$trfinfo = trfinfo
return(result)
} |
remove_prefix <- function(data, prefices, sep = ".") {
for (prefix in prefices) {
prefix <- paste0(prefix, sep)
names(data) %<>% gsub(prefix, "", .)
}
data
} |
ck_conv_vox = function(data,message){
if(missing(message)) message = TRUE
if(!(is.data.frame(data))) stop("data must be a data.frame or a data.table")
if(ncol(data) > 4){
if(message) print("NOTE: data contain more than 3 columns, three first used")
}
if(ncol(data) < 4){
stop("data must contain 4 columns, x, y, z and number of points")
}
dfr=FALSE
if(!data.table::is.data.table(data)) dfr = TRUE
data=data.table::data.table(data[,1:4])
data.table::setnames(data,c("x","y","z","npts"))
if(!(all(sapply(data[,1:3],class)=="numeric") & (all(sapply(data[,4],class)=="integer")|all(sapply(data[,4],class)=="numeric")) )){
stop("All the fields of the data must be numeric")
}
if(any(is.na(data))&message) warning("data contains missing values.")
invisible(list(data=data,dfr=dfr))
} |
test_that("check class and length of output", {
testthat::skip_on_cran()
local_edition(3)
data(ExampleData.DeValues, envir = environment())
temp <- expect_s4_class(calc_FiniteMixture(
ExampleData.DeValues$CA1,
sigmab = 0.2,
n.components = 2,
grain.probability = TRUE,
verbose = TRUE), "RLum.Results")
expect_equal(length(temp), 10)
results <- get_RLum(temp)
expect_equal(results$de[1], 31.5299)
expect_equal(results$de[2], 72.0333)
expect_equal(results$de_err[1], 3.6387)
expect_equal(results$de_err[2], 2.4082)
expect_equal(results$proportion[1], 0.1096)
expect_equal(results$proportion[2], 0.8904)
expect_s4_class(calc_FiniteMixture(
ExampleData.DeValues$CA1,
sigmab = 0.2,
n.components = 2:3,
grain.probability = TRUE,
verbose = FALSE), "RLum.Results")
}) |
assoTest <- function(Dx, Dy, hapMat, nperm, method, xlab = "", ylab = "", main = ""){
n = length(Dy)
assoStats = vector(length = n, mode = "list")
permStatMat = matrix(NA, nrow = n, ncol = nperm)
for(i in 1:n){
assoStats[[i]] = performTest(Dx = Dx, Dy = Dy[[i]], testname = method, nperm = nperm)
permStatMat[i, ] = assoStats[[i]]$permStats
}
trueStats = rep(NA, length(assoStats))
for(j in 1:length(assoStats)){
trueStats[j] = assoStats[[j]]$Stat
}
if( nperm != 0){
mar_pval = rep(NA, length(assoStats))
for(k in 1:length(assoStats)){
mar_pval[k] = assoStats[[k]]$pValue
}
}else{
mar_pval = NA
}
omPvalue = (sum(apply(permStatMat, 2, max) >= max(trueStats))+1)/(nperm + 1)
plt <- plot(hapMat$posns, trueStats, xlab = xlab, ylab = ylab, main = main )
return(list(plt, Stats = trueStats, OmPval = omPvalue, mPval = mar_pval))
}
performTest <- function(Dx, Dy, testname, nperm){
if(testname == "HHG"){
return( HHGtest(Dx = Dx, Dy = Dy, nperm = nperm))
}
if(testname == "dCor"){
return( dCorTest(Dx = Dx, Dy = Dy, nperm = nperm))
}
if(testname == "Mantel"){
return(MantelTest(Dx = Dx, Dy = Dy, nperm = nperm))
}
if(testname == "RV"){
return(RVtest(Dx = Dx, Dy = Dy, nperm = nperm))
}
} |
test.millsR <- function() {
xVals <- 1:5
yVals <- millsR(xVals)
yReqd <- c(0.65568, 0.42137, 0.30459, 0.23665, 0.19281)
tol <- 0.001
checkEquals(yReqd, yVals, tol = tol)
tol <- 10^(-14)
xVals <- (1:10)*10^7
yVals <- millsR(xVals)
yReqd <-
c(1.00090856345226e-07, 4.99371810711756e-08,
3.43212891632624e-08, 2.51099915574398e-08, 1.95556810878505e-08,
1.95556810878505e-08, 1.52299797447126e-08, 1.52299797447126e-08,
1.52299797447126e-08, 1.52299797447126e-08)
checkEquals((yVals - yReqd)/yReqd, rep(0, length(yVals)), tol = tol)
checkEquals(millsR(1:5, log = TRUE), log(millsR(1:5)), tol = tol)
} |
test_that("number format works correctly", {
expect_equal(number(123.45, accuracy = 1), "123")
expect_equal(number(123.45, accuracy = 10), "120")
expect_equal(number(123.45, accuracy = .25), "123.5")
expect_equal(
number(12345, big.mark = ","),
"12,345"
)
expect_equal(
number(12.3, decimal.mark = ",", accuracy = .1),
"12,3"
)
expect_equal(
number(1.234, scale = 100),
"123"
)
expect_equal(
number(123, prefix = "pre", suffix = "post"),
"pre123post"
)
expect_equal(number(c(1, 23)), c("1", "23"))
expect_equal(number(c(1, 23), trim = FALSE), c(" 1", "23"))
})
test_that("number_format works with Inf", {
cust <- number_format(suffix = "suff", accuracy = NULL)
expect_equal(cust(c(Inf, -Inf)), c("Inf", "-Inf"))
})
test_that("number preserves names", {
expect_named(number(c(a = 1)), "a")
})
test_that("comma format always adds commas", {
expect_equal(comma(1e3), "1,000")
expect_equal(comma(1e6), "1,000,000")
expect_equal(comma(1e9), "1,000,000,000")
})
test_that("comma preserves names", {
expect_named(comma(c(a = 1)), "a")
})
test_that("formatters don't add extra spaces", {
has_space <- function(x) any(grepl("\\s", x))
x <- 10^c(-1, 0, 1, 3, 6, 9)
expect_false(has_space(number(x, big.mark = ",")))
expect_false(has_space(comma(x)))
expect_false(has_space(dollar(x)))
expect_false(has_space(percent(x, big.mark = ",")))
expect_false(has_space(scientific(x)))
})
test_that("formats work with 0 length input", {
x <- numeric()
expected <- character()
expect_identical(number(x), expected)
expect_identical(comma(x), expected)
expect_identical(dollar(x), expected)
expect_identical(percent(x), expected)
expect_identical(scientific(x), expected)
expect_identical(comma_format()(x), expected)
expect_identical(date_format()(as.Date(character(0))), expected)
expect_identical(dollar_format()(x), expected)
expect_identical(parse_format()(x), expression())
expect_identical(parse_format()(character()), expression())
expect_identical(percent_format()(x), expected)
expect_identical(scientific_format()(x), expected)
expect_identical(trans_format(identity)(x), expected)
})
test_that("precision rounds large numbers appropriately", {
x <- c(0, 0.025)
expect_equal(precision(x), 0.001)
expect_equal(precision(x * 10), 0.01)
expect_equal(precision(x * 100), 0.1)
expect_equal(precision(x * 1000), 1)
expect_equal(precision(x * 10000), 1)
})
test_that("precision handles duplicate values", {
expect_equal(precision(c(0, 0, 0.025)), 0.001)
expect_equal(precision(c(Inf, 0.1, 0.2, Inf)), 0.01)
})
test_that("precision ignores Inf and NA", {
expect_equal(precision(c(NA, Inf, -Inf)), 1)
expect_equal(precision(c(1, NA)), 1)
}) |
boot.senv <- function (X, Y, u, B)
{
X <- as.matrix(X)
a <- dim(Y)
n <- a[1]
r <- a[2]
p <- ncol(X)
fit <- senv(X, Y, u, asy = F)
Yfit <- matrix(1, n, 1) %*% t(fit$mu) + X %*% t(fit$beta)
res <- Y - Yfit
bootenv <- function(i) {
res.boot <- res[sample(1:n, n, replace = T), ]
Y.boot <- Yfit + res.boot
return(c(senv(X, Y.boot, u, asy = F)$beta))
}
bootbeta <- lapply(1:B, function(i) bootenv(i))
bootbeta <- matrix(unlist(bootbeta), nrow = B, byrow = TRUE)
bootse <- matrix(apply(bootbeta, 2, stats::sd), nrow = r)
return(bootse)
} |
"toy_wide_censN" |
lsm_l_area_cv <- function(landscape, directions = 8) {
landscape <- landscape_as_list(landscape)
result <- lapply(X = landscape,
FUN = lsm_l_area_cv_calc,
directions = directions)
layer <- rep(seq_along(result),
vapply(result, nrow, FUN.VALUE = integer(1)))
result <- do.call(rbind, result)
tibble::add_column(result, layer, .before = TRUE)
}
lsm_l_area_cv_calc <- function(landscape, directions, resolution = NULL){
area_patch <- lsm_p_area_calc(landscape,
directions = directions,
resolution = resolution)
if (all(is.na(area_patch$value))) {
return(tibble::tibble(level = "landscape",
class = as.integer(NA),
id = as.integer(NA),
metric = "area_cv",
value = as.double(NA)))
}
area_cv <- raster::cv(area_patch$value)
return(tibble::tibble(level = "landscape",
class = as.integer(NA),
id = as.integer(NA),
metric = "area_cv",
value = as.double(area_cv)))
} |
.checkMetricInvariants <- function(metric) {
checkTrue(metric >= 0)
checkTrue(metric <= 1)
}
TestKSDCC <- function() {
x <- rexp(100)
h1 <- hist(x, plot=FALSE)
h2 <- hist(x, breaks=seq(0, round(max(x) + 1), by=0.1), plot=FALSE)
ksdcc.1 <- KSDCC(h1)
ksdcc.2 <- KSDCC(h2)
.checkMetricInvariants(ksdcc.1)
.checkMetricInvariants(ksdcc.2)
checkTrue(ksdcc.1 >= ksdcc.2)
x1.min <- rep(head(h1$breaks, -1), h1$counts)
x1.max <- rep(tail(h1$breaks, -1), h1$counts)
checkEquals(unname(ks.test(x1.min, x1.max, exact=F)$statistic), KSDCC(h1))
x2.min <- rep(head(h2$breaks, -1), h2$counts)
x2.max <- rep(tail(h2$breaks, -1), h2$counts)
checkEquals(unname(ks.test(x2.min, x2.max, exact=F)$statistic), KSDCC(h2))
}
TestEMDCC <- function() {
set.seed(0)
x <- rexp(100)
h1 <- hist(x, plot=FALSE)
h2 <- hist(x, breaks=seq(0, round(max(x) + 1), by=0.1), plot=FALSE)
emdcc.1 <- EMDCC(h1)
emdcc.2 <- EMDCC(h2)
.checkMetricInvariants(emdcc.1)
.checkMetricInvariants(emdcc.2)
checkTrue(emdcc.1 >= emdcc.2)
if (require(emdist)) {
MinEcdf <- HistToEcdf(h1, f=0)
MaxEcdf <- HistToEcdf(h1, f=1)
A1 <- matrix(c(rep(1, length(h1$counts)),
h1$mids, MaxEcdf(tail(knots(MinEcdf), -1))), ncol=3)
A2 <- matrix(c(rep(1, length(h1$counts)),
h1$mids, MinEcdf(head(knots(MinEcdf), -1))), ncol=3)
checkEquals(emd(A1, A2), emdcc.1, tol=2^-23)
}
} |
getNote <- function(note) {
paste(scan(note, '', sep = '\n', quiet = TRUE), collapse = '\n')
}
getDose <- function(note, ...) {
d <- medExtractR::medExtractR(getNote(note), ...)
if(length(d) == 1 && is.na(d)) return(NULL)
d[,'filename'] <- basename(note)
d <- d[, c('filename', 'entity', 'expr', 'pos')]
return(d)
} |
library("zlog")
albumin <- c(42, 34, 38, 43, 50, 42, 27, 31, 24)
z(albumin, limits = c(35, 52))
zlog(albumin, limits = c(35, 52))
izlog(zlog(albumin, limits = c(35, 52)), limits = c(35, 52))
z <- -10:10
oldpar <- par(mar = c(0, 0, 0, 0), oma = c(0, 0, 0, 0))
image(matrix(z, ncol = 1), col = zcol(z), axes = FALSE)
text(seq(0, 1, length.out=length(z)), 0, label = z)
par(oldpar)
bilirubin <- c(11, 9, 2, 5, 22, 42, 37, 200, 20)
zloga <- zlog(albumin, limits = c(35, 52))
zlogb <- zlog(bilirubin, limits = c(2, 21))
d <- data.frame(
Category = c(
rep(c(
"blood donor",
"hepatitis without cirrhosis",
"hepatitis with cirrhosis"
),
each = 3
)
),
albumin = albumin,
zloga = zloga,
bilirubin = bilirubin,
zlogb = zlogb
)
d$albumin <- kableExtra::cell_spec(
d$albumin, background = zcol(zloga), align = "right"
)
d$bilirubin <- kableExtra::cell_spec(
d$bilirubin, background = zcol(zlogb), align = "right"
)
kableExtra::kable_classic(
kableExtra::kbl(
d,
col.names = c(
"Category",
"albumin", "zlog(albumin)", "bilirubin", "zlog(bilirubin)"
),
digits = 2,
escape = FALSE,
caption = paste0(
"Table reproduced from @hoffmann2017, Table 2, limits used: ",
"albumin 35-52 g/l, bilirubin 2-21 µmol/l."
)
),
"basic"
)
reference_limits(albumin)
reference_limits(albumin, probs = c(0.05, 0.95))
exp(reference_limits(log(albumin)))
reference <- data.frame(
param = c("albumin", rep("bilirubin", 4)),
age = c(0, 1, 2, 3, 7),
sex = "both",
units = c("g/l", rep("µmol/l", 4)),
lower = c(35, rep(NA, 4)),
upper = c(52, 5, 8, 13, 18)
)
knitr::kable(reference)
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference[reference$param == "albumin",]
)
lookup_limits(
age = 18 * 365.25,
sex = "female",
table = reference
)
lookup_limits(
age = 0:8,
sex = rep(c("female", "male"), 5:4),
table = reference[reference$param == "bilirubin",]
)
set_missing_limits(reference)
set_missing_limits(reference, fraction = c(0.2, 5))
x <- data.frame(
age = c(40, 50),
sex = c("female", "male"),
albumin = c(42, NA)
)
x
z_df(impute_df(x, reference, method = "mean"), reference)
zlog_df(impute_df(x, reference), reference)
library("survival")
data("pbc")
labs <- c(
"bili", "chol", "albumin", "copper", "alk.phos", "ast", "trig",
"platelet", "protime"
)
pbc <- pbc[, c("age", "sex", labs)]
knitr::kable(head(pbc), digits = 1)
param <- rep(labs, ifelse(labs %in% c("copper", "ast"), 2, 1))
sex <- rep_len("both", length(param))
sex[param %in% c("copper", "ast")] <- c("f", "m")
reference <- data.frame(
param = param, age = 0, sex = sex, lower = NA, upper = NA
)
for (i in seq_len(nrow(reference))) {
reference[i, c("lower", "upper")] <-
if (reference$sex[i] == "both")
reference_limits(pbc[reference$param[i]])
else
reference_limits(pbc[pbc$sex == reference$sex[i], reference$param[i]])
}
knitr::kable(reference)
pbc[c(6, 14),]
pbc <- impute_df(pbc, reference)
pbc[c(6, 14),]
pbc <- zlog_df(pbc, reference)
pbctbl <- head(pbc, n = 25)
pbctbl[labs] <- lapply(labs, function(l) {
kableExtra::cell_spec(
sprintf("%.1f", unlist(pbctbl[l])),
background = zcol(unlist(pbctbl[l])),
align = "right"
)
})
kableExtra::kable_classic(
kableExtra::kbl(pbctbl, digits = 1, escape = FALSE),
"basic"
)
sessionInfo() |
library(testthat)
expect_plots_same_message <- "The TeX expression %s should %s render the same as the given expression.
Compare:
* TeX: %s
* Expression: %s
Note: TeX string evaluated to %s.
"
expect_renders_same <- function(object, expected_expression) {
expected_expression <- as.expression(rlang::enexpr(expected_expression))
.expect_renders(object, expected_expression, negate=FALSE)
}
expect_renders_different <- function(object, expected_expression) {
expected_expression <- as.expression(rlang::enexpr(expected_expression))
.expect_renders(object, expected_expression, negate=TRUE)
}
.expect_renders <- function(object, expected_expression, negate) {
act <- testthat::quasi_label(rlang::enquo(object), arg="object")
plot_md5 <- function(expr, prefix) {
fn <- tempfile(pattern = prefix, fileext = ".png")
png(fn, 640, 480, res=150)
plot(expr, main=act$val)
dev.off()
tools::md5sum(fn)
}
if (is.character(act$val)) {
result_expression <- TeX(act$val)
} else{
result_expression <- act$val
}
act$md5_1 <- plot_md5(result_expression, "latex2exp_")
act$md5_2 <- plot_md5(expected_expression, "expression_")
message <- sprintf(expect_plots_same_message,
act$val,
if (!negate) "" else "not",
names(act$md5_1),
names(act$md5_2),
result_expression)
comparison_successful <- identical(unname(act$md5_1), unname(act$md5_2))
if (negate) {
comparison_successful <- !comparison_successful
}
if (!comparison_successful && interactive()) {
plot(expected_expression, main="Expected")
plot(result_expression, main="Result")
}
expect(comparison_successful,
message)
invisible(act$val)
} |
CPP.AHP.Unif = function (n,list,x){
min = apply(simplify2array(list), 1:2, min)
max = apply(simplify2array(list), 1:2, max)
c=nrow(min)
d = c^2
simu = vector("list", d)
k=1
for (i in 1:c)
{
for (j in 1:c)
{
simu[[k]] <- runif(n,min[i,j],max[i,j])
k = k+1
}}
un = unlist(simu)
abc = matrix(un,c^2,n,byrow=TRUE)
m = vector("list", n)
weight = vector("list", n)
CI = vector("list", n)
for (a in 1:n)
{
m[[a]] = as.vector(abc[,a])
matrix = matrix(m[[a]],nrow = c,ncol = c, byrow = TRUE)
for (i in 1:c)
{
weight[[a]][i] <- prod(matrix[i,])^(1/c)
}
temp_sum <- sum(weight[[a]])
weight[[a]] <- weight[[a]]/temp_sum
lambda_max <- Re(eigen(matrix)$values[1])
CI[[a]] <- (lambda_max-c)/(c-1)
}
RI = c(0,0,0.58,0.9,1.12,1.24,1.32,1.41,1.45,1.49)
min = which.min(CI)
index = CI[[min]]/RI[c]
w.min = weight[[min]]
w = w.min
y = t(as.matrix(apply(x,2,sum)))
dadosn=x
for (j in 1:ncol(x))
{
for (i in 1:nrow(x))
{
dadosn[i,j] = x[i,j]/y[j]
}}
dadosn = replace(dadosn, dadosn == 0, 0.0000000001)
x = dadosn
PMax = x
mat = x
sd = apply(x,2,sd)
for (j in 1:ncol(x))
{
for (i in 1:nrow(x))
{
PMax[i,j] = (integrate(Vectorize(function(x) {prod(pnorm(x,mat[,j][-i],sd[j]))*dnorm(x,mat[,j][[i]],sd[j])}),-2,2)) $value
}}
PMax = PMax[,]
saw = PMax%*%w
rank = rank(-saw)
SAW = cbind(saw, rank)
colnames(SAW) = c("SAW","Rank")
Result = list(Weights.AHP=w, PMax=PMax, CPP=SAW)
Result
} |
compPowerRespDetection<-function(bkgLevel, respLevel, numCats, numCatsWithResp,
normDistribution=FALSE, showProgress=FALSE,
numTrialsPerCat=15, numBootIters=1000,
numRuns=1000, alpha=0.05) {
if (numCatsWithResp>numCats) {
stop("number of categories with response must be less then number of categories")
}
responseLevels<-c(rep(respLevel,numCatsWithResp),
rep(bkgLevel,numCats-numCatsWithResp))
numSig<-0
for (i in 1:numRuns) {
if (showProgress) print(i)
if (normDistribution) sim1<-simNormCatResp(bkgLevel,responseLevels,numTrialsPerCat)
else sim1<-simCatResp(bkgLevel,responseLevels,numTrialsPerCat)
sigLevel<-testCatEffectBoot(sim1,numBootIters,testFnc=sumSqCat,backMean=bkgLevel)
if (sigLevel<alpha) numSig<-numSig+1
}
numSig
} |
truncHist <-
function(x, xmin=NULL, xmax=NULL, trim=0.025, main=NULL, xlab="x", ...) {
if (!is.numeric(x)) stop("'x' must be numeric.")
if (length(xmin)>1 | (!is.numeric(xmin) & !is.null(xmin))) stop("'xmin' must be scalar numeric or NULL.")
if (length(xmax)>1 | (!is.numeric(xmax) & !is.null(xmax))) stop("'xmax' must be scalar numeric or NULL.")
if (length(trim)!=1 | !is.numeric(trim)) stop("'trim' must be scalar numeric between 0 and 0.5.")
if (trim<0 | trim>0.5) stop("'trim' must be scalar numeric between 0 and 0.5.")
if ( (is.null(xmin)& !is.null(xmax)) || (!is.null(xmin)&is.null(xmax)))
stop("'xmin' and 'xmax' must both be NULL or must both be nonNULL.")
if ( !is.null(main) & !is.character(main) ) stop("'main' must be character or NULL.")
if ( !is.character(xlab) ) stop("'xlab' must be character.")
if (is.null(xmin)&is.null(xmax))
y <- sort(x)[(length(x)*trim): (length(x)*(1-trim))]
if (!is.null(xmin)&!is.null(xmax)) {
if (xmin >= xmax) stop("'xmin' cannot be as large as or larger than 'xmax'.")
y <- x[ x>xmin & x<xmax ] }
if ( is.null(main) ) {
main = paste("Truncated Histogram of", xlab)
if (trim<=0) main = paste("Histogram of", xlab) }
hist(y, main=main, xlab=xlab, ...)
} |
mape <- function(y, yhat) {
if(class(y) != 'integer' && class(y) != 'numeric') {
stop('Invalid input: y should be numeric or integer vector representing a linear response')
} else if(class(yhat) != 'integer' && class(yhat) != 'numeric') {
stop('Invalid input: yhat should be numeric or integer vector of predicted linear response')
} else if(length(y) != length(yhat)) {
stop('Invalid input: vectors y and yhat should have the same length')
} else {
mape <- mean(abs((y - yhat)/y))
return(mape)
}
} |
prepare.array = function(data, x, splines,
m = 2, sparse = TRUE, ...) {
arglist = list(...)
arg_check_data(data)
if (missing(x)) {
evalargs = default.evalargs(data)
}
arg_check_data_x(data, x)
if (missing(splines)) {
splines = default.splines(x)
}
arg_check_x_splines(x, splines)
d = length(x)
if (!is.null(arglist$assembled)) {
assembled = arglist$assembled
} else {
assembled = assemble(splines, x = x, m = m,
sparse = sparse, ...)
}
A = lapply(assembled, getElement, name = "A")
Ytilde = rh.seq(A, data, transpose = TRUE)
structure(list(
Ytilde = Ytilde,
sum_ysq = sum(data^2),
n = dim(data),
s = lapply(assembled, getElement, name = "s"),
B = lapply(assembled, getElement, name = "B"),
Q = lapply(assembled, getElement, name = "Q"),
A = lapply(assembled, getElement, name = "A"),
U = lapply(assembled, getElement, name = "U"),
loglambda = rep(0, d),
x = x
), class = "prepared_array")
} |
`is.Stem.Model` <-
function(x) inherits(x, "Stem.Model") |
library(hexSticker)
library(ggseg)
library(ggplot2)
devtools::load_all(".")
atlas <- jhu
pkgname <- "ggsegJHU"
p <- ggseg(atlas = atlas,
view = "lower axial",
show.legend = FALSE,
colour = "grey30",
size = .2,
mapping = aes(fill = region)) +
scale_fill_brain2(palette = atlas$palette) +
theme_void() +
theme_transparent()
sticker(p,
package = pkgname,
filename="man/figures/logo.svg",
s_y = 1.2,
s_x = 1,
s_width = 1,
s_height = 1,
p_family = "mono",
p_size = 5,
p_color = "grey30",
p_y = .6,
h_fill = "white",
h_color = "grey30"
)
sticker(p,
package = pkgname,
filename="man/figures/logo.png",
s_y = 1.2,
s_x = 1,
s_width = 1,
s_height = 1,
p_family = "mono",
p_size = 5,
p_color = "grey30",
p_y = .6,
h_fill = "white",
h_color = "grey30"
)
pkgdown::build_favicons() |
fixDur <- function( data, fixTime, passes, AOI = NULL )
{
if( is_tibble( data ) )
{
data <- as.data.frame( data )
}
fixDur.inputChecks( data = data, fixTime = fixTime, passes = passes, AOI = AOI )
if( !is.null( AOI ) )
{
AOI <- data[ , AOI ]
if( is.factor( AOI ) )
{
AOI <- data.frame( AOI = levels( AOI ),
stringsAsFactors = F )
} else AOI <- data.frame( AOI = unique( AOI ), stringsAsFactors = F )
}
if( any( data[ , passes] == 0 ) )
data0 <- data[ data[ , passes] == 0, ]
data <- data[ data[ , passes] != 0, ]
if( !is.character( data[ , passes ] ) )
data[ , passes ] <- as.character( data[ , passes ] )
splitted_pass <- transpose(
as.data.frame(
strsplit( data[, passes], split = "_", fixed = T )
)
)
if( ncol( splitted_pass ) < 2 )
{
result <- aggregate( list( duration = data[ , fixTime ] ),
by = list( AOI = splitted_pass[ , 1 ]),
FUN = sum )
if( exists( "data0" ) )
{
result0 <- sum( data0[ , fixTime ] )
result <- rbind( data.frame( AOI = 0, duration = result0 ),
result )
}
}else
{
result <- aggregate( list( duration = data[ , fixTime ] ),
by = list( AOI = splitted_pass[ , 2 ],
passes = splitted_pass[ , 1 ]),
FUN = sum )
result <- spread( result, key = "passes", value = "duration", fill = 0, drop = F )
if( exists( "data0" ) )
{
result0 <- sum( data0[ , fixTime ] )
result <- rbind( data.frame( AOI = 0, FPF = result0, FPR = NA, SP = NA ),
result )
}
if( !is.null( AOI ) )
result <- merge( result, AOI, by = "AOI", all = T )
result[ is.na( result ) ] <- 0
if( any( splitted_pass [ , 1 ] == "FPF" ) )
{
names( result )[ 2:4 ] <- c( "FirstPassForward", "FirstPassRereading", "SecondPass" )
}else names( result )[ 2:3 ] <- c( "FirstPass", "SecondPass" )
}
return( as.data.frame( result ) )
}
fixDur.inputChecks <- function( data, fixTime, passes, AOI )
{
if( !is.data.frame( data ) ) stop( "data should be a data frame" )
if( length( fixTime ) > 1 ) stop( paste0("fixTime should be a single number or ",
"character, indicating the fixation time ",
"column" ) )
if( is.character( fixTime ) & !( fixTime %in% colnames( data ) ) )
stop( "fixTime is not a column of data" )
if( length( passes ) > 1 ) stop( paste0("passes should be a single number or ",
"character, indicating the coded passes ",
"column" ) )
if( is.character( passes ) & !( passes %in% colnames( data ) ) )
stop( "passes is not a column of data" )
if( !is.null( AOI ) & is.character( AOI ) & length( AOI ) == 1 )
{
if( !( AOI %in% colnames( data ) ) )
stop( "the value provide to AOI is not a column name of data" )
}
} |
if(getRversion() >= '2.15.1') utils::globalVariables(c('scoring.fun', 'testChar'))
TestScorerGUI <- function() {
catalog <- set.tests.directory()
courrier10 <- tkfont.create(family="courier", size=10)
arial8 <- tkfont.create(family="arial", size=8)
present.test <- new.env(parent = emptyenv())
subject <- new.env(parent = emptyenv())
top <- tktoplevel()
tkwm.title(top, 'TestScorer 1.7.2')
tkwm.resizable(top, FALSE, FALSE)
testFrame <- tkframe(top, relief="groove",borderwidth=2)
idFrame <- tkframe(top, relief="groove",borderwidth=2)
respFrame <- tkframe(top, relief="groove",borderwidth=2)
tkgrid.configure(testFrame, idFrame, respFrame)
number.of.tests <- length(catalog)
tests <- character(0)
for (i in 1:number.of.tests)
tests <- c(tests, catalog[[i]][[1]])
which.testFrame <- tkframe(testFrame, relief="groove", borderwidth=2)
scr <- tkscrollbar(which.testFrame, repeatinterval=5,
command=function(...)tkyview(test.selBox,...))
test.selBox <- tklistbox(which.testFrame, height=6, width='31',
selectmode='single', yscrollcommand=function(...)tkset(scr,...),
background='white', exportselection=F)
for (i in (1:number.of.tests))
tkinsert(test.selBox,'end',tests[i])
tkselection.set(test.selBox,0)
tkgrid.configure(which.testFrame, sticky='nw')
tkgrid(tklabel(which.testFrame, text='Which test would you like to score?'), sticky='nw')
tkgrid(test.selBox, scr, sticky='nw')
tkgrid.configure(scr, rowspan=3, sticky='nse')
on.nameFile <- function() {
choice.top <- tktoplevel()
tkwm.deiconify(choice.top)
tkwm.resizable(choice.top, FALSE, FALSE)
tkgrab.set(choice.top)
tktitle(choice.top) <- 'Saving scores'
tkgrid(tklabel(choice.top, text=' '))
choiceFrame <- tkframe(choice.top, relief="groove", borderwidth=2)
tkgrid(choiceFrame)
rb.dont <- tkradiobutton(choice.top)
rb.new <- tkradiobutton(choice.top)
rb.exist <- tkradiobutton(choice.top)
rbChoice <- tclVar("dont")
tkconfigure(rb.dont, variable=rbChoice ,value="dont")
tkconfigure(rb.new, variable=rbChoice ,value="new")
tkconfigure(rb.exist, variable=rbChoice, value="exist")
tkgrid(tklabel(choiceFrame, text="Save to:"), stick='w')
tkgrid(tklabel(choiceFrame, text=" Don't save"), rb.dont, sticky='w')
tkgrid(tklabel(choiceFrame, text=" An existing file"), rb.exist, sticky='w')
tkgrid(tklabel(choiceFrame, text=" A new file"), rb.new, sticky='w')
tkgrid(tklabel(choice.top, text=' '))
donechoiceVar <- tclVar(0)
OkDoneChoice.but <- tkbutton(choice.top, text=' OK ',
command=function() tclvalue(donechoiceVar) <- 1)
tkgrid(OkDoneChoice.but)
tkgrid(tklabel(choice.top, text=paste('Close this window to cancel the action.',
'Option will be set to "Don\'t save".',
sep='\n')))
tkbind(choice.top, '<Destroy>', function() tclvalue(donechoiceVar) <- 3)
tkfocus(choice.top)
tkwait.variable(donechoiceVar)
doneChoice <- as.integer(tclvalue(donechoiceVar))
tkgrab.release(choice.top)
tkdestroy(choice.top)
nameFile=''
if (doneChoice==1) {
if (tclvalue(rbChoice)=='dont') {
tclvalue(nameFileVar) <- "Don't save"
tclvalue(write.itemsVar) <- 'Yes'
}
else if (tclvalue(rbChoice)=='new') {
msg <- paste("First choose a directory.",
"Then a name for the file will be asked.",
"",
"Note: It is not save to mix data with scoring scripts",
" in the same directory.",
sep="\n")
tkmessageBox(message=msg)
name.dir <- tk_choose.dir()
if (!is.na(name.dir)) {
a.file <- tktoplevel()
tkwm.deiconify(a.file)
tkwm.resizable(a.file, FALSE, FALSE)
tkgrab.set(a.file)
tktitle(a.file) <- 'File'
tkgrid(tklabel(a.file, text=''))
nameFrame <- tkframe(a.file, relief="groove", borderwidth=2)
tkgrid(nameFrame)
nameVar <- tclVar('')
nameEntryWidget <- tkentry(nameFrame, width = 20,
textvariable = nameVar)
tkgrid(tklabel(nameFrame, text = 'Name for the file:'), nameEntryWidget)
tkgrid(tklabel(a.file, text="DON'T MISS THE EXTENSION!"))
tkgrid(tklabel(a.file, text=''))
tkfocus(nameEntryWidget)
donechoiceVar <- tclVar(0)
OkDoneChoice.but <- tkbutton(a.file, text=' OK ',
command=function() tclvalue(donechoiceVar) <- 1)
tkgrid(OkDoneChoice.but)
tkgrid(tklabel(a.file, text='Close this window to cancel the action.'))
tkbind(a.file, '<Destroy>', function() tclvalue(donechoiceVar) <- 3)
tkfocus(a.file)
tkwait.variable(donechoiceVar)
doneChoice <- as.integer(tclvalue(donechoiceVar))
new.file <- tclvalue(nameVar)
tkgrab.release(a.file)
tkdestroy(a.file)
} else new.file <- ''
if (new.file!='') {
nameFile <- paste(name.dir, '/', new.file, sep='', collapse='')
the.file.exists <- file.exists(nameFile)
if (the.file.exists) {
msg <- paste('File already exists.',
'New data will be appended.',
sep='\n')
tkmessageBox(message=msg, icon='warning', type='ok')
}
} else nameFile <- ''
}
else if (tclvalue(rbChoice)=='exist') {
nameFile <- tk_choose.files(multi=FALSE)
if (length(nameFile)==0) nameFile <- ''
}
}
if (nameFile=='') {
tclvalue(nameFileVar) <- "Don't save"
tclvalue(write.itemsVar) <- 'Yes'
tkconfigure(showBut, text=' Show results ')
tkconfigure(writeBut, foreground='gray50')
tkconfigure(YesButton, state='disabled')
tkconfigure(NoButton, state='disabled')
msg <- "Choosing a file has been canceled. \nOption is set to \"Don't save\"."
tkmessageBox(message=msg, icon='warning', type='ok')
} else if (grepl('TST_', nameFile)) {
msg <- paste('Names begining with the string "TST_" are not allowed.',
'Choose another name.',
sep='\n')
tkmessageBox(message=msg, icon='error', type='ok')
tclvalue(nameFileVar) <- "Don't save"
tclvalue(write.itemsVar) <- 'Yes'
tkconfigure(showBut, text=' Show results ')
tkconfigure(writeBut, foreground='gray50')
tkconfigure(YesButton, state='disabled')
tkconfigure(NoButton, state='disabled')
} else if (!file.exists(nameFile)) {
tclvalue(nameFileVar) <- nameFile
tkconfigure(showBut, text='Show & write results')
tkconfigure(writeBut, foreground='black')
tkconfigure(YesButton, state='normal')
tkconfigure(NoButton, state='normal')
} else {
options(warn = -1)
disk.file <- read.csv2(nameFile, nrows=1)
options(warn = 0)
disk.file.names <- names(disk.file)
names.needed <- c('id', 'test', 'age', 'sex', 'date', 'obs')
if(!all(names.needed %in% disk.file.names)) {
msg <- paste("The file ",
nameFile,
" has not a valid structure.",
"\nChoose or create an other file.",
sep="")
tkmessageBox(message=msg, icon='error', type='ok')
tclvalue(nameFileVar) <- "Don't save"
tclvalue(write.itemsVar) <- 'Yes'
tkconfigure(showBut, text=' Show results ')
tkconfigure(writeBut, foreground='gray50')
tkconfigure(YesButton, state='disabled')
tkconfigure(NoButton, state='disabled')
} else {
present.test <- sub('^TST_', '', present.test[['test']])
if(disk.file[1, 2] != present.test) {
msg <- paste("The file ",
nameFile,
" is for an other test (",
disk.file[1, 2],
").",
"\nChoose or create an other file.",
sep="")
tkmessageBox(message=msg, icon='error', type='ok')
tclvalue(nameFileVar) <- "Don't save"
tclvalue(write.itemsVar) <- 'Yes'
tkconfigure(showBut, text=' Show results ')
tkconfigure(writeBut, foreground='gray50')
tkconfigure(YesButton, state='disabled')
tkconfigure(NoButton, state='disabled')
} else {
tclvalue(nameFileVar) <- nameFile
tkconfigure(showBut, text='Show & write results')
tkconfigure(writeBut, foreground='black')
tkconfigure(YesButton, state='normal')
tkconfigure(NoButton, state='normal')
}
}
}
}
where.writeFrame <- tkframe(testFrame, relief="groove", borderwidth=2)
fileLbl <- tklabel(where.writeFrame,
text='Where would you like to save scores in tabular format? ')
tkgrid(where.writeFrame, sticky='w')
tkgrid(fileLbl, sticky='w')
nameFileVar <- tclVar("Don't save")
nameFileEntry <- tklabel(where.writeFrame, text=tclvalue(nameFileVar),
width=70)
fileNameBut <- tkbutton(where.writeFrame,
text='Change\noption',
command=on.nameFile)
tkconfigure(nameFileEntry, textvariable=nameFileVar, bg='lightgrey',
relief='groove', borderwidth=2)
tkgrid(nameFileEntry, fileNameBut, sticky='ew')
write.itemsFrame<- tkframe(where.writeFrame)
write.itemsVar <- tclVar('Yes')
YesButton <- tkradiobutton(write.itemsFrame, variable=write.itemsVar,
value='Yes')
NoButton <- tkradiobutton(write.itemsFrame, variable=write.itemsVar,
value='No')
tkconfigure(YesButton, state='disabled')
tkconfigure(NoButton, state='disabled')
tkgrid(write.itemsFrame, sticky='w')
tkgrid.configure(tklabel(write.itemsFrame,
text='Would you like to save also the items?'),
tklabel(write.itemsFrame, text='Yes'), YesButton,
tklabel(write.itemsFrame, text='No'), NoButton,
sticky='w')
testCharLbl <- tklabel(testFrame, text='Test information')
testCharEntry <- tktext(testFrame, width=71, height=7,
bg='lightgrey', font=arial8)
tkgrid(testCharLbl, sticky='w')
tkgrid(testCharEntry, sticky='w')
idVar <- tclVar('')
idEntry <- tkentry(idFrame, width='30', textvariable=idVar)
ageVar <- tclVar('')
ageEntry <- tkentry(idFrame, width='2', textvariable=ageVar)
sexVar <- tclVar('Male')
sexFrame <- tkframe(idFrame, relief="groove", borderwidth=2)
maleButton <- tkradiobutton(sexFrame, variable=sexVar, value='Male')
femaleButton <- tkradiobutton(sexFrame, variable=sexVar, value='Female')
dateVar <- tclVar('')
dateEntry <- tkentry(idFrame, width='10', textvariable=dateVar)
commVar <- tclVar('')
commEntry <- tkentry(idFrame, width='30', textvariable=commVar)
tkgrid.configure(idFrame, sticky='nw')
tkgrid(tklabel(idFrame, text='Identification'), sticky='nw')
tkgrid(idEntry, sticky='nw')
tkgrid(tklabel(idFrame, text='Age'), sticky='nw')
tkgrid(ageEntry, sticky='nw')
tkgrid(sexFrame, sticky='nw')
tkgrid.configure(tklabel(sexFrame, text='Male'),
maleButton, tklabel(sexFrame, text='Female'),
femaleButton)
tkgrid(tklabel(idFrame, text='Date'), sticky='nw')
tkgrid(dateEntry, sticky='nw')
tkgrid(tklabel(idFrame, text='Comment'), sticky='nw')
tkgrid(commEntry, sticky='nw')
entryFrame <- tkframe(respFrame, relief="groove", borderwidth=2)
tkgrid(tklabel(entryFrame, text="Entry items window"), sticky='nw')
item.numVar <- tclVar('Item to enter: 1 -->')
item.numEntry <- tklabel(entryFrame, text=tclvalue(item.numVar), width=20)
itemVar <- tclVar('')
itemEntry <- tkentry(entryFrame, width='1',
textvariable=idVar, font=courrier10 )
tkconfigure(item.numEntry, textvariable=item.numVar, fg='blue')
tkconfigure(itemEntry, textvariable=itemVar)
tkgrid.configure(respFrame, sticky='nw')
tkgrid(item.numEntry, itemEntry)
tkgrid(entryFrame, sticky='ew')
itemsFrame <- tkframe(respFrame)
items <- tktext(itemsFrame, bg='lightgrey', font=courrier10,
height=10, width='10')
tkconfigure(items, state='disabled')
itemsText <- tktext(itemsFrame, bg='lightgrey', font=courrier10,
height=10, width='7')
tkinsert(itemsText, 'end',
paste(seq(1, 91, 10), '-', seq(10, 100, 10), '\n',
sep='', collapse=''))
tkconfigure(itemsText, state='disabled')
tkgrid(tklabel(itemsFrame, text='1234567890',
font=courrier10))
tkgrid(items, itemsText)
tkgrid(itemsFrame)
initialize.test <- function(num.order) {
test <- paste('TST_', catalog[[num.order]][[1]],
sep='')
assign('test', test, envir=present.test)
total.items <- catalog[[num.order]][[4]]
assign('total.items', total.items, envir=present.test)
valid.characters <- c(catalog[[num.order]][[5]],
catalog[[num.order]][[6]], 'space')
assign('valid.characters', valid.characters, envir=present.test)
items.string <- paste(c(rep(' ', present.test[['total.items']]),
rep('=', (present.test[['total.items']] %/% 100 +1)*100 - present.test[['total.items']])),
collapse='')
assign('items.string', items.string, envir=present.test)
next.item <- 1
assign('next.item', next.item, envir=present.test)
tkconfigure(testCharEntry, stat='normal')
tkdelete(testCharEntry, '0.0', 'end')
tkinsert(testCharEntry,"end","Test name: ")
tkinsert(testCharEntry,'end', paste(catalog[[num.order]][[2]]))
tkinsert(testCharEntry,"end","\nAuthor: ")
tkinsert(testCharEntry,'end', paste(catalog[[num.order]][[3]]))
tkinsert(testCharEntry,"end","\nNumber of items: ")
tkinsert(testCharEntry,'end', paste(catalog[[num.order]][[4]]))
tkinsert(testCharEntry,"end","\nValid answers: ")
tkinsert(testCharEntry,'end', paste(catalog[[num.order]][[5]]))
tkinsert(testCharEntry,'end','\nMissings: ')
if (length(catalog[[num.order]][[6]])==0)
tkinsert(testCharEntry,'end', 'space')
else tkinsert(testCharEntry,'end', paste(catalog[[num.order]][[6]], '& space'))
tkinsert(testCharEntry,'end','\nComment: ')
tkinsert(testCharEntry,'end', paste(catalog[[num.order]][[7]]))
tkconfigure(testCharEntry, state='disabled')
tkconfigure(items, state='normal')
tkdelete(items, '0.0', 'end')
tkinsert(items, '0.0', present.test[['items.string']])
tkconfigure(items, state='disabled')
}
on.item.numEntry <- function(K) {
if (is.element(K, c(present.test[['valid.characters']],
'Up', 'Down', 'Left', 'Right',
'Num_Lock'))) {
if (K=='Up')
if (present.test[['next.item']] < 11) answer.out()
else present.test[['next.item']] <- present.test[['next.item']] - 10
else if (K=='Down')
if (present.test[['next.item']] > present.test[['total.items']]-10) answer.out()
else present.test[['next.item']] <- present.test[['next.item']] + 10
else if (K=='Left')
if (present.test[['next.item']] < 2) answer.out()
else present.test[['next.item']] <- present.test[['next.item']] - 1
else if (K=='Right')
if (present.test[['next.item']] > present.test[['total.items']]) answer.out()
else present.test[['next.item']] <- present.test[['next.item']] + 1
else if (K=='Num_Lock') {}
else if (present.test[['next.item']] > present.test[['total.items']]) answer.out()
else {
present.test[['next.item']] <- present.test[['next.item']] + 1
tclvalue(item.numVar) <- present.test[['next.item']]
if (K=='space') item.value <- ' ' else item.value <- K
present.test[['items.string']] <- paste(substr(present.test[['items.string']],
1,
present.test[['next.item']]-2),
item.value,
substr(present.test[['items.string']],
present.test[['next.item']],
nchar(present.test[['items.string']])),
sep='')
}
}
else invalid.answer(K)
items.string.mod <- paste(substr(present.test[['items.string']],
1,
present.test[['next.item']] - 1),
'*',
substr(present.test[['items.string']],
present.test[['next.item']] + 1,
nchar(present.test[['items.string']])),
sep='')
hundred <- (present.test[['next.item']]-1) %/% 100
tkconfigure(itemsText, state='normal')
tkdelete(itemsText, '0.0', 'end')
tkinsert(itemsText, 'end',
paste(seq(hundred*100+1, hundred*100+91, 10), '-',
seq(hundred*100+10, hundred*100+100, 10), '\n',
sep='',
collapse=''))
tkconfigure(itemsText, state='disabled')
items.string.mod <- substring(items.string.mod, hundred * 100 + 1,
(hundred + 1) * 100)
tkconfigure(items, state='normal')
tkdelete(items, '0.0', 'end')
tkinsert(items, '0.0', items.string.mod)
tkconfigure(items, state='disabled')
tkdelete(itemEntry, '0', 'end')
tkinsert(itemEntry, '0', substring(present.test[['items.string']],
present.test[['next.item']],
present.test[['next.item']]))
if (present.test[['next.item']] == present.test[['total.items']]+1) {
alarm()
tclvalue(item.numVar) <- 'END OF TEST'
}
else tclvalue(item.numVar) <- paste('Item to enter: ',
present.test[['next.item']],
'-->')
}
answer.out <- function(K)
{ msg <- paste('You tried to go out of the range of items.',
'\n"Test information" shows the number of items of this test.',
sep='\n')
tkmessageBox(message=msg, icon='error')
tkfocus(itemEntry)
}
invalid.answer <- function(K)
{ msg <- paste('Answer "', K, '" is invalid.',
'\n\nSee "Test information" window for valid answers.',
sep='')
tkmessageBox(message=msg, icon='error')
tkfocus(itemEntry)
}
on.show.and.record <- function(){
results <- score.results()
show.results(results[[1]], results[[2]])
if (tclvalue(nameFileVar) != "Don't save") write.results(results[[3]], results[[4]])
}
on.write <- function(){
results <- score.results()
write.results(results[[3]], results[[4]])
}
score.results <- function() {
assign('id', tclvalue(idVar), envir=subject)
assign('age', tclvalue(ageVar), envir=subject)
assign('sex', tclvalue(sexVar), envir=subject)
assign('date.test', tclvalue(dateVar), envir=subject)
assign('comm.sbj', tclvalue(commVar), envir=subject)
answers <- character(present.test[['total.items']])
for (i in 1:present.test[['total.items']])
answers[i] <- substring(present.test[['items.string']], i, i)
eval(parse(text=paste(text="source('",
present.test[['test']],
".r')",
sep="")))
results <- scoring.fun(answers,
subject[['sex']],
subject[['age']],
subject[['id']],
subject[['date.test']],
subject[['comm.sbj']])
results.lst <- results$results.lst
results.df <- results$results.df
results.scores <- results$results.scores
list(results.lst=results.lst,
results.df=results.df,
results.scores=results.scores,
answers=answers)
}
show.results <- function(results.lst, results.df){
options(width=100)
cat('\n\n')
cat('----------------------',
sub('^TST_', '',
present.test[['test']]),
'-----------------------\n')
cat('Subject:', subject[['id']], '\n')
cat('Sex:', subject[['sex']], '\n')
cat('Age:', subject[['age']], '\n')
cat('Date:', subject[['date.test']], '\n')
cat('Comment:', subject[['comm.sbj']], '\n\n')
for (i in seq_along(results.lst))
cat(results.lst[[i]], '\n')
cat('\n')
print(results.df, right=FALSE, row.names=FALSE, na.print='-')
}
write.results <- function(results.scores, answers){
if (tclvalue(nameFileVar) != "Don't save") {
the.file.exists <- file.exists(tclvalue(nameFileVar))
options(warn=-1)
case <- data.frame(id=subject[['id']],
test=sub('^TST_', '', present.test[['test']]),
age=as.numeric(subject[['age']]),
sex=subject[['sex']],
date=subject[['date.test']],
obs=subject[['comm.sbj']])
options(warn=0)
if (is.data.frame(results.scores))
case <- cbind(case, results.scores)
else case <- cbind(case, t(results.scores))
if (tclvalue(write.itemsVar)=='Yes') {
if (the.file.exists) {
if ((length(results.scores)+6)==length(read.csv2(tclvalue(nameFileVar), header = TRUE, nrows = 1))) {
msg <- paste("This file doesn't accept items.",
"Items have not been saved, but scales yes.",
"To save items use an other (existing or new created) file,",
"with the save items option checked.",
sep="\n")
tkmessageBox(message=msg, icon='warning')
tclvalue(write.itemsVar) <- 'No'
} else case <- cbind(case, i=t(as.numeric(answers)))
} else case <- cbind(case, i=t(as.numeric(answers)))
}
if (!the.file.exists) {
write.table(case, tclvalue(nameFileVar), row.names=F,
sep=';', na='', quote=TRUE)
} else { write.table(case, tclvalue(nameFileVar), append=TRUE,
row.names=F, col.names=F, sep=';', na='', quote=TRUE)
}
rm(case, inherits=TRUE)
msg <- 'Test scores has been saved.'
tkmessageBox(message=msg, icon='info')
}
else {msg <- paste('First choose a file where to write the resuts.',
'Use the "Change option" button.',
sep='\n')
tkmessageBox(message=msg, icon='error')}
}
on.clean.all <- function() {
tkdelete(idEntry, 0, 'end')
tkdelete(ageEntry, 0, 'end')
tkdelete(dateEntry, 0, 'end')
tkdelete(commEntry, 0, 'end')
tkdelete(itemEntry, 0, 'end')
tclvalue(sexVar) <- 'Male'
on.clean.test()
}
on.new.test <- function() {
if (tclvalue(nameFileVar)!="Don't save") {
tclvalue(nameFileVar) <- "Don't save"
tclvalue(write.itemsVar) <- 'Yes'
tkconfigure(showBut, text=' Show results ')
tkconfigure(writeBut, foreground='gray50')
tkconfigure(YesButton, state='disabled')
tkconfigure(NoButton, state='disabled')
msg <- paste("The file for saving scores is no longer valid for the new test.",
"Saving results has been reseted to \"Don't save\".",
"Select an other file if appropiate.",
sep='\n')
tkmessageBox(message=msg, icon='warning')
}
on.clean.test()
}
on.clean.test <- function() {
tkdelete(itemEntry, 0, 'end')
initialize.test(as.numeric(tkcurselection(test.selBox))+1)
tclvalue(item.numVar) <- 'Item to enter: 1 -->'
tkconfigure(itemsText, state='normal')
tkdelete(itemsText, '0.0', 'end')
tkinsert(itemsText, 'end',
paste(seq(1, 91, 10), '-', seq(10, 100, 10), '\n',
sep='', collapse=''))
tkconfigure(itemsText, state='disabled')
tkgrid(items, itemsText)
}
on.exit <- function() {
msg <- paste(' -------------------------------------------------------',
' | To exit the R session close the window or type: q() |',
' | |',
' | TestScorer do not use the workspace image, so |',
' | you can safely answer "No" to the next question. |',
' -------------------------------------------------------',
sep='\n')
message(msg)
tkdestroy(top)
}
on.help <- function() {
modalDialog <- function() {
dlg <- tktoplevel()
tkwm.title(dlg, 'Help')
tkwm.resizable(dlg, FALSE, FALSE)
tkwm.deiconify(dlg)
tkgrab.set(dlg)
tkfocus(dlg)
scrBar <- tkscrollbar(dlg, repeatinterval=5,
command=function(...)tkyview(helpText,...))
helpText <- tktext(dlg, height=30, width='70', font=courrier10,
yscrollcommand=function(...)tkset(scrBar,...))
txt <- readLines('Help.txt', n=-1)
tkinsert(helpText, 'end', paste(txt, '\n', sep='', collapse=''))
tkconfigure(helpText, state='disabled')
onClose <- function() {
tkgrab.release(dlg)
tkdestroy(dlg)
tkfocus(top)
}
Close.but <-tkbutton(dlg, text=" Close ",command=onClose)
tkgrid(helpText, scrBar, sticky='ns')
tkgrid(Close.but)
tkfocus(dlg)
tkbind(dlg, "<Destroy>", function() {tkgrab.release(dlg);tkfocus(top)})
tkwait.window(dlg)
}
modalDialog()
}
on.manager <- function() {
manager.top <- tktoplevel()
tkwm.deiconify(manager.top)
tkwm.resizable(manager.top, FALSE, FALSE)
tkgrab.set(manager.top)
tktitle(manager.top) <- 'Test Manager'
tkgrid(tklabel(manager.top, text=' '))
managerFrame <- tkframe(manager.top, relief="groove",borderwidth=2)
tkgrid(managerFrame)
rb.add <- tkradiobutton(managerFrame)
rb.del <- tkradiobutton(managerFrame)
rbValue <- tclVar("Add")
tkconfigure(rb.add, variable=rbValue ,value="Add")
tkconfigure(rb.del, variable=rbValue, value="Delete")
tkgrid(tklabel(managerFrame, text="Make a choice:"), stick='w')
tkgrid(tklabel(managerFrame, text=" Add a new test "), rb.add)
tkgrid(tklabel(managerFrame, text=" Delete an existing test"), rb.del)
tkgrid(tklabel(manager.top, text=' '))
doneManager <- tclVar(0)
OkDoneManager.but <- tkbutton(manager.top, text=' OK ',
command=function() tclvalue(doneManager) <- 1)
tkgrid(OkDoneManager.but)
tkgrid(tklabel(manager.top, text='Close this window to cancel the action.'))
tkbind(manager.top, '<Destroy>', function() tclvalue(doneManager) <- 3)
tkfocus(manager.top)
tkwait.variable(doneManager)
doneVal <- as.integer(tclvalue(doneManager))
tkgrab.release(manager.top)
tkdestroy(manager.top)
if (doneVal==1) {
tkdestroy(top)
if (tclvalue(rbValue)=='Add') add.new.test()
if (tclvalue(rbValue)=='Delete') delete.test()
}
}
buttFrame <- tkframe(top)
showBut <- tkbutton(buttFrame, text=" Show results ", command=on.show.and.record)
writeBut <- tkbutton(buttFrame, text=" Only save ",
foreground='gray50', command=on.write)
cleanTestBut <- tkbutton(buttFrame, text=" Clean items ", command=on.clean.test)
cleanAllBut <- tkbutton(buttFrame, text=" Clean all ", command=on.clean.all)
exitBut <- tkbutton(buttFrame, text="Exit TestScorer", command=on.exit)
helpBut <- tkbutton(buttFrame, text=" Help ", command=on.help)
managerBut <- tkbutton(buttFrame, text="Test Manager", command=on.manager)
tkgrid(buttFrame, columnspan=3)
tkgrid(showBut, writeBut, cleanTestBut, cleanAllBut, managerBut, helpBut, exitBut)
notabeneFrame <- tkframe(top, relief="groove", borderwidth=2)
tkgrid(notabeneFrame, columnspan=3)
tkgrid(tklabel(notabeneFrame, text='Gray windows are non-editable.'))
tkgrid(tklabel(notabeneFrame, text='To introduce the items, put the cursor inside the white box in "Entry items window". Then enter the answers using numerical keys.'))
tkgrid(tklabel(notabeneFrame, text='You can use the arrow keys to skip between items. Do NOT use "backspace".'))
tkgrid(tklabel(notabeneFrame, text='Use the R console menu option "File" to print or save the results.'))
tkgrid(tklabel(notabeneFrame, text='Click help for more detailed instructions.'))
tkbind(itemEntry, "<KeyRelease>", on.item.numEntry)
tkbind(test.selBox, "<ButtonRelease-1>", on.new.test)
initialize.test(1)
on.new.test()
tkfocus(top)
}
set.tests.directory <- function() {
content <- dir()
existing.tests <- content[grep('^TST_.+\\.r$', content)]
if (length(existing.tests)==0) {
choice.dir.top <- tktoplevel()
tkwm.deiconify(choice.dir.top)
tkwm.resizable(choice.dir.top, FALSE, FALSE)
tkgrab.set(choice.dir.top)
tktitle(choice.dir.top) <- 'Choose a directory'
tkgrid(tklabel(choice.dir.top, text=''))
tkgrid(tklabel(choice.dir.top, text='You have to choose or create a directory for working with TestScorer.'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=''))
tkgrid(tklabel(choice.dir.top, text='If you create a new directory, six files will be copied to it:'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=' DASS.r: R script for scoring DASS scales'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=' MHLC.r: R script for scoring MHLC test'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=' RAAS.r: R script for scoring RAAS scales'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=' Help.txt: an ascii file with help instructions'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=' TestScorerHelp.pdf: PDF with further help'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=' .Profile: to open TestScorer when R is launched from this directory'), sticky='w')
tkgrid(tklabel(choice.dir.top, text=''))
choice.dirFrame <- tkframe(choice.dir.top, relief='groove',
borderwidth=2)
tkgrid(choice.dirFrame)
rb.continue <- tkradiobutton(choice.dir.top)
rb.stop <- tkradiobutton(choice.dir.top)
rbdirChoiceVar <- tclVar('continue')
tkconfigure(rb.continue, variable=rbdirChoiceVar, value='continue')
tkconfigure(rb.stop, variable=rbdirChoiceVar, value='stop')
tkgrid(tklabel(choice.dirFrame, text='Choose an option:'), sticky='w')
tkgrid(tklabel(choice.dirFrame, text=' Select an existing directory or create a new one'), rb.continue, sticky='w')
tkgrid(tklabel(choice.dirFrame, text=' Stop & exit TestScorer'), rb.stop, sticky='w')
tkgrid(tklabel(choice.dir.top, text=' '))
doneChoiceDirVar <- tclVar(0)
OkDoneChoiceDir.but <- tkbutton(choice.dir.top, text=' Ok ',
command=function() tclvalue(doneChoiceDirVar) <- 1)
tkgrid(OkDoneChoiceDir.but)
tkbind(choice.dir.top, '<Destroy>', function() tclvalue(doneChoiceDirVar) <- 3)
tkfocus(choice.dir.top)
tkwait.variable(doneChoiceDirVar)
doneChoiceDir <- tclvalue(doneChoiceDirVar)
choiceDir <- tclvalue(rbdirChoiceVar)
tkgrab.release(choice.dir.top)
tkdestroy(choice.dir.top)
if (doneChoiceDir=='1' && choiceDir=='continue') {
set.dir <- 'stop TestScorer'
working.dir <- tk_choose.dir()
if (working.dir!='') {
setwd(working.dir)
content <- dir()
if (length(grep('TST_.+\\.r$', content))==0) {
file.copy(from=system.file('some.stuff/TST_DASS.r',
package='TestScorer'), to=working.dir)
file.copy(from=system.file('some.stuff/TST_MHLC.r',
package='TestScorer'), to=working.dir)
file.copy(from=system.file('some.stuff/TST_RAAS.r',
package='TestScorer'), to=working.dir)
file.copy(from=system.file('some.stuff/TST_IPIP50.r',
package='TestScorer'), to=working.dir)
file.copy(from=system.file('some.stuff/Help.txt',
package='TestScorer'), to=working.dir)
file.copy(from=system.file('doc/TestScorerHelp.pdf',
package='TestScorer'), to=working.dir)
cat(paste('
'\nsuppressPackageStartupMessages(require(TestScorer))',
'\nTestScorerGUI()'),
file='.Rprofile')
if (.Platform$OS.type=='windows') {
if (.Platform$r_arch=='i386') startR <- paste(R.home(), '/bin/i386/Rgui.exe', sep='')
else startR <- paste(R.home(), '/bin/x64/Rgui.exe', sep='')
cat(paste('start ""',
startR,
'--no-restore --quiet'),
file='TestScorer.cmd')
}
}
set.dir <- 'test has been copied'
}
} else
set.dir <- 'stop TestScorer'
} else
set.dir <- 'tests already exist'
if (set.dir!='stop TestScorer') {
content <- dir()
existing.tests <- content[grep('^TST_.+\\.r$', content)]
if (length(existing.tests)>0) {
catalog <- list()
for (i in seq_along(existing.tests)) {
source(existing.tests[i])
catalog <- c(catalog, list(testChar))
cat.length <- length(catalog)
acronyms <- character()
for (i in 1:cat.length) acronyms <- c(acronyms, catalog[[i]]$acronym)
dupli <- acronyms[duplicated(acronyms)]
if (length(dupli>0))
tkmessageBox(message=paste('Some test in catalog are duplicated:', paste(dupli, collapse=', '),
'\n\nConsiderer revising the test files in the directory.',
'\nProbably an acronym do not match the file name.'),
icon='warning', type='ok')
}
}
} else
stop(paste('No directory has been choosen.',
'TestScorer has been stopped by the user.',
sep='\n'))
catalog
}
add.new.test <- function() {
test.char <- new.env(parent = emptyenv())
assign('trans.is.numeric', 'yes', envir=test.char)
scale.char <- new.env(parent = emptyenv())
assign('trans.is.numeric', 'yes', envir=scale.char)
make.test.window <- function() {
no.trans <- function() {
assign('graphVal', tclVar('no'), envir=test.char)
assign('equalVal', tclVar('no'), envir=test.char)
assign('name.transVal', tclVar('Centil'), envir=test.char)
tkconfigure(rb.graph.yes, variable=test.char[['graphVal']], state='disabled')
tkconfigure(rb.graph.no, variable=test.char[['graphVal']], state='disabled')
tkconfigure(rb.equal.yes, variable=test.char[['equalVal']], state='disabled')
tkconfigure(rb.equal.no, variable=test.char[['equalVal']], state='disabled')
tkconfigure(entry.name, textvariable=test.char[['name.transVal']], state='disabled')
assign('n.age.groupsVal', tclVar('1'), envir=test.char)
tkconfigure(entry.n.age.groups, textvariable=test.char[['n.age.groupsVal']], state='disabled')
}
other.trans <- function() {
if (tclvalue(test.char[['prorrateVal']])=='yes' || tclvalue(test.char[['scoringVal']])=='mean')
tkmessageBox(message='NB: Raw scores would be rounded before transformation.\n Considerer if rounding is appropiate.',
icon='warning', type='ok')
if (tclvalue(test.char[['graphVal']])=='yes')
{ assign('graphVal', tclVar('no'), envir=test.char)
tkmessageBox(message='NB: No graph for non-T transformation, graph option set to "no".',
icon='warning', type='ok')
}
tkconfigure(rb.graph.yes, variable=test.char[['graphVal']], state='disabled')
tkconfigure(rb.graph.no, variable=test.char[['graphVal']], state='disabled')
tkconfigure(rb.equal.yes, state='normal')
tkconfigure(rb.equal.no, state='normal')
assign('name.transVal', tclVar('Centil'), envir=test.char)
tkconfigure(entry.name, textvariable=test.char[['name.transVal']], state='normal')
assign('n.age.groupsVal', tclVar('1'), envir=test.char)
tkconfigure(entry.n.age.groups, textvariable=test.char[['n.age.groupsVal']], state='normal')
}
Tmean.trans <- function() {
tkconfigure(rb.equal.yes, state='normal')
tkconfigure(rb.equal.no, state='normal')
tkconfigure(rb.graph.yes, state='normal')
tkconfigure(rb.graph.no, state='normal')
assign('name.transVal', tclVar('Centil'), envir=test.char)
tkconfigure(entry.name, textvariable=test.char[['name.transVal']], state='disabled')
assign('n.age.groupsVal', tclVar('1'), envir=test.char)
tkconfigure(entry.n.age.groups, textvariable=test.char[['n.age.groupsVal']], state='normal')
}
Ttable.trans <- function() {
if (tclvalue(test.char[['prorrateVal']])=='yes' || tclvalue(test.char[['scoringVal']])=='mean')
tkmessageBox(message=paste('NB: Raw scores would be rounded before transformation.',
' Considerer if rounding is appropiate.',
sep='\n'),
icon='warning', type='ok')
tkconfigure(rb.equal.yes, state='normal')
tkconfigure(rb.equal.no, state='normal')
tkconfigure(rb.graph.yes, state='normal')
tkconfigure(rb.graph.no, state='normal')
assign('name.transVal', tclVar('Centil'), envir=test.char)
tkconfigure(entry.name, textvariable=test.char[['name.transVal']], state='disabled')
assign('n.age.groupsVal', tclVar('1'), envir=test.char)
tkconfigure(entry.n.age.groups, textvariable=test.char[['n.age.groupsVal']], state='normal')
}
raw.is.sum <- function() {
tkconfigure(rb.prorat.no, state='normal')
tkconfigure(rb.prorat.yes, state='normal')
}
raw.is.mean <- function() {
if(tclvalue(test.char[['prorrateVal']])=='yes') {
assign('prorrateVal', tclVar('no'), envir=test.char)
tkconfigure(rb.prorat.no, variable=test.char[['prorrateVal']], state='disabled')
tkconfigure(rb.prorat.yes, variable=test.char[['prorrateVal']], state='disabled')
tkmessageBox(message='Prorrate has been reseted to "no".', icon='warning', type='ok')
}
if(tclvalue(test.char[['transVal']])!='no') {
assign('transVal', tclVar('no'), envir=test.char)
tkconfigure(rb.trans.No, variable=test.char[['transVal']], state='normal')
tkconfigure(rb.trans.Tmean, variable=test.char[['transVal']], state='normal')
tkconfigure(rb.trans.Ttable, variable=test.char[['transVal']], state='normal')
tkconfigure(rb.trans.Other, variable=test.char[['transVal']], state='normal')
assign('graphVal', tclVar('no'), envir=test.char)
tkconfigure(rb.graph.no, variable=test.char[['graphVal']], state='disabled')
tkconfigure(rb.graph.yes, variable=test.char[['graphVal']], state='disabled')
assign('equalVal', tclVar('no'), envir=test.char)
tkconfigure(rb.equal.no, variable=test.char[['equalVal']], state='disabled')
tkconfigure(rb.equal.yes, variable=test.char[['equalVal']], state='disabled')
tkmessageBox(message='Transform has been reseted to "no".', icon='warning', type='ok')
}
}
prorrate.yes <- function() {
if(tclvalue(test.char[['transVal']])!='no') {
assign('transVal', tclVar('no'), envir=test.char)
tkconfigure(rb.trans.No, variable=test.char[['transVal']], state='normal')
tkconfigure(rb.trans.Tmean, variable=test.char[['transVal']], state='normal')
tkconfigure(rb.trans.Ttable, variable=test.char[['transVal']], state='normal')
tkconfigure(rb.trans.Other, variable=test.char[['transVal']], state='normal')
assign('graphVal', tclVar('no'), envir=test.char)
tkconfigure(rb.graph.no, variable=test.char[['graphVal']], state='disabled')
tkconfigure(rb.graph.yes, variable=test.char[['graphVal']], state='disabled')
assign('equalVal', tclVar('no'), envir=test.char)
tkconfigure(rb.equal.no, variable=test.char[['equalVal']], state='disabled')
tkconfigure(rb.equal.yes, variable=test.char[['equalVal']], state='disabled')
tkmessageBox(message='Transform has been reseted to "no".', icon='warning', type='ok')
}
}
validate.test <- function() {
is.OkTest <- 'yes'
options(warn=-1)
acronymTest <- tclvalue(test.char[['acronymTestVal']])
acronymTest <- sub(' +$', '', acronymTest)
acronymTest <- sub('^ +', '', acronymTest)
tmp <- grep('([[:alnum:]]|_)+$', acronymTest)
if (length(tmp)==0) {
is.OkTest <- 'no'
msg <- paste('Acronym is not valid.',
'\nOnly alphanumeric and the character "_" are allowed.',
sep='\n')
tkmessageBox(message=msg, icon="error", type="ok")
}
content <- dir()
existing.tests <- content[grep('TST_.+\\.r$', content)]
existing.tests <- gsub('TST_', '', existing.tests)
existing.tests <- gsub('.r$', '', existing.tests)
if(acronymTest %in% existing.tests) {
is.OkTest <- 'no'
tkmessageBox(message="This test already exists. Change the acronym or cancel.",
icon="error", type="ok")
}
n.items <- as.numeric(tclvalue(test.char[['n.itemsVal']]))
if (is.na(n.items) || length(grep('\\.', n.items)>0)) {
is.OkTest <- 'no'
tkmessageBox(message="Number of items is not valid.", icon="error", type="ok")
}
valid <- tclvalue(test.char[['validVal']])
valid <- as.numeric(unlist(strsplit(valid, ',')))
if (length(valid) == 0 ||
any(is.na(valid)) ||
any(nchar(valid) > 1)) {
is.OkTest <- 'no'
tkmessageBox(message="Valid answers are not valid.", icon="error", type="ok")
}
miss <- tclvalue(test.char[['missVal']])
miss <- as.numeric(unlist(strsplit(miss, ',')))
if (any(is.na(miss)) ||
any(nchar(valid) > 1)) {
is.OkTest <- 'no'
tkmessageBox(message="Missings are not valid.", icon="error", type="ok")
}
if (any(miss %in% valid)) {
is.OkTest <- 'no'
tkmessageBox(message="Don't include missing values into the valid values.", icon="error", type="ok")
}
reversed <- tclvalue(test.char[['reversedVal']])
reversed <- as.numeric(unlist(strsplit(reversed, ',')))
if (any(is.na(reversed) | any(grep('\\.', reversed)))) {
is.OkTest <- 'no'
tkmessageBox(message="Reversed items are not valid.", icon="error", type="ok")
}
if (length(reversed)!=0 && max(reversed, na.rm=TRUE)>n.items) {
is.OkTest <- 'no'
tkmessageBox(message="Some reversed item is greather than de number of items of the test.",
icon="error", type="ok")
}
n.scales <- as.numeric(tclvalue(test.char[['n.scalesVal']]))
if (is.na(n.scales)) {
is.OkTest <- 'no'
tkmessageBox(message="Number of scales is not valid.", icon="error", type="ok")
}
n.age.groups <- as.numeric(tclvalue(test.char[['n.age.groupsVal']]))
if (is.na(n.age.groups) || grepl('\\.', n.age.groups)) {
is.OkTest <- 'no'
tkmessageBox(message="Age-groups is not an integer.", icon="error", type="ok")
}
else if (n.age.groups == 0) {
is.OkTest <- 'no'
tkmessageBox(message="Age-groups should be at least 1.", icon="error", type="ok")
}
else if (n.age.groups > 1) {
assign('n.age.groupsVal', tclVar('1'), envir=test.char)
tkconfigure(entry.n.age.groups, textvariable=test.char[['n.age.groupsVal']], state='normal')
tkmessageBox(message="Sorry, norms only implementet as yet for one group.", icon="error", type="ok")
}
options(warn=0)
is.OkTest
}
OnOkTest <- function() {
OkTest <- validate.test()
if (OkTest=='yes') tclvalue(doneTest) <- 1
}
top.test <- tktoplevel()
tkwm.title(top.test, "Test characteristics")
tkwm.resizable(top.test, FALSE, FALSE)
frameAcronym <- tkframe(top.test)
assign('acronymTestVal', tclVar(""), envir=test.char)
entry.acronymTest <- tkentry(frameAcronym ,width="10", textvariable=test.char[['acronymTestVal']])
tkgrid(frameAcronym, sticky='w')
tkgrid(tklabel(frameAcronym, text="Enter an acronym for the test"), entry.acronymTest, sticky='w')
tkgrid(tklabel(top.test, text="Note: Use only letters, numbers and '_'. The first character must be a letter."), sticky='w')
tkgrid(tklabel(top.test, text=' '))
frameName <- tkframe(top.test)
assign('nameTestVal', tclVar(""), envir=test.char)
entry.nameTest <- tkentry(frameName , width="40", textvariable=test.char[['nameTestVal']])
tkgrid(frameName, sticky='w')
tkgrid(tklabel(frameName, text="Enter the name of the test (optional)"), entry.nameTest, sticky='w')
tkgrid(tklabel(top.test, text=' '))
frameRef <- tkframe(top.test)
assign('refVal', tclVar(""), envir=test.char)
entry.ref <- tkentry(frameRef ,width="40", textvariable=test.char[['refVal']])
tkgrid(frameRef, sticky='w')
tkgrid(tklabel(frameRef, text="Enter the reference of the test (optional)"), entry.ref, sticky='w')
tkgrid(tklabel(top.test, text=' '))
frameComm <- tkframe(top.test)
assign('commVal', tclVar(""), envir=test.char)
entry.comm <- tkentry(frameComm ,width="40", textvariable=test.char[['commVal']])
tkgrid(frameComm, sticky='w')
tkgrid(tklabel(frameComm, text="Comment (optional)"), entry.comm, sticky='w')
tkgrid(tklabel(top.test, text=paste("Note: Any optional comment (e.g.: Use only for ages greater than 18).")), sticky='w')
frame.rigth <- tkframe(top.test, relief="groove", borderwidth=2)
frame.left <- tkframe(top.test, relief="groove", borderwidth=2)
frame.rigth <- tkframe(top.test, relief="groove", borderwidth=2)
tkgrid(frame.left, frame.rigth, sticky='nw')
tkgrid(tklabel(frame.left, text=' '))
frameN.items <- tkframe(frame.left)
assign('n.itemsVal', tclVar(""), envir=test.char)
entry.n.items <- tkentry(frameN.items ,width="10", textvariable=test.char[['n.itemsVal']])
tkgrid(frameN.items, sticky='w')
tkgrid(tklabel(frameN.items, text="Enter the number of items"), entry.n.items, sticky='w')
tkgrid(tklabel(frame.left, text=' '))
frameValid <- tkframe(frame.left)
assign('validVal', tclVar(""), envir=test.char)
entry.valid <- tkentry(frameValid ,width="20", textvariable=test.char[['validVal']])
tkgrid(frameValid, sticky='w')
tkgrid(tklabel(frameValid, text="Valid answers"), entry.valid, sticky='w')
tkgrid(tklabel(frame.left, text=paste("Note: Can be any number.",
"Do NOT include the missing values here",
"(e.g.: 1,2,3).")), sticky='w')
tkgrid(tklabel(frame.left, text="Use only letters separated by commas."), sticky='w')
tkgrid(tklabel(frame.left, text=' '))
frameMiss <- tkframe(frame.left)
assign('missVal', tclVar(""), envir=test.char)
entry.miss <- tkentry(frameMiss ,width="10", textvariable=test.char[['missVal']])
tkgrid(frameMiss, sticky='w')
tkgrid(tklabel(frameMiss, text="Missing answers"), entry.miss, sticky='w')
tkgrid(tklabel(frame.left, text=paste("Note: Any numbers which represent a missing.",
"'space' is automatically added as a missing character.")), sticky='w')
tkgrid(tklabel(frame.left, text="Type only numbers separated by commas."), sticky='w')
tkgrid(tklabel(frame.left, text=' '))
frameReversed <- tkframe(frame.left)
assign('reversedVal', tclVar(""), envir=test.char)
entry.reversed <- tkentry(frameReversed, width="60", textvariable=test.char[['reversedVal']])
tkgrid(frameReversed, sticky='w')
tkgrid(tklabel(frameReversed, text="Reversed items"), entry.reversed, sticky='w')
tkgrid(tklabel(frame.left, text=paste("Note: Left blank if none of the items should be reversed.",
"Otherwise, use commas to separate the numbers.")), sticky='w')
tkgrid(tklabel(frame.left, text=' '))
frameScoring <- tkframe(frame.left)
rb.sum <- tkradiobutton(frameScoring)
rb.mean <- tkradiobutton(frameScoring)
rb.prorat.no <- tkradiobutton(frameScoring)
rb.prorat.yes <- tkradiobutton(frameScoring)
assign('scoringVal', tclVar("sum"), envir=test.char)
tkconfigure(rb.sum, variable=test.char[['scoringVal']], value="sum", command=raw.is.sum)
tkconfigure(rb.mean, variable=test.char[['scoringVal']], value="mean", command=raw.is.mean)
rb.prorat.no <- tkradiobutton(frameScoring)
rb.prorat.yes <- tkradiobutton(frameScoring)
assign('prorrateVal', tclVar("no"), envir=test.char)
tkconfigure(rb.prorat.no, variable=test.char[['prorrateVal']], value="no")
tkconfigure(rb.prorat.yes, variable=test.char[['prorrateVal']], value="yes", command=prorrate.yes)
tkgrid(frameScoring, sticky='w')
tkgrid(tklabel(frameScoring, text="Scoring Procedure? "),
tklabel(frameScoring, text="Mean"), rb.mean,
tklabel(frameScoring, text="Add"),rb.sum,
tklabel(frameScoring, text="If add, prorrate missings? "),
tklabel(frameScoring, text="No"), rb.prorat.no,
tklabel(frameScoring, text="Yes"),rb.prorat.yes, sticky='w')
tkgrid(tklabel(frame.left, text=' '))
frameN.scales <- tkframe(frame.left)
assign('n.scalesVal', tclVar(""), envir=test.char)
entry.n.scales <- tkentry(frameN.scales ,width="2", textvariable=test.char[['n.scalesVal']])
tkgrid(frameN.scales, sticky='w')
tkgrid(tklabel(frameN.scales, text="Enter the number of scales"), entry.n.scales, sticky='w')
rb.trans.No <- tkradiobutton(frame.rigth)
rb.trans.Tmean <- tkradiobutton(frame.rigth)
rb.trans.Ttable <- tkradiobutton(frame.rigth)
rb.trans.Other <- tkradiobutton(frame.rigth)
rb.graph.yes <- tkradiobutton(frame.rigth)
rb.graph.no <- tkradiobutton(frame.rigth)
rb.equal.yes <- tkradiobutton(frame.rigth)
rb.equal.no <- tkradiobutton(frame.rigth)
assign('transVal', tclVar('no'), envir=test.char)
assign('graphVal', tclVar('no'), envir=test.char)
assign('equalVal', tclVar('no'), envir=test.char)
assign('name.transVal', tclVar('Centil'), envir=test.char)
assign('n.age.groupsVal', tclVar('1'), envir=test.char)
entry.name <- tkentry(frame.rigth, width='5', textvariable=test.char[['name.transVal']], state='disabled')
entry.n.age.groups <- tkentry(frame.rigth, width='1', textvariable=test.char[['n.age.groupsVal']], state='disabled')
tkconfigure(rb.trans.No, variable=test.char[['transVal']], value="no", command=no.trans)
tkconfigure(rb.trans.Tmean, variable=test.char[['transVal']], value="Tmean", command=Tmean.trans)
tkconfigure(rb.trans.Ttable, variable=test.char[['transVal']], value="Ttable", command=Ttable.trans)
tkconfigure(rb.trans.Other, variable=test.char[['transVal']], value="Other", command=other.trans)
tkconfigure(rb.graph.yes, variable=test.char[['graphVal']], value="yes", state='disabled')
tkconfigure(rb.graph.no, variable=test.char[['graphVal']], value="no", state='disabled')
tkconfigure(rb.equal.yes, variable=test.char[['equalVal']], value="yes", state='disabled')
tkconfigure(rb.equal.no, variable=test.char[['equalVal']], value="no", state='disabled')
tkgrid(tklabel(frame.rigth, text="Choose one option for transforming raw scores:"), sticky='w')
tkgrid(tklabel(frame.rigth, text=" 1. Do NOT transform"), rb.trans.No, sticky='w')
tkgrid(tklabel(frame.rigth, text=" 2. T'scores using mean & sd"), rb.trans.Tmean, sticky='w')
tkgrid(tklabel(frame.rigth, text=" 3. T'scores using a table"), rb.trans.Ttable, sticky='w')
tkgrid(tklabel(frame.rigth, text=" 4. Other transformation using a table"), rb.trans.Other, sticky='w')
tkgrid(tklabel(frame.rigth, text=" Choose a name, e.g.: 'Centil'"),
entry.name, sticky='w')
tkgrid(tklabel(frame.rigth, text=""), sticky='w')
tkgrid(tklabel(frame.rigth, text=" Number of age-groups norms"),
entry.n.age.groups, sticky='w')
tkgrid(tklabel(frame.rigth, text=" Transformation is equal for both sexes?"),
tklabel(frame.rigth, text='Yes'), rb.equal.yes,
tklabel(frame.rigth, text='No'), rb.equal.no, sticky='w')
tkgrid(tklabel(frame.rigth, text=" Add a pseudo-graph for T'scores?"),
tklabel(frame.rigth, text='Yes'), rb.graph.yes,
tklabel(frame.rigth, text='No'), rb.graph.no, sticky='w')
doneTest <- tclVar(0)
tkgrid(tklabel(top.test, text=''))
OkTest.but <-tkbutton(top.test, text=" OK ", command=OnOkTest)
tkgrid(OkTest.but, columnspan=2)
tkgrid(tklabel(top.test,
text='Close the window to cancel adding a new test.'),
columnspan=2)
tkbind(top.test, "<Destroy>", function() tclvalue(doneTest) <- 3)
tkfocus(top.test)
tkwait.variable(doneTest)
if (tclvalue(doneTest)==1) {
OkTest <- 'yes'
acronymTest <- tclvalue(test.char[['acronymTestVal']])
acronymTest <- sub(' +$', '', acronymTest)
acronymTest <- sub('^ +', '', acronymTest)
n.items <- as.numeric(tclvalue(test.char[['n.itemsVal']]))
valid <- tclvalue(test.char[['validVal']])
valid <- as.numeric(unlist(strsplit(valid, ',')))
miss <- tclvalue(test.char[['missVal']])
miss <- as.numeric(unlist(strsplit(miss, ',')))
reversed <- tclvalue(test.char[['reversedVal']])
reversed <- as.numeric(unlist(strsplit(reversed, ',')))
n.scales <- as.numeric(tclvalue(test.char[['n.scalesVal']]))
test.characteristics <- list(acronymTest <- acronymTest,
nameTest <- tclvalue(test.char[['nameTestVal']]),
ref <- tclvalue(test.char[['refVal']]),
comm <- tclvalue(test.char[['commVal']]),
n.items <- n.items,
valid <- valid,
miss <- miss,
reversed <- reversed,
scoring <- tclvalue(test.char[['scoringVal']]),
prorrate <- tclvalue(test.char[['prorrateVal']]),
n.scales <- n.scales,
trans <- tclvalue(test.char[['transVal']]),
equal <- tclvalue(test.char[['equalVal']]),
graph <- tclvalue(test.char[['graphVal']]),
name.trans <- tclvalue(test.char[['name.transVal']]),
n.age.agroups <- tclvalue(test.char[['n.age.groupsVal']]))
} else {
OkTest <- 'no'
test.characteristics <- as.list(rep('', 15))
}
tkdestroy(top.test)
list(OkTest=OkTest, test.characteristics=test.characteristics)
}
write.test.begining <- function(acronymTest, nameTest, ref, n.items, valid,
miss, comm, reversed, trans, graph) {
cat(paste('
acronymTest,
'scale scoring script'),
file='tmp')
cat(paste('\n
Sys.Date()),
file='tmp', append=TRUE)
cat('\n
cat(paste('\ntestChar <- list(acronym = "',
acronymTest,
'",',
sep=''),
file='tmp', append=TRUE)
cat(paste('\n name = "',
nameTest,
'",',
sep=''),
file='tmp', append=TRUE)
cat(paste('\n ref = "',
ref,
'",',
sep=''),
file='tmp', append=TRUE)
cat(paste('\n n.items = ',
n.items,
',',
sep=''),
file='tmp', append=TRUE)
cat('\n valid = c(', file='tmp', append=TRUE)
if (length(valid)>1)
for (i in 1:(length(valid)-1)) cat(paste(valid[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(valid[length(valid)],
'),',
sep=''),
file='tmp', append=TRUE)
cat('\n miss = c(', file='tmp', append=TRUE)
if (length(miss)>1)
for (i in 1:(length(miss)-1)) cat(paste(miss[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(miss[length(miss)],
'),',
sep=''),
file='tmp', append=TRUE)
cat(paste('\n comm = "',
comm,
'")',
sep=''),
file='tmp', append=TRUE)
cat('\n\nscoring.fun <- function(answers, sex, age, id, date.test, comm) {', file='tmp', append=TRUE)
cat('\n
cat('\n
cat('\n answers <- as.numeric(answers)
if (length(miss)!=0) {
cat(paste('\n answers[answers %in% c(',
miss,
')] <- NA
sep=''),
file='tmp', append=TRUE)
}
cat('\n blanks <- sum(is.na(answers))
cat(paste('\n pcnt.blanks <- round((blanks / ',
n.items,
') * 100)
sep=''),
file='tmp', append=TRUE)
if (sum(nchar(reversed))!=0) {
cat('\n
cat('\n reversed.items <- c(', file='tmp', append=TRUE)
if (length(reversed)>1)
for (i in 1:(length(reversed)-1)) cat(paste(reversed[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(reversed[length(reversed)],
')',
sep=''),
file='tmp', append=TRUE)
max.answ <- max(valid)
cat(paste('\n answers[reversed.items] <- (',
max.answ,
' + 1) - answers[reversed.items]',
sep=''),
file='tmp', append=TRUE)
}
cat('\n results <- data.frame(NULL)
if (trans=='Tmean') {
cat('\n\n toT <- function(raw.score, mean, sd) {
cat('\n T.score <- round(((raw.score - mean) / sd) * 10 + 50)' , file='tmp', append=TRUE)
cat('\n T.score' , file='tmp', append=TRUE)
cat('\n }
}
if (graph=='yes') {
cat('\n\n makeGraph <- function(T.score) {
cat('\n template <- "| : : | : | : | : : |"' , file='tmp', append=TRUE)
cat('\n options(warn=-1)', file='tmp', append=TRUE)
cat('\n T.score <- as.integer(T.score)
cat('\n options(warn=0)', file='tmp', append=TRUE)
cat('\n if (!is.na(T.score)) {', file='tmp', append=TRUE)
cat('\n if (T.score < 0) T.score <- 0' , file='tmp', append=TRUE)
cat('\n else if (T.score > 100) T.score <- 100' , file='tmp', append=TRUE)
cat('\n position <- round((T.score / 2) + 1)' , file='tmp', append=TRUE)
cat(paste('\n graph <- paste(substr(template, 1, position-1),',
' substr(template, position + 1, nchar(template)),',
' sep="o")
sep='\n'),
file='tmp', append=TRUE)
cat('\n } else {' , file='tmp', append=TRUE)
cat('\n graph <- "Not graphicable"',
file='tmp', append=TRUE)
cat('\n }', file='tmp', append=TRUE)
cat('\n graph', file='tmp', append=TRUE)
cat('\n }
}
}
make.scale.window <- function(scale.num, n.items, valid, trans, equal, graph, name.trans) {
ValidateScaleChar <- function() {
is.OkScale='yes'
options(warn=-1)
acronymScale <- tclvalue(acronymScaleVal)
acronymScale <- sub(' +$', '', acronymScale)
acronymScale <- sub('^ +', '', acronymScale)
tmp <- grep('^[[:alpha:]]([[:alnum:]]|_)*$', acronymScale)
if (length(tmp)==0) {
is.OkScale <- 'no'
msg <- paste('Acronym is not valid.',
'\nThe first character should be a letter',
'Only alphanumeric and the character "_" are allowed.',
sep='\n')
tkmessageBox(message=msg, icon="error", type="ok")
}
tmp <- tclvalue(itemsVal)
items <- as.numeric(unlist(strsplit(tmp, ',')))
if (length(items) == 0 ||
any(is.na(items)) ||
any(grep('\\.', items))) {
is.OkScale <- 'no'
tkconfigure(entry.items, state='normal')
tkmessageBox(message="Items are not valid.", icon="error", type="ok")
}
if (max(items, na.rm=TRUE)>n.items) {
is.OkScale <- 'no'
tkconfigure(entry.items, state='normal')
tkmessageBox(message="Some value is greather than the number of items of the test.",
icon="error", type="ok")
}
if (trans=='no' || trans=='Tmean')
assign('tableDone', 'no table is needed', envir=scale.char)
if (trans=='Tmean') {
if (equal=='yes') {
mean.1 <- as.numeric(tclvalue(mean.1Val))
if(is.na(mean.1)) {
is.OkScale <- 'no'
tkmessageBox(message="Mean is not valid.", icon="error", type="ok")
}
sd.1 <- as.numeric(tclvalue(sd.1Val))
if(is.na(sd.1)) {
is.OkScale <- 'no'
tkmessageBox(message="SD is not valid.", icon="error", type="ok")
}
} else {
mean.males <- as.numeric(tclvalue(mean.malesVal))
if(is.na(mean.malesVal)) {
is.OkScale <- 'no'
tkmessageBox(message="Mean for males is not valid.",
icon="error", type="ok")
}
sd.males <- as.numeric(tclvalue(sd.malesVal))
if(is.na(sd.malesVal)) {
is.OkScale <- 'no'
tkmessageBox(message="SD for males is not valid.",
icon="error", type="ok")
}
mean.females <- as.numeric(tclvalue(mean.femalesVal))
if(is.na(mean.femalesVal)) {
is.OkScale <- 'no'
tkmessageBox(message="Mean for females is not valid.",
icon="error", type="ok")
}
sd.females <- as.numeric(tclvalue(sd.femalesVal))
if(is.na(sd.femalesVal)) {
is.OkScale <- 'no'
tkmessageBox(message="SD for females is not valid.",
icon="error", type="ok")
}
}
}
if (scale.char[['tableDone']]=='no') {
is.OkScale <- 'no'
tkmessageBox(message="You need open and fill the transformation table.",
icon="error", type="ok")
} else
if (any(grepl('^-$', unlist(scale.char[['transTable']]))) ||
any(grepl('^$', unlist(scale.char[['transTable']])))) {
is.OkScale <- 'no'
msg <- paste('All or some of the transformations values are missing',
'Open and refill the table.',
sep='\n')
tkmessageBox(message=msg, icon="error", type="ok")
}
options(warn=0)
is.OkScale
}
top.scale <- tktoplevel()
tkwm.title(top.scale, paste("Definition of scale number", scale.num))
tkwm.resizable(top.scale, FALSE, FALSE)
frameAcronym <- tkframe(top.scale)
acronymScaleVal <- tclVar("")
entry.acronymScale <- tkentry(frameAcronym ,width="10", textvariable=acronymScaleVal)
tkgrid(frameAcronym, sticky='w')
tkgrid(tklabel(frameAcronym, text="Enter an acronym for the scale"), entry.acronymScale, sticky='w')
tkgrid(tklabel(top.scale, text="Note: Use only letters, numbers and '_'. The first character must be a letter."), sticky='w')
tkgrid(tklabel(top.scale, text=' '))
frameName <- tkframe(top.scale)
nameScaleVal <- tclVar("")
entry.name <- tkentry(frameName ,width="40", textvariable=nameScaleVal)
tkgrid(frameName, sticky='w')
tkgrid(tklabel(frameName, text="Enter the scale's name (optional)"), entry.name, sticky='w')
tkgrid(tklabel(top.scale, text=' '))
frameItems <- tkframe(top.scale)
itemsVal <- tclVar("")
entry.items <- tkentry(frameItems, width="60", textvariable=itemsVal)
tkgrid(frameItems, sticky='w')
tkgrid(tklabel(frameItems, text="Items making up the scale"), entry.items, sticky='w')
tkgrid(tklabel(top.scale, text="Note: Use commas to separate the numbers."), sticky='w')
if (trans=='Tmean') {
if (equal=='yes') {
tkgrid(tklabel(top.scale, text=' '))
frameMean.sd <- tkframe(top.scale)
mean.1Val <- tclVar("")
sd.1Val <- tclVar("")
entry.mean <- tkentry(frameMean.sd ,width="8", textvariable=mean.1Val)
entry.sd <- tkentry(frameMean.sd ,width="8", textvariable=sd.1Val)
tkgrid(frameMean.sd, sticky='w')
tkgrid(tklabel(frameMean.sd, text="Mean"),entry.mean,
tklabel(frameMean.sd, text=" SD"), entry.sd, sticky='w')
} else {
tkgrid(tklabel(top.scale, text=' '))
frameMean.sd.males <- tkframe(top.scale)
mean.malesVal <- tclVar("")
sd.malesVal <- tclVar("")
entry.mean.males <- tkentry(frameMean.sd.males ,width="8", textvariable=mean.malesVal)
entry.sd.males <- tkentry(frameMean.sd.males ,width="8", textvariable=sd.malesVal)
tkgrid(frameMean.sd.males, sticky='w')
tkgrid(tklabel(frameMean.sd.males, text="Males: Mean"), entry.mean.males,
tklabel(frameMean.sd.males, text=" SD"), entry.sd.males,
sticky='w')
frameMean.sd.females <- tkframe(top.scale)
mean.femalesVal <- tclVar("")
sd.femalesVal <- tclVar("")
entry.mean.females <- tkentry(frameMean.sd.females ,width="8", textvariable=mean.femalesVal)
entry.sd.females <- tkentry(frameMean.sd.females ,width="8", textvariable=sd.femalesVal)
tkgrid(frameMean.sd.females, sticky='w')
tkgrid(tklabel(frameMean.sd.females, text="Females: Mean"), entry.mean.females,
tklabel(frameMean.sd.females, text=" SD"), entry.sd.females,
sticky='w')
}
} else if (trans=='Ttable' || trans=='Other') {
make.table.win <- function(valid, items, equal) {
tkconfigure(entry.items, state='disabled')
n.items <- length(unlist(strsplit(items, ',')))
min.score <- min(valid)*n.items
max.score <- max(valid)*n.items
n.scores <- max.score - min.score + 1
if (equal=='yes') {
matrixTrans <- matrix(c(as.character(min.score:max.score), rep('-', n.scores)),
nrow=n.scores,
ncol=2)
matrixTrans <- rbind(c('Raw', 'Transf'), matrixTrans)
tclArrayTrans <- tclArray()
for (i in (1:(n.scores+1)))
for (j in (1:2))
tclArrayTrans[[i-1,j-1]] <- matrixTrans[i,j]
nrow <- n.scores+1
ncol <- 2
} else {
matrixTrans <- matrix(c(as.character(min.score:max.score), rep('-', 2*(n.scores))),
nrow=n.scores,
ncol=3)
matrixTrans <- rbind(c('Raw', 'Male', 'Female'), matrixTrans)
tclArrayTrans <- tclArray()
for (i in (1:(n.scores+1)))
for (j in (1:3))
tclArrayTrans[[i-1,j-1]] <- matrixTrans[i,j]
nrow <- n.scores+1
ncol <- 3
}
trans.win <- tktoplevel()
tkwm.resizable(trans.win, FALSE, FALSE)
tkgrab.set(trans.win)
tableFrame <- tkframe(trans.win)
tkgrid(tableFrame)
tclRequire("Tktable")
tkwm.title(trans.win, 'Transform')
table <- tkwidget(tableFrame, "table",
rows=nrow, cols=ncol,
titlerows=1, titlecols=1,
height=16, width=ncol+1,
yscrollcommand=function(...) tkset(yscr,...))
yscr <- tkscrollbar(tableFrame, command=function(...)tkyview(table,...))
tkgrid(table, yscr)
tkgrid.configure(yscr, sticky="nsw")
tkconfigure(table, variable=tclArrayTrans, selectmode="single", background="white")
tkgrid(tklabel(trans.win, text='Note: "-" sign will be automatically removed.'))
tkgrid(tklabel(trans.win, text=' '))
doneTransVal <- tclVar(0)
OkTrans.but <- tkbutton(trans.win, text=" OK ", command=function() tclvalue(doneTransVal) <- 1)
tkgrid(OkTrans.but)
tkgrid(tklabel(trans.win, text='Close the window to cancel the table.'))
tkgrid(tklabel(trans.win, text='Canceling the table allows the reedition of items.'))
tkbind(trans.win, "<Destroy>", function() tclvalue(doneTransVal) <- 3)
tkfocus(trans.win)
tkwait.variable(doneTransVal)
if (equal=='yes') {
transTable <- character(n.scores)
for (i in 1:n.scores) transTable[i] <- tclvalue(tclArrayTrans[[i, 1]])
}
else {
transTableMales <- character(n.scores)
for (i in 1:n.scores) transTableMales[i] <- tclvalue(tclArrayTrans[[i, 1]])
transTableFemales <- character(n.scores)
for (i in 1:n.scores) transTableFemales[i] <- tclvalue(tclArrayTrans[[i, 2]])
}
if (tclvalue(doneTransVal)==3) {
tkconfigure(entry.items, state='normal')
msg <- paste('The table has been canceled.',
'All the transformations are set to "-".',
'Edition of items is enabled.',
sep='\n')
tkmessageBox(message=msg, icon='warning', type='ok')
}
tkdestroy(trans.win)
if (equal=='yes') {
transTable <- list(transTable)
} else
transTable <- list(transTableMales, transTableFemales)
assign('transTable', transTable, envir=scale.char)
assign('tableDone', 'yes', envir=scale.char)
}
tkgrid(tklabel(top.scale, text=' '))
defTableFrame <- tkframe(top.scale)
assign('tableDone', 'no', envir=scale.char)
openTable.but <- tkbutton(top.scale, text='Open',
command=function() make.table.win(valid, tclvalue(itemsVal), equal))
tkgrid.configure(defTableFrame, sticky='w')
tkgrid(tklabel(defTableFrame,
text = 'Transformation table: '),
openTable.but,
sticky='w')
tkgrid(tklabel(top.scale,
text='Note: To avoid mismatch between number of items and number of raw scores,'),
sticky='w')
tkgrid(tklabel(top.scale,
text=' when the table is openned, the edition of items is blocked'),
sticky='w')
tkgrid(tklabel(top.scale,
text=' and the table is reseted accordingly the number of items.'),
sticky='w')
}
OnOkScale <- function() {
OkScale <- ValidateScaleChar()
if (OkScale=='yes') tclvalue(doneScale) <- 1
}
tkgrid(tklabel(top.scale, text=' '))
doneScale <- tclVar(0)
scale.butFrame <- tkframe(top.scale)
tkgrid(scale.butFrame)
OkScale.but <- tkbutton(scale.butFrame,
text=" OK ",
command=OnOkScale)
cancelScale.but <- tkbutton(scale.butFrame,
text="Cancel scale",
command=function() tclvalue(doneScale) <- 2)
cancelTest.but<- tkbutton(scale.butFrame,
text=" Cancel test ",
command=function() tclvalue(doneScale) <- 3)
tkgrid(OkScale.but, cancelScale.but, cancelTest.but)
tkbind(top.scale, '<Destroy>', function() tclvalue(doneScale) <- 2)
tkfocus(top.scale)
tkwait.variable(doneScale)
if (tclvalue(doneScale)==1) {
acronymScale <- tclvalue(acronymScaleVal)
acronymScale <- sub(' +$', '', acronymScale)
acronymScale <- sub('^ +', '', acronymScale)
nameScale <- tclvalue(nameScaleVal)
items <- tclvalue(itemsVal)
items <- as.numeric(unlist(strsplit(items, ',')))
mean.1 <- NA
sd.1 <- NA
mean.males <- NA
mean.females <- NA
sd.males <- NA
sd.females <- NA
trans.1 <- NA
trans.males <- NA
trans.females <- NA
if(trans=='Tmean' && equal=='yes') {
mean.1 <- as.numeric(tclvalue(mean.1Val))
sd.1 <- as.numeric(tclvalue(sd.1Val))
}
else if (trans=='Tmean' && equal=='no') {
mean.males <- as.numeric(tclvalue(mean.malesVal))
sd.males <- as.numeric(tclvalue(sd.malesVal))
mean.females <- as.numeric(tclvalue(mean.femalesVal))
sd.females <- as.numeric(tclvalue(sd.femalesVal))
}
else if ((trans=='Ttable' || trans=='Other') && equal=='yes') {
trans.1 <- scale.char[['transTable']]
trans.1 <- trans.1[[1]]
trans.1 <- gsub('(^-)|(-$)', '', trans.1)
if (sum(!grepl('^[0-9]+$', trans.1))>0) {
assign('trans.is.numeric', 'no', envir=test.char)
assign('trans.is.numeric', 'no', envir=scale.char)
} else
assign('trans.is.numeric', 'yes', envir=scale.char)
}
else if ((trans=='Ttable' || trans=='Other') && equal=='no') {
trans <- scale.char[['transTable']]
trans.males <- trans[[1]]
trans.females <- trans[[2]]
trans.males <- gsub('(^-)|(-$)', '', trans.males)
trans.females <- gsub('(^-)|(-$)', '', trans.females)
if (sum(!grepl('^[0-9]+$', trans.males))>0 || sum(!grepl('^[0-9]+$', trans.females))>0) {
assign('trans.is.numeric', 'no', envir=test.char)
assign('trans.is.numeric', 'no', envir=scale.char)
} else
assign('trans.is.numeric', 'yes', envir=test.char)
}
OkScale <- 'yes'
n.items <- length(items)
min.score <- min(valid)*n.items
scale.characteristics <- list(acronymScale=acronymScale,
nameScale=nameScale,
items=items,
mean.1=mean.1,
sd.1=sd.1,
mean.males=mean.males,
mean.females=mean.females,
sd.males=sd.males,
sd.females=sd.females,
trans.1=trans.1,
trans.males=trans.males,
trans.females=trans.females,
min.score=min.score)
} else
if (tclvalue(doneScale)==2) {
OkScale <- 'repeat scale'
scale.characteristics <- list('')
} else {
OkScale <- 'no'
scale.characteristics <- list('')
}
tkdestroy(top.scale)
list(OkScale=OkScale, scale.characteristics=scale.characteristics)
}
write.scale <- function(acronymScale, nameScale, items,
scale.num, scoring, prorrate, trans, equal, name.trans, graph,
mean.1, sd.1,
mean.males, mean.females, sd.males, sd.females,
trans.1,
trans.males, trans.females, min.score) {
cat(paste('\n\n
acronymScale,
'scale scoring commands'),
file='tmp', append=TRUE)
cat('\n
cat(paste('\n results[',
scale.num,
', "Acronym"] <- "',
acronymScale,
'"
sep=''),
file='tmp', append=TRUE)
cat(paste('\n results[',
scale.num,
', "Scale"] <- "',
nameScale,
'"
sep=''),
file='tmp', append=TRUE)
cat('\n
cat('\n items <- c(', file='tmp', append=TRUE)
if (length(items)>1)
for (i in 1:(length(items)-1)) cat(paste(items[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(items[length(items)],
')',
sep=''),
file='tmp', append=TRUE)
cat(paste('\n results[',
scale.num,
', "Miss"] <- sum(is.na(answers[items]))
sep=''),
file='tmp', append=TRUE)
cat(paste('\n if (results[',
scale.num,
', "Miss"] == length(items)) {
sep=''),
file='tmp', append=TRUE)
cat(paste('\n results[',
scale.num,
', "Raw"] <- NA',
sep=''),
file='tmp', append=TRUE)
if (trans=='Tmean' || trans=='Ttable') {
cat(paste('\n results[',
scale.num,
', "T"] <- NA',
sep=''),
file='tmp', append=TRUE)
}
if (trans=='Other') {
cat(paste('\n results[',
scale.num,
', "',
name.trans,
'"] <- NA',
sep=''),
file='tmp', append=TRUE)
}
if (graph=='yes')
cat(paste('\n results[',
scale.num,
', "Graph"] <- "All items missing"',
sep=''),
file='tmp', append=TRUE)
cat('\n } else {',
file='tmp', append=TRUE)
if (scoring=='sum' && prorrate=='no')
cat(paste('\n results[',
scale.num,
', "Raw"] <- sum(answers[items], na.rm=TRUE)
sep=''),
file='tmp', append=TRUE)
else if (scoring=='sum' && prorrate=='yes')
cat(paste('\n results[',
scale.num,
', "Raw"] <- round(mean(answers[items], na.rm=TRUE)*length(items), 2)
sep=''),
file='tmp', append=TRUE)
else
cat(paste('\n results[',
scale.num,
', "Raw"] <- round(mean(answers[items], na.rm=TRUE), 2)
sep=''),
file='tmp', append=TRUE)
if(trans=='Tmean' && equal=='no') {
cat(paste('\n if (sex=="Male") results[',
scale.num,
', "T"] <- toT(results[',
scale.num,
', "Raw"], ',
mean.males,
', ',
sd.males,
')
sep=''),
file='tmp', append=TRUE)
cat(paste('\n else results[',
scale.num,
', "T"] <- toT(results[',
scale.num,
', "Raw"], ',
mean.females,
', ',
sd.females,
')',
sep=''),
file='tmp', append=TRUE)
} else if(trans=='Tmean' && equal=='yes') {
cat(paste('\n results[',
scale.num,
', "T"] <- toT(results[',
scale.num,
', "Raw"], ',
mean.1,
', ',
sd.1,
')
sep=''),
file='tmp', append=TRUE)
} else if ((trans=='Ttable' || trans=='Other') && equal=='no') {
cat('\n
if (scale.char[['trans.is.numeric']]=='yes') {
cat('\n trans.males.table <- c(', file='tmp', append=TRUE)
if (length(trans.males)>1)
for (i in 1:(length(trans.males)-1)) cat(paste(trans.males[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(trans.males[length(trans.males)],
')',
sep=''),
file='tmp', append=TRUE)
} else {
cat('\n trans.males.table <- c(', file='tmp', append=TRUE)
if (length(trans.males)>1)
for (i in 1:(length(trans.males)-1)) cat(paste('"', trans.males[i], '", ', sep=''), file='tmp', append=TRUE)
cat(paste('"',
trans.males[length(trans.males)],
'")',
sep=''),
file='tmp', append=TRUE)
}
if (scale.char[['trans.is.numeric']]=='yes') {
cat('\n trans.females.table <- c(', file='tmp', append=TRUE)
if (length(trans.females)>1)
for (i in 1:(length(trans.females)-1)) cat(paste(trans.females[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(trans.females[length(trans.females)],
')',
sep=''),
file='tmp', append=TRUE)
} else {
cat('\n trans.females.table <- c(', file='tmp', append=TRUE)
if (length(trans.females)>1)
for (i in 1:(length(trans.females)-1)) cat(paste('"', trans.females[i], '", ', sep=''), file='tmp', append=TRUE)
cat(paste('"',
trans.females[length(trans.females)],
'")',
sep=''),
file='tmp', append=TRUE)
}
if (scoring=='sum' && prorrate=='no')
cat(paste('\n index <- results[',
scale.num,
', "Raw"]',
sep=''),
file='tmp', append=TRUE)
else
cat(paste('\n index <- round(results[',
scale.num,
', "Raw"])
sep=''),
file='tmp', append=TRUE)
cat(paste('\n index <- ',
1 - min.score,
' + index
1 - min.score,
', because raw scores begin at ',
min.score,
sep=''),
file='tmp', append=TRUE)
cat(paste('\n if (sex=="Male") results[',
scale.num,
', "',
sep=''),
file='tmp', append=TRUE)
if (trans=='Ttable')
cat('T', file='tmp', append=TRUE)
else
cat(name.trans , file='tmp', append=TRUE)
cat('"] <- trans.males.table[index]', file='tmp', append=TRUE)
cat(paste('\n else results[',
scale.num,
', "',
sep=''),
file='tmp', append=TRUE)
if (trans=='Ttable')
cat('T', file='tmp', append=TRUE)
else
cat(name.trans , file='tmp', append=TRUE)
cat('"] <- trans.females.table[index]', file='tmp', append=TRUE)
} else if ((trans=='Ttable' || trans=='Other') && equal=='yes') {
cat('\n
if (scale.char[['trans.is.numeric']]=='yes') {
cat('\n trans.table <- c(', file='tmp', append=TRUE)
if (length(trans.1)>1)
for (i in 1:(length(trans.1)-1)) cat(paste(trans.1[i], ', ', sep=''), file='tmp', append=TRUE)
cat(paste(trans.1[length(trans.1)], ')', sep=''), file='tmp', append=TRUE)
} else {
cat('\n trans.table <- c(', file='tmp', append=TRUE)
if (length(trans.1)>1)
for (i in 1:(length(trans.1)-1)) cat(paste('"', trans.1[i], '", ', sep=''), file='tmp', append=TRUE)
cat(paste('"', trans.1[length(trans.1)], '")', sep=''), file='tmp', append=TRUE)
}
if (scoring=='sum' && prorrate=='no')
cat(paste('\n index <- results[',
scale.num,
', "Raw"]',
sep=''),
file='tmp', append=TRUE)
else
cat(paste('\n index <- round(results[',
scale.num,
', "Raw"])
sep=''),
file='tmp', append=TRUE)
cat(paste('\n index <- ',
1 - min.score,
' + index
1 - min.score,
', because raw scores begin at ',
min.score,
sep=''),
file='tmp', append=TRUE)
cat(paste('\n results[',
scale.num,
', "',
sep=''),
file='tmp', append=TRUE)
if (trans=='Ttable')
cat('T', file='tmp', append=TRUE)
else
cat(name.trans , file='tmp', append=TRUE)
cat('"] <- trans.table[index]', file='tmp', append=TRUE)
}
if(graph=='yes')
cat(paste('\n results[',
scale.num,
', "Graph"] <- makeGraph(results[',
scale.num,
', "T"])
sep=''),
file='tmp', append=TRUE)
cat('\n }', file='tmp', append=TRUE)
}
write.test.end <- function(acronymTest, trans, graph, name.trans) {
cat('\n\n
cat('\n
if (graph=='no') {
cat('\n results.scores <- unlist(results[-c(1, 2)])
file='tmp', append=TRUE)
} else {
cat('\n results.scores <- unlist(results[-c(1, 2, 6)])
file='tmp', append=TRUE)
}
cat('\n names <- paste(results$Acronym, names(results.scores), sep=".")',
file='tmp', append=TRUE)
cat('\n names(results.scores) <- sub("[0-9]+$", "", names)
file='tmp', append=TRUE)
if (graph=='yes') {
cat('\n\n
cat('\n
cat('\n names(results)[6] <- "0 10 20 30 40 50 60 70 80 90 100"',
file='tmp', append=TRUE)
}
cat('\n\n
cat('\n
cat('\n results.lst <- list(paste("Total number of missing items: ",',
file='tmp', append=TRUE)
cat('\n blanks,',
file='tmp', append=TRUE)
cat('\n " (",',
file='tmp', append=TRUE)
cat('\n pcnt.blanks,',
file='tmp', append=TRUE)
cat('\n "%)",',
file='tmp', append=TRUE)
cat('\n sep=""))',
file='tmp', append=TRUE)
cat('\n\n
cat('\n
cat('\n list(results.lst = results.lst,', file='tmp', append=TRUE)
cat('\n results.df = results,', file='tmp', append=TRUE)
cat('\n results.scores = results.scores)', file='tmp', append=TRUE)
cat('\n\n}
file.name <- paste('TST_', acronymTest, '.r', sep='')
file.rename(from='tmp', to=file.name)
msg <- paste("Test definition and scoring script have been saved as TST_",
acronymTest, '.r', sep='')
tkmessageBox(message=msg)
}
ret.values <- make.test.window()
continue.test <- ret.values[[1]]
test.characteristics <- ret.values[[2]]
acronymTest <- test.characteristics[[1]]
nameTest <- test.characteristics[[2]]
ref <- test.characteristics[[3]]
comm <- test.characteristics[[4]]
n.items <- test.characteristics[[5]]
valid <- test.characteristics[[6]]
miss <- test.characteristics[[7]]
reversed <- test.characteristics[[8]]
scoring <- test.characteristics[[9]]
prorrate <- test.characteristics[[10]]
n.scales <- test.characteristics[[11]]
trans <- test.characteristics[[12]]
equal <- test.characteristics[[13]]
graph <- test.characteristics[[14]]
name.trans <- test.characteristics[[15]]
if (continue.test=='yes')
write.test.begining(acronymTest, nameTest, ref, n.items, valid,
miss, comm, reversed, trans, graph)
if (continue.test=='yes') {
scale.num <-0
while ((scale.num < n.scales) && (continue.test == 'yes')) {
scale.num <- scale.num + 1
ret.values <- make.scale.window(scale.num, n.items, valid, trans,
equal, graph, name.trans)
OkScale <- ret.values[[1]]
scale.characteristics <- ret.values[[2]]
acronymScale <- scale.characteristics['acronymScale']
nameScale <- scale.characteristics['nameScale']
items <- unlist(scale.characteristics['items'])
mean.1 <- scale.characteristics['mean.1']
sd.1 <- scale.characteristics['sd.1']
mean.males <- scale.characteristics['mean.males']
mean.females <- scale.characteristics['mean.females']
sd.males <- scale.characteristics['sd.males']
sd.females <- scale.characteristics['sd.females']
trans.1 <- unlist(scale.characteristics['trans.1'])
trans.males <- unlist(scale.characteristics['trans.males'])
trans.females <- unlist(scale.characteristics['trans.females'])
min.score <- unlist(scale.characteristics['min.score'])
if (OkScale=='yes')
write.scale(acronymScale, nameScale, items,
scale.num, scoring, prorrate, trans,
equal, name.trans, graph,
mean.1, sd.1,
mean.males, mean.females,
sd.males, sd.females,
trans.1,
trans.males, trans.females, min.score)
else
if (OkScale=='repeat scale') {
scale.num <- scale.num - 1
continue.test <- 'yes'
}
else
continue.test <- 'no'
}
}
if (continue.test=='yes')
write.test.end(acronymTest, trans, graph, name.trans)
if (continue.test=='no') {
msg <- "Test definition has been canceled."
tkmessageBox(message=msg, icon='warning', type='ok')
options(warn=-1)
try(dummy <- file.remove('tmp'))
options(warn=0)
}
TestScorerGUI()
}
delete.test <- function() {
content <- dir()
existing.tests <- content[grep('TST_.+\\.r$', content)]
existing.tests <- gsub('TST_', '', existing.tests)
delete.top <- tktoplevel()
tkwm.title(delete.top, 'Delete a test')
tkwm.resizable(delete.top, FALSE, FALSE)
scr <- tkscrollbar(delete.top, repeatinterval=5,
command=function(...)tkyview(test.selBox,...))
test.selBox <- tklistbox(delete.top, height=3, width='31',
selectmode='single', yscrollcommand=function(...)tkset(scr,...),
background='white', exportselection=F)
for (i in (seq_along(existing.tests)))
tkinsert(test.selBox,'end', existing.tests[i])
tkselection.set(test.selBox,0)
tkgrid(tklabel(delete.top, text='Which test would you like to delete?'), sticky='nw')
tkgrid(test.selBox, scr, sticky='nw')
tkgrid.configure(scr, rowspan=5, sticky='nse')
tkgrid(tklabel(delete.top, text=' '))
doneDeleteTestVal <- tclVar(0)
OkDeleteTest.but <- tkbutton(delete.top, text=" OK ",
command=function() tclvalue(doneDeleteTestVal) <- 1)
tkgrid(OkDeleteTest.but)
tkgrid(tklabel(delete.top, text='Close the window to cancel deleting a test.'))
tkbind(delete.top, "<Destroy>", function() tclvalue(doneDeleteTestVal) <- 3)
tkfocus(delete.top)
tkwait.variable(doneDeleteTestVal)
if (tclvalue(doneDeleteTestVal)==1) {
test.to.delete <- existing.tests[as.numeric(tkcurselection(test.selBox))+1]
test.to.delete <- sub('.r$', '', test.to.delete)
file.to.rename <- paste('TST_', test.to.delete, '.r', sep='')
file.new.name <- paste('TST_', test.to.delete, '.bak', sep='')
file.rename(from=file.to.rename, to=file.new.name)
tkdestroy(delete.top)
tkmessageBox(message=paste('Extension type has been changed to ".bak".',
'This test will not appear in TestScorer.',
sep='\n'),
icon='warning', type='ok')
}
TestScorerGUI()
}
|
library(grid)
library(gridSVG)
pdf(file = NULL)
rg <- radialGradient(col = c("white", "black"))
m <- mask(gradientFillGrob(circleGrob(), gradient = rg))
registerMask("circleMask", m)
sp <- gTree(name = "simplePlot",
children = gList(xaxisGrob(), yaxisGrob(),
rectGrob(gp = gpar(fill = "grey"))),
vp = plotViewport())
grid.draw(sp)
grid.mask("simplePlot", label = "circleMask")
grid.export("mask-simpleplot.svg")
dev.off()
pdf(file = NULL)
gridSVG.newpage()
rg <- radialGradient(col = c("white", "black"))
m <- mask(gradientFillGrob(circleGrob(), gradient = rg))
pushMask(m)
sp <- gTree(name = "simplePlot",
children = gList(xaxisGrob(), yaxisGrob(),
rectGrob(gp = gpar(fill = "grey"))),
vp = plotViewport())
grid.draw(sp)
popMask()
grid.export("pushmask-simpleplot.svg")
dev.off() |
"nyc_marathon" |
initECRControl = function(fitness.fun, n.objectives = NULL, minimize = NULL) {
task = makeOptimizationTask(fitness.fun, n.objectives = n.objectives, minimize = minimize)
makeS3Obj("ecr_control", task = task)
}
extractFunctionParameters = function(fun) {
UseMethod("extractFunctionParameters")
}
extractFunctionParameters.smoof_function = function(fun) {
par.set = getParamSet(fun)
return(list(
n.objectives = getNumberOfObjectives(fun),
n.dim = getNumberOfParameters(fun),
minimize = shouldBeMinimized(fun),
upper = getUpper(par.set),
lower = getLower(par.set))
)
}
extractFunctionParameters.function = function(fun) {
return(list())
}
extractFunctionParameters.smoof_wrapped_function = function(fun) {
extractFunctionParameters(getWrappedFunction(fun))
}
initControlParams = function(control, ...) {
control$params = list(...)
return(control)
}
initDefaultOperators = function(control, type, n.objectives) {
n.objectives = asInt(n.objectives, lower = 1L)
assertChoice(type, c("float", "permutation", "binary", "custom"))
obj.type = if (n.objectives == 1L) "single" else "multi"
control = registerECROperator(control, "selectForMating", getDefaultEvolutionaryOperators(type, "parent.selector", n.objectives, control))
control = registerECROperator(control, "selectForSurvival", getDefaultEvolutionaryOperators(type, "survival.selector", n.objectives, control))
control = registerECROperator(control, "mutate", getDefaultEvolutionaryOperators(type, "mutator", n.objectives, control))
control = registerECROperator(control, "recombine", getDefaultEvolutionaryOperators(type, "recombinator", n.objectives, control))
return(control)
}
checkCorrectOperatorType = function(operator, class, type) {
if (!inherits(operator, class)) {
stopf("%s must be of class '%s', not '%s'.", type, class, collapse(attr(operator, "class"), sep = ", "))
}
}
getDefaultEvolutionaryOperators = function(representation, type, n.objectives, control) {
if (n.objectives == 1L) {
return(getSingleObjectiveDefaults(representation, type, control))
}
return(getMultiObjectiveDefaults(representation, type, control))
}
getSingleObjectiveDefaults = function(representation, type, control) {
defaults = list(
"float" = list(
"parent.selector" = setup(selTournament, k = 2L),
"mutator" = try(setup(mutGauss), silent = TRUE),
"recombinator" = setup(recIntermediate),
"survival.selector" = setup(selGreedy)
),
"binary" = list(
"parent.selector" = setup(selTournament, k = 2L),
"mutator" = setup(mutBitflip),
"recombinator" = setup(recCrossover),
"survival.selector" = setup(selGreedy)
),
"permutation" = list(
"parent.selector" = setup(selTournament, k = 2L),
"mutator" = setup(mutSwap),
"recombinator" = setup(recPMX),
"survival.selector" = setup(selGreedy)
),
"custom" = list(
"parent.selector" = setup(selTournament, k = 2L),
"mutator" = NULL,
"recombinator" = NULL,
"survival.selector" = setup(selGreedy)
)
)
if (representation %in% names(defaults)) {
return(defaults[[representation]][[type]])
}
stopf("No defaults availiable for custom representation. You need to specify all
operators by hand.")
}
getMultiObjectiveDefaults = function(representation, type, control) {
defaults = list(
"float" = list(
"parent.selector" = setup(selSimple),
"mutator" = try(setup(mutGauss), silent = TRUE),
"recombinator" = setup(recIntermediate),
"survival.selector" = setup(selNondom)
),
"binary" = list(
"parent.selector" = setup(selSimple),
"mutator" = setup(mutBitflip),
"recombinator" = setup(recCrossover),
"survival.selector" = setup(selNondom)
),
"permutation" = list(
"parent.selector" = setup(selSimple),
"mutator" = setup(mutSwap),
"recombinator" = setup(recPMX),
"survival.selector" = setup(selNondom)
),
"custom" = list(
"parent.selector" = setup(selSimple),
"mutator" = NULL,
"recombinator" = NULL,
"survival.selector" = setup(selNondom)
)
)
if (representation %in% names(defaults)) {
return(defaults[[representation]][[type]])
}
stopf("No defaults availiable for custom representation. You need to specify all
operators by hand.")
} |
library("plm")
data("Grunfeld", package = "plm")
Grunfeld$fac <- factor(1:200)
pGrun <- pdata.frame(Grunfeld)
options("plm.fast" = FALSE)
pGrunpser1.1 <- pseriesfy(pGrun)
collapse.avail <- if (!requireNamespace("collapse", quietly = TRUE)) FALSE else TRUE
if(collapse.avail) {
options("plm.fast" = TRUE)
pGrunpser2.1 <- pseriesfy(pGrun)
options("plm.fast" = FALSE)
class(pGrunpser1.1)
class(pGrunpser2.1)
stopifnot(identical(pGrunpser1.1, pGrunpser2.1))
lapply(pGrunpser1.1, class)
lapply(pGrunpser2.1, class)
lapply(pGrunpser1.1, names)
lapply(pGrunpser2.1, names)
form <- inv ~ value + capital
plm(form, pGrunpser1.1, model = "within")
plm(form, pGrunpser2.1, model = "within")
options("plm.fast" = FALSE)
pGrunpser1.2 <- pseriesfy(pGrunpser1.1)
options("plm.fast" = TRUE)
pGrunpser2.2 <- pseriesfy(pGrunpser2.1)
options("plm.fast" = FALSE)
class(pGrunpser1.2)
class(pGrunpser2.2)
lapply(pGrunpser1.2, class)
lapply(pGrunpser2.2, class)
lapply(pGrunpser1.2, names)
lapply(pGrunpser2.2, names)
stopifnot(identical(pGrunpser1.1, pGrunpser1.2))
stopifnot(identical(pGrunpser2.1, pGrunpser2.2))
stopifnot(identical(pGrunpser1.2, pGrunpser2.2))
with(pGrun, lag(value))
with(pGrunpser1.1, lag(value))
invisible(NULL)
} |
abort <- function(message = NULL,
class = NULL,
...,
call,
body = NULL,
footer = NULL,
trace = NULL,
parent = NULL,
use_cli_format = NULL,
.internal = FALSE,
.file = NULL,
.frame = NULL,
.subclass = deprecated()) {
.__signal_frame__. <- TRUE
caller <- caller_env()
if (is_null(.frame)) {
if (is_environment(maybe_missing(call))) {
.frame <- call
} else {
.frame <- caller
}
} else {
check_environment(.frame)
}
info <- abort_context(.frame, parent)
if (is_missing(call)) {
if (is_null(info$from_handler)) {
call <- .frame
} else {
call <- info$setup_caller
}
}
message <- validate_signal_args(message, class, call, .subclass, "abort")
call <- error_call(call)
message_info <- cnd_message_info(
message,
body,
footer,
caller,
use_cli_format = use_cli_format,
internal = .internal
)
message <- message_info$message
extra_fields <- message_info$extra_fields
use_cli_format <- message_info$use_cli_format
if (is_null(trace) && is_null(peek_option("rlang:::disable_trace_capture"))) {
with_options(
"rlang:::disable_trace_capture" = TRUE,
"rlang:::visible_bottom" = info$bottom_frame,
{ trace <- trace_back() }
)
}
cnd <- error_cnd(
class,
...,
message = message,
!!!extra_fields,
use_cli_format = use_cli_format,
call = call,
parent = parent,
trace = trace
)
signal_abort(cnd, .file)
}
abort_context <- function(frame, parent, call = caller_env()) {
calls <- sys.calls()
frames <- sys.frames()
parents <- sys.parents()
frame_loc <- detect_index(frames, identical, frame)
setup_loc <- 0L
setup_caller <- NULL
from_handler <- NULL
if (frame_loc > 1L) {
prev_frame <- frames[[frame_loc - 1L]]
if (env_has(prev_frame, ".__handler_frame__.")) {
from_handler <- "calling"
frame_loc <- frame_loc - 1L
setup_frame <- env_get(prev_frame, ".__setup_frame__.", default = NULL)
if (!is_null(setup_frame)) {
setup_caller <- eval_bare(call2(parent.frame), setup_frame)
}
}
}
bottom_loc <- frame_loc
if ((frame_loc - 1) > 0) {
call1 <- calls[[frame_loc]]
call2 <- calls[[frame_loc - 1]]
if (is_exiting_handler_call(call1, call2)) {
from_handler <- "exiting"
setup_loc <- calls_try_catch_loc(calls, frame_loc)
bottom_loc <- parents[[setup_loc]]
} else {
if (is_string(from_handler, "calling") || !is_null(parent)) {
if (is_calling_handler_inlined_call(call1)) {
from_handler <- "calling"
bottom_loc <- calls_signal_loc(calls, frame_loc - 1L)
} else if (is_calling_handler_simple_error_call(call1, call2)) {
from_handler <- "calling"
bottom_loc <- calls_signal_loc(calls, frame_loc - 2L)
}
setup_loc <- calls_setup_loc(calls, frames, frame_loc)
}
}
}
if (bottom_loc) {
bottom_loc <- skip_signal_frames(bottom_loc, frames)
bottom_frame <- frames[[bottom_loc]]
} else {
bottom_frame <- NULL
}
if (is_null(setup_caller) && setup_loc) {
setup_caller <- frames[[parents[[setup_loc]]]]
}
list(
from_handler = from_handler,
bottom_frame = bottom_frame,
setup_caller = setup_caller
)
}
calls_try_catch_loc <- function(calls, loc) {
loc <- loc - 1L
node <- as.pairlist(rev(calls[seq_len(loc)]))
while (is_call(node_car(node), c("tryCatchList", "tryCatchOne"))) {
node <- node_cdr(node)
loc <- loc - 1L
}
loc
}
calls_signal_loc <- function(calls, loc) {
tmp_node <- tmp_loc <- found_restart <- NULL
node <- as.pairlist(rev(calls[seq_len(loc)]))
call <- node_car(node)
advance <- function(node, i) {
list(node_cdr(node), i - 1L)
}
advance_restart <- function(node, i) {
found <- FALSE
restart_fns <- c(
"doWithOneRestart",
"withOneRestart",
"withRestarts"
)
while (is_call(node_car(node), restart_fns)) {
node <- node_cdr(node)
i <- i - 1L
found <- TRUE
}
list(node, i, found)
}
if (is_call(call, "stop")) {
return(loc)
}
if (is_call(call, "signalCondition")) {
c(tmp_node, tmp_loc, found_restart) %<-% advance_restart(node, loc)
if (found_restart && is_call(node_car(tmp_node), "message")) {
return(tmp_loc)
} else {
return(loc)
}
}
c(tmp_node, tmp_loc, found_restart) %<-% advance_restart(node, loc)
if (found_restart) {
if (is_call(node_car(tmp_node), ".signalSimpleWarning")) {
c(tmp_node, tmp_loc) %<-% advance(tmp_node, tmp_loc)
}
if (is_call(node_car(tmp_node), "warning")) {
return(tmp_loc)
}
}
loc
}
calls_setup_loc <- function(calls, frames, handler_loc) {
handler <- sys.function(handler_loc)
top <- handler_loc
while (TRUE) {
calls <- calls[seq_len(top)]
setup_loc <- detect_index(calls, is_call, "withCallingHandlers", .right = TRUE)
if (!setup_loc) {
return(0L)
}
signal_handlers <- frames[[setup_loc]][["handlers"]]
if (some(signal_handlers, identical, handler)) {
return(setup_loc)
}
top <- setup_loc - 1L
}
}
skip_signal_frames <- function(loc, frames) {
found <- FALSE
while (loc > 1 && env_has(frames[[loc - 1L]], ".__signal_frame__.")) {
found <- TRUE
loc <- loc - 1L
}
if (found) {
loc - 1L
} else {
loc
}
}
is_calling_handler_inlined_call <- function(call) {
is_call(call) && is_function(call[[1]]) && is_condition(call[[2]])
}
is_calling_handler_simple_error_call <- function(call1, call2) {
identical(call1, quote(h(simpleError(msg, call)))) && is_call(call2, ".handleSimpleError")
}
is_exiting_handler_call <- function(call1, call2) {
identical(call1, quote(value[[3L]](cond))) && is_call(call2, "tryCatchOne")
}
cnd_message_info <- function(message,
body,
footer,
env,
cli_opts = NULL,
use_cli_format = NULL,
internal = FALSE,
error_call = caller_env()) {
if (internal) {
check_exclusive(footer, .internal, .require = FALSE, .frame = error_call)
}
if (length(message) > 1 && !is_character(body) && !is_null(body)) {
stop_multiple_body(body, call = error_call)
}
cli_opts <- cli_opts %||% use_cli(env, error_call = error_call)
if (!is_null(use_cli_format)) {
cli_opts[["format"]] <- use_cli_format
}
fields <- list()
if (cli_opts[["inline"]]) {
message[] <- map_chr(message, cli::format_inline, .envir = env)
}
use_cli_format <- cli_opts[["format"]]
if (use_cli_format) {
if (length(message) > 1) {
fields$body <- c(message[-1], body)
message <- message[1]
} else {
fields$body <- body
}
if (!is_null(footer)) {
fields$footer <- footer
}
if (internal) {
fields$footer <- footer_internal
}
} else {
if (length(message) > 1 && is_null(names(message))) {
names(message) <- c("", rep_len("*", length(message) - 1))
}
if (is_character(body)) {
message <- c(message, body)
} else {
fields$body <- body
}
if (is_character(footer)) {
message <- c(message, footer)
} else {
fields$footer <- footer
}
if (internal) {
message <- c(message, footer_internal)
}
message <- .rlang_cli_format_fallback(message)
}
list(
message = message,
use_cli_format = use_cli_format,
extra_fields = fields
)
}
utils::globalVariables(".internal")
footer_internal <- c(
"i" = "This is an internal error, please report it to the package authors."
)
stop_multiple_body <- function(body, call) {
msg <- c(
sprintf(
"Can't supply conflicting bodies in %s and %s.",
format_arg("body"),
format_arg("message")
),
"x" = sprintf(
"%s must be character or NULL when a length > 1 %s is supplied.",
format_arg("body"),
format_arg("message")
),
"i" = sprintf(
"%s is currently %s.",
format_arg("body"),
friendly_type_of(body)
)
)
abort(msg, call = call)
}
local_use_cli <- function(...,
format = TRUE,
inline = FALSE,
frame = caller_env()) {
check_dots_empty0(...)
use_cli <- c(format = format, inline = inline)
if (is_namespace(frame)) {
frame$.__rlang_use_cli__. <- use_cli
} else {
local_bindings(.__rlang_use_cli__. = use_cli, .frame = frame)
}
invisible(NULL)
}
use_cli <- function(env, error_call) {
if (is_true(peek_option("rlang:::disable_cli"))) {
return(FALSE)
}
default <- c(format = FALSE, inline = FALSE)
last <- topenv(env)
if (identical(last, global_env()) && "devtools_shims" %in% search()) {
last <- empty_env()
}
flag <- env_get(
env,
".__rlang_use_cli__.",
default = default,
inherit = TRUE,
last = last
)
check_use_cli_flag(flag, error_call = error_call)
flag
}
check_use_cli_flag <- function(flag, error_call) {
if (!is_logical(flag) || !identical(names(flag), c("format", "inline")) || anyNA(flag)) {
abort("`.__rlang_use_cli__.` has unknown format.", call = error_call)
}
if (flag[["inline"]]) {
if (!has_cli_format || !has_cli_inline) {
msg <- c(
"`.__rlang_use_cli__.[[\"inline\"]]` is set to `TRUE` but cli is not installed or is too old.",
"i" = "The package author should add a recent version of `cli` to their `Imports`."
)
with_options(
"rlang:::disable_cli" = TRUE,
abort(call = error_call)
)
}
if (!flag[["format"]]) {
msg <- "Can't use cli inline formatting without cli bullets formatting."
abort(msg, call = error_call)
}
}
}
signal_abort <- function(cnd, file = NULL) {
.__signal_frame__. <- TRUE
if (is_true(peek_option("rlang::::force_unhandled_error"))) {
fallback <- cnd
} else {
signalCondition(cnd)
fallback <- cnd
class(fallback) <- c("rlang_error", "condition")
fallback$message <- ""
fallback$rlang$internal$entraced <- TRUE
}
poke_last_error(cnd)
cnd <- cnd_set_backtrace_on_error(cnd, peek_backtrace_on_error())
msg <- cnd_message(cnd, inherit = TRUE, prefix = TRUE)
cat_line(msg, file = file %||% default_message_file())
local_options(show.error.messages = FALSE)
stop(fallback)
}
local_error_call <- function(call, frame = caller_env()) {
frame$.__error_call__. <- call
invisible(NULL)
}
NULL
caller_arg <- function(arg) {
arg <- substitute(arg)
check_arg(arg)
expr <- do.call(substitute, list(arg), envir = caller_env())
as_label(expr)
}
format_error_call <- function(call) {
call <- error_call(call)
if (is_null(call)) {
return(NULL)
}
label <- error_call_as_string(call)
if (is_null(label)) {
return(NULL)
}
if (grepl("\n", label)) {
cli_with_whiteline_escapes(label, format_code)
} else {
format_code(label)
}
}
error_call_as_string <- function(call) {
if (!is_call(call)) {
return(NULL)
}
if (inherits(call, "AsIs")) {
call <- expr_deparse(unclass(call))
if (length(call) == 1) {
return(call)
} else {
return(NULL)
}
}
if (is_call(call, c("eval", "evalq"))) {
return(NULL)
}
if (!is_call_simple(call)) {
return(NULL)
}
old <- call[[1]]
call[[1]] <- sym(call_name(call))
if (is_call(call, "if")) {
call[[3]] <- quote(...)
return(as_label(call[1:3]))
}
if (!is_string(call_parse_type(call), "")) {
return(paste(error_call_deparse(call), collapse = "\n"))
}
if (is_symbol(call[[1]]) && needs_backticks(call[[1]])) {
return(as_string(call[[1]]))
}
call[[1]] <- old
as_label(call[1])
}
error_call_deparse <- function(call) {
out <- expr_deparse(call)
if (length(out) > 1) {
out[-1] <- paste0(" ", out[-1])
}
out
}
error_call <- function(call) {
while (is_environment(call)) {
flag <- env_get(call, ".__error_call__.", default = TRUE)
if (is_null(flag) || is_call(flag)) {
call <- flag
break
}
if (is_environment(flag)) {
call <- flag
next
}
if (is_string(flag, "caller")) {
call <- eval_bare(call2(caller_env), call)
next
}
if (is_string(gen <- call$.Generic)) {
frames <- sys.frames()
i <- detect_index(frames, identical, call, .right = TRUE)
while (i > 1) {
i <- i - 1
prev <- frames[[i]]
if (is_call(frame_call(prev), "NextMethod")) {
next
}
if (identical(prev$.Generic, gen)) {
next
}
return(error_call(prev))
}
}
call <- frame_call(call)
break
}
if (!is_call(call)) {
return(NULL)
}
quo_squash(call)
}
call_restore <- function(x, to) {
attr(x, "srcref") <- attr(to, "srcref")
x
}
NULL
backtrace_on_error_opts <- c("none", "reminder", "branch", "collapse", "full")
format_onerror_backtrace <- function(cnd, opt = peek_backtrace_on_error()) {
opt <- arg_match0(opt, backtrace_on_error_opts, "backtrace_on_error")
if (opt == "none") {
return(NULL)
}
trace <- cnd$trace
while (is_condition(cnd$parent)) {
cnd <- cnd$parent
if (!is_null(cnd$trace)) {
trace <- cnd$trace
}
}
if (is_null(trace) || !trace_length(trace)) {
return(NULL)
}
if (opt == "reminder") {
if (is_interactive()) {
reminder <- silver("Run `rlang::last_error()` to see where the error occurred.")
} else {
reminder <- NULL
}
return(reminder)
}
if (opt == "branch") {
max_frames <- 10L
} else {
max_frames <- NULL
}
simplify <- switch(
opt,
full = "none",
reminder = "branch",
opt
)
paste_line(
"Backtrace:",
format(trace, simplify = simplify, max_frames = max_frames)
)
}
peek_backtrace_on_error <- function() {
opt <- peek_backtrace_on_error_opt("rlang_backtrace_on_error")
if (!is_null(opt)) {
return(opt)
}
if (report_in_progress()) {
"branch"
} else if (is_interactive()) {
"reminder"
} else {
"full"
}
}
peek_backtrace_on_error_report <- function() {
peek_backtrace_on_error_opt("rlang_backtrace_on_error_report") %||% "none"
}
peek_backtrace_on_error_opt <- function(name) {
opt <- peek_option(name)
if (!is_null(opt) && !is_string(opt, backtrace_on_error_opts)) {
options(list2("{name}" := NULL))
warn(c(
sprintf("Invalid %s option.", format_arg(name)),
i = "The option was just reset to `NULL`."
))
return(NULL)
}
opt
} |
claims_by_first_report <- function(tbl_policy, frequency, payment_severity, lags){
if (missing(frequency)) stop("Must supply frequency.")
if (missing(payment_severity)) stop("Must supply payment_severity.")
numFreq <- length(frequency)
numSev <- length(payment_severity)
frequency <- maybe_wrap_in_list(frequency)
payment_severity <- maybe_wrap_in_list(payment_severity)
if (numFreq > numSev) {
message("frequency has more elements than severity. Recycling to accommodate.")
indices <- rep_len(seq.int(numSev), length.out = numFreq)
payment_severity <- payment_severity[indices]
numSev <- length(payment_severity)
} else if (numFreq < numSev) {
message("payment_severity has more elements than frequency. Recycling to accommodate.")
indices <- rep_len(seq.int(numFreq), length.out = numSev)
frequency <- frequency[indices]
numFreq <- length(frequency)
}
if (numFreq != numSev) {
stop("Something very strange has happened. Contact package maintainer for support.")
}
if (missing(lags)) {
lags <- seq.int(numFreq)
}
num_lags <- length(lags)
numPolicies <- nrow(tbl_policy)
lstClaims <- vector("list", num_lags)
first_claim_id <- 1
for (iLag in seq.int(num_lags)) {
claimFrequencies <- sample_or_rep(frequency[[iLag]], numPolicies)
if (any(claimFrequencies < 0)) {
message("Some claim frequencies are negative. These will be set to zero.")
claimFrequencies <- pmax(0, claimFrequencies)
}
claimFrequencies <- as.integer(claimFrequencies)
totalClaims <- sum(claimFrequencies)
claimIDs <- seq.int(from = first_claim_id, length.out = totalClaims)
first_claim_id <- max(claimIDs) + 1
policyholderIds <- mapply(rep, tbl_policy$policyholder_id, claimFrequencies, SIMPLIFY = FALSE)
policyholderIds <- do.call("c", policyholderIds)
effectiveDates <- mapply(rep, tbl_policy$policy_effective_date, claimFrequencies, SIMPLIFY = FALSE)
effectiveDates <- do.call("c", effectiveDates)
severities <- sample_or_rep(payment_severity[[iLag]], totalClaims)
lstClaims[[iLag]] <- tibble(policyholder_id = policyholderIds
, policy_effective_date = effectiveDates
, claim_id = claimIDs
, lag = lags[iLag]
, payment_amount = severities)
}
tbl_claims <- do.call(rbind, lstClaims)
tbl_claims
} |
if (requireNamespace("tinytest", quietly = TRUE)) {
tinytest::test_package("ggiraph")
} |
rm(list=ls())
library(tidyverse)
library(ukcovid19)
library(paletteer)
library(RcppRoll)
library(lubridate)
library(scales)
library(ragg)
deaths.reg <- get_data(filters="areaType=region", structure=list(date="date",
name="areaName",
deaths="newDeaths28DaysByDeathDate"))
deaths.reg <- deaths.reg %>%
mutate(pop=case_when(
name=="East of England" ~ 6236072,
name=="London" ~ 8961989,
name=="West Midlands" ~ 5934037,
name=="East Midlands" ~ 4835928,
name=="North East" ~ 2669941,
name=="Yorkshire and The Humber" ~ 5502967,
name=="North West" ~ 7341196,
name=="South East" ~ 9180135,
name=="South West" ~ 5624696),
mortrate=deaths*100000/pop,
date=as.Date(date),
mortrateroll=roll_mean(mortrate, 7, align="center", fill=NA)) %>%
arrange(date)
maxdate <- max(deaths.reg$date)
agg_tiff("Outputs/COVIDDeathsxRegionLine.tiff", units="in", width=10, height=7, res=500)
deaths.reg %>%
filter(date<maxdate-days(3)) %>%
ggplot()+
geom_line(aes(x=date, y=mortrateroll, colour=name))+
theme_classic()+
scale_x_date(name="", breaks=breaks_pretty(n=interval(min(deaths.reg$date, na.rm=TRUE), maxdate-days(3))%/% months(1)))+
scale_y_continuous(name="Daily COVID-19 deaths per 100,000")+
scale_colour_paletteer_d("LaCroixColoR::paired", name="Region")+
labs(title="COVID-19 deaths are falling consistently across all regions of England",
subtitle="Daily deaths per 100,000 within 28 days of a positive COVID-19 test",
caption="Data from PHE | Plot by @VictimOfMaths")+
theme(plot.title=element_text(face="bold", size=rel(1.2)))
dev.off()
agg_tiff("Outputs/COVIDDeathsxRegionLineRecent.tiff", units="in", width=10, height=7, res=500)
deaths.reg %>%
filter(date<maxdate-days(3) & date>as.Date("2020-09-01")) %>%
ggplot()+
geom_line(aes(x=date, y=mortrateroll, colour=name))+
theme_classic()+
scale_x_date(name="", breaks=breaks_pretty(n=interval(min(deaths.reg$date, na.rm=TRUE), maxdate-days(3))%/% months(1)))+
scale_y_continuous(name="Daily COVID-19 deaths per 100,000")+
scale_colour_paletteer_d("LaCroixColoR::paired", name="Region")+
labs(title="Deaths associated with COVID-19 are still falling rapidly across England",
subtitle="Daily deaths per 100,000 within 28 days of a positive COVID-19 test",
caption="Data from PHE | Plot by @VictimOfMaths")+
theme(plot.title=element_text(face="bold", size=rel(1.2)))
dev.off()
peaks <- deaths.reg %>%
mutate(period=if_else(date<as.Date("2020-08-01"), "Wave 1", "Wave 2")) %>%
group_by(name, period) %>%
summarise(peak=max(mortrateroll, na.rm=TRUE)) %>%
spread(period, peak)
agg_tiff("Outputs/COVIDDeathsxRegionScatter.tiff", units="in", width=8, height=6, res=500)
ggplot(peaks)+
geom_point(aes(x=`Wave 1`, y=`Wave 2`, colour=name))+
geom_abline(intercept=0)+
scale_colour_paletteer_d("LaCroixColoR::paired", name="Region")+
theme_classic()+
scale_x_continuous(limits=c(0,3), name="Peak mortality rate Mar-Jul\n7-day rolling average")+
scale_y_continuous(limits=c(0,3), name="Peak mortality rate Aug-Jan\n7-day rolling average")+
labs(title="Correlation between the Spring and Autumn/Winter peaks is limited",
subtitle="Deaths per 100,000 within 28 days of a positive COVID-19 test",
caption="Date from PHE | Plot by @VictimOfMaths")+
theme(plot.title=element_text(face="bold", size=rel(1.2)))
dev.off()
deaths.nat <- get_data(filters="areaType=nation", structure=list(date="date",
name="areaName",
deaths="newDeaths28DaysByDeathDate"))
deaths.nat <- deaths.nat %>%
mutate(pop=case_when(
name=="England" ~ 56286961,
name=="Scotland" ~ 5463300,
name=="Wales" ~ 3152879,
name=="Northern Ireland" ~ 1893667),
mortrate=deaths*100000/pop,
date=as.Date(date)) %>%
arrange(date) %>%
group_by(name) %>%
mutate(mortrateroll=roll_mean(mortrate, 7, align="center", fill=NA)) %>%
ungroup()
agg_tiff("Outputs/COVIDDeathsxCountryLine.tiff", units="in", width=10, height=7, res=500)
deaths.nat %>%
filter(date<maxdate-days(3)) %>%
ggplot()+
geom_line(aes(x=date, y=mortrateroll, colour=name))+
theme_classic()+
scale_x_date(name="", breaks=breaks_pretty(n=interval(min(deaths.reg$date, na.rm=TRUE), maxdate-days(3))%/% months(1)))+
scale_y_continuous(name="Daily COVID-19 deaths per 100,000")+
scale_colour_paletteer_d("fishualize::Scarus_quoyi", name="")+
labs(title="Deaths linked to COVID-19 are falling in all four UK nations",
subtitle="Daily deaths per 100,000 within 28 days of a positive COVID-19 test",
caption="Data from PHE | Plot by @VictimOfMaths")+
theme(plot.title=element_text(face="bold", size=rel(1.2)))
dev.off()
agg_tiff("Outputs/COVIDDeathsxCountryLineRecent.tiff", units="in", width=10, height=7, res=500)
deaths.nat %>%
filter(date<maxdate-days(3) & date>as.Date("2020-09-01")) %>%
ggplot()+
geom_line(aes(x=date, y=mortrateroll, colour=name))+
theme_classic()+
scale_x_date(name="", breaks=breaks_pretty(n=interval(min(deaths.reg$date, na.rm=TRUE), maxdate-days(3))%/% months(1)))+
scale_y_continuous(name="Daily COVID-19 deaths per 100,000")+
scale_colour_paletteer_d("fishualize::Scarus_quoyi", name="")+
labs(title="Mortality rates across the UK have been falling consistently since mid-January",
subtitle="Daily deaths per 100,000 within 28 days of a positive COVID-19 test",
caption="Data from PHE | Plot by @VictimOfMaths")+
theme(plot.title=element_text(face="bold", size=rel(1.2)))
dev.off() |
pred_NHANES3 <- function(age, height, gender=1, ethnicity=1, param="FEV1") {
param <- param[param %in% c("FEV1", "FVC", "FEV1FVC", "PEF", "FEF2575", "FEV6", "FEV1FEV6")]
if (length(param)==0) stop("No valid parameters found in argument 'param'!")
dat <- rspiro_check_data(age, height, gender, ethnicity, NHANES=TRUE)
dat$under20 <- dat$age<20
dat$age2 <- dat$age^2
dat$Intercept <- 1
dat$height2 <- (dat$height * 100)^2
for (p in param) {
if (p %in% c("FEV1FVC", "FEV1FEV6")) {
cf <- t(mapply(function(p, gend, ethn) { NHtb6[
with(NHtb6, which(param==p & sex==gend & ethnicity==ethn)),
c("interceptPRD", "Age")]
}, p=p, gend=dat$gender, ethn=dat$ethnicity))
cf <- matrix(as.numeric(cf), ncol=ncol(cf), nrow=nrow(cf), dimnames=dimnames(cf))
dat[[paste0("pred.", p)]] <- unname(rowSums(dat[,c("Intercept","age")]*cf))/100
} else {
cf <- t(mapply(function(p, gend, ethn, u20) { NHtb45[
with(NHtb45, which(param==p & sex==gend & ethnicity==ethn & under20==u20)),
c("intercept", "age", "age2", "HtPRD")]
}, p=p, gend=dat$gender, ethn=dat$ethnicity, u20=dat$under20))
cf <- matrix(as.numeric(cf), ncol=ncol(cf), nrow=nrow(cf), dimnames=dimnames(cf))
dat[[paste0("pred.", p)]] <- unname(rowSums(dat[,c("Intercept","age","age2","height2")]*cf))
}
}
return(dat[,grep("pred", names(dat), fixed=TRUE)])
} |
name_stages <- function(mat, names = NULL, prefix = "stage_", left_pad = TRUE) {
if (!is.matrix(mat) && !is.list(mat)) {
stop("Argument `mat` must be either a matrix or list of matrices.\n")
}
if (is.matrix(mat)) {
if (length(unique(dim(mat))) != 1L) {
stop("When `mat` is supplied as a matrix, it must be square.\n")
} else {
mdim <- nrow(mat)
}
} else {
if (length(unique(unlist(lapply(mat, dim), use.names = FALSE))) != 1L) {
stop("Each matrix in `mat` must be square with the same dimensions.\n")
} else {
mdim <- nrow(mat[[1]])
}
}
if (is.null(names) && !is.character(prefix)) {
stop("Either stage `names` or a naming `prefix` must be supplied.\n")
}
if (!is.null(names) && is.character(prefix)){
warning("Naming `prefix` ignored, using stage `names` instead.\n")
}
if (is.null(names)) {
if (isTRUE(left_pad)) {
fmt <- paste0("%0", nchar(mdim), "d")
names <- paste0(prefix, sprintf(fmt, 1:mdim))
} else if (isFALSE(left_pad)) {
names <- 1:mdim
} else {
stop("Argument `left_pad` must be of type logical (TRUE/FALSE).\n")
}
}
if (mdim != length(names)) {
stop("Incorrect number of stage names supplied: ", length(names),
" names supplied for ", mdim, " life stages.\n")
}
if (is.list(mat) && !is.null(unlist(lapply(mat, dimnames), use.names = FALSE)) |
is.matrix(mat) && !is.null(unlist(dimnames(mat), use.names = FALSE))) {
warning("Existing stage names have been overwritten!\n")
}
if (is.matrix(mat)) {
dimnames(mat) <- list(names, names)
} else {
mat <- lapply(mat, `dimnames<-`, list(names, names))
}
return(mat)
} |
"plot.surface" <- function(x, main = NULL, type = "C",
zlab = NULL, xlab = NULL, ylab = NULL, levels = NULL, zlim = NULL,
graphics.reset = NULL, labcex = 0.6, add.legend = TRUE, ...) {
obj <- x
old.par <- par(no.readonly = TRUE)
if (is.na(match(type, c("b", "c", "C", "I", "p")))) {
stop("plot type does not match b, C, I, or p.")
}
if (is.null(zlim)) {
zlim = range(obj$z, na.rm = TRUE)
}
if (is.null(graphics.reset) & (type == "b")) {
graphics.reset <- TRUE
}
else {
graphics.reset <- FALSE
}
if (graphics.reset) {
on.exit(par(old.par))
}
if (is.null(xlab)) {
if (is.null(obj$xlab))
xlab <- "X"
else xlab <- obj$xlab
}
if (is.null(ylab)) {
if (is.null(obj$ylab))
ylab <- "Y"
else ylab <- obj$ylab
}
if (is.null(zlab)) {
if (is.null(obj$zlab))
zlab <- "Z"
else zlab <- obj$zlab
}
if (is.null(main))
if (!is.null(obj$main))
main <- obj$main
if (type == "b")
set.panel(1, 2, TRUE)
if (type == "p" | type == "b") {
if (type == "b") {
add.legend <- FALSE
old.mar <- par()$mar
par(mar = c(0, 5, 0, 0))
}
drape.plot(obj, xlab = xlab, ylab = ylab, zlab = zlab,
zlim = zlim, add.legend = add.legend, ...)
if (!is.null(main))
title(main)
}
if (type == "I") {
image.plot(obj$x, obj$y, obj$z, xlab = xlab, ylab = ylab,
zlim = zlim, ...)
if ((!is.null(main)) & type != "b")
title(main)
}
if (type == "c") {
if (is.null(levels))
levels <- pretty(obj$z[!is.na(obj$z)], 5)
contour(obj$x, obj$y, obj$z, levels = levels, labcex = labcex,
lwd = 2, ...)
if ((!is.null(main)) & type != "b")
title(main)
}
if (type == "b" | type == "C") {
if (type == "b") {
par(mar = old.mar)
}
image.plot(obj$x, obj$y, obj$z, xlab = xlab, ylab = ylab,
graphics.reset = graphics.reset, zlim = zlim, ...)
if (is.null(levels))
levels <- pretty(obj$z[!is.na(obj$z)], 5)
contour(obj$x, obj$y, obj$z, add = TRUE, levels = levels,
labcex = labcex, col = "black", lwd = 2)
if ((!is.null(main)) & type != "b")
title(main)
}
invisible()
} |
isPositiveNumberOrNaScalar <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = 1, zeroAllowed = TRUE, negativeAllowed = FALSE, positiveAllowed = TRUE, nonIntegerAllowed = TRUE, naAllowed = TRUE, nanAllowed = FALSE, infAllowed = FALSE, message = message, argumentName = argumentName)
} |
"pine" |
names.clock_rcrd <- function(x) {
.Call(`_clock_clock_rcrd_names`, x)
}
`names<-.clock_rcrd` <- function(x, value) {
.Call(`_clock_clock_rcrd_set_names`, x, value)
}
`[.clock_rcrd` <- function(x, i) {
i <- maybe_missing(i, default = TRUE)
vec_slice(x, i)
}
`[[.clock_rcrd` <- function(x, i) {
size <- vec_size(x)
names <- names(x)
i <- vec_as_location2(i, n = size, names = names, arg = "i")
x <- unname(x)
vec_slice(x, i)
}
vec_math.clock_rcrd <- function(.fn, .x, ...) {
switch(
.fn,
is.nan = clock_rcrd_is_nan(.x),
is.finite = clock_rcrd_is_finite(.x),
is.infinite = clock_rcrd_is_infinite(.x),
NextMethod()
)
}
clock_rcrd_is_nan <- function(x) {
vec_rep(FALSE, vec_size(x))
}
clock_rcrd_is_finite <- function(x) {
!vec_equal_na(x)
}
clock_rcrd_is_infinite <- function(x) {
vec_rep(FALSE, vec_size(x))
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(saeHB) |
makeWeightsAIC <-
function(aics){
min.i<-which(aics==min(aics))
deltas<-aics-aics[min.i][1]
w<-exp(-deltas/2)/sum(exp(-deltas/2))
return(w)
} |
knitr::opts_chunk$set(collapse = T, comment = "
options(tibble.print_min = 4L, tibble.print_max = 4L)
library(grapherator)
addEdgesThreshold = function(graph, threshold, ...) {
n = getNumberOfNodes(graph)
coords = getNodeCoordinates(graph)
dists = as.matrix(dist(coords, method = "euclidean", ...))
adj.mat = dists < threshold
diag(adj.mat) = FALSE
return(list(adj.mat = adj.mat, generator = "ThEG"))
}
set.seed(1)
g = graph(lower = 0, upper = 100)
g = addNodes(g, n = 25, generator = addNodesUniform)
g = addEdges(g, generator = addEdgesThreshold, threshold = 30)
plot(g)$pl.coords
set.seed(1)
g = graph(lower = 0, upper = 100)
g = addNodes(g, n = 5, generator = addNodesUniform)
g = addNodes(g, n = 25, by.centers = TRUE, generator = addNodesGrid, lower = c(0, 0), upper = c(15, 15))
g = addEdges(g, generator = addEdgesThreshold, threshold = 13, type = "intracluster")
g = addEdges(g, generator = addEdgesDelauney, type = "intercenter")
plot(g)$pl.coords |
ms_explode <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
UseMethod("ms_explode")
}
ms_explode.character <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
input <- check_character_input(input)
apply_mapshaper_commands(data = input, command = "-explode", force_FC = force_FC, sys = sys, sys_mem = sys_mem)
}
ms_explode.geo_json <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
apply_mapshaper_commands(data = input, command = "-explode", force_FC = force_FC, sys = sys, sys_mem = sys_mem)
}
ms_explode.geo_list <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
geojson <- geo_list_to_json(input)
ret <- apply_mapshaper_commands(data = geojson, command = "-explode", force_FC = force_FC, sys = sys, sys_mem = sys_mem)
geojsonio::geojson_list(ret)
}
ms_explode.SpatialPolygons <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
explode_sp(input, sys = sys, sys_mem = sys_mem)
}
ms_explode.SpatialLines <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
explode_sp(input, sys = sys, sys_mem = sys_mem)
}
explode_sp <- function(input, sys, sys_mem) {
ms_sp(input = input, call = "-explode", sys = sys, sys_mem = sys_mem)
}
ms_explode.sf <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
explode_sf(input = input, sys = sys, sys_mem = sys_mem)
}
ms_explode.sfc <- function(input, force_FC = TRUE, sys = FALSE, sys_mem = 8) {
explode_sf(input = input, sys = sys, sys_mem = sys_mem)
}
explode_sf <- function(input, sys, sys_mem) {
ms_sf(input = input, call = "-explode", sys = sys, sys_mem = sys_mem)
} |
print.src <- function(x, ...){
p1 <- "\nWeibull regression for a right-censored response with an interval-censored covariate\n\n"
p2 <- "\nCoefficients:\n"
p3 <- round(t(x$coeff[, "Estimate", drop = FALSE]), 5)
rownames(p3) <- ""
p4 <- paste("\nAIC: ", round(x$AIC, 1), "\n", sep = "")
cat(p1)
cat("Call:\n")
print(x$Call)
cat(p2)
print(p3)
cat(p4)
invisible(x)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.