code
stringlengths 1
13.8M
|
---|
breathtest_data = function(patient_id,
name = NA,
first_name = NA,
initials = NA,
dob = NA,
birth_year = NA,
gender = NA,
study = NA,
pat_study_id = NA,
file_name,
device = "generic",
substrate,
record_date,
start_time = record_date,
end_time = record_date,
test_no ,
dose = 100,
height = 180,
weight = 75,
t50 = NA,
gec = NA,
tlag = NA,
data = data) {
if (!inherits(data, "data.frame"))
stop("Function breathtest_data: data must be a data frame")
if (nrow(data) < 5)
stop("Function breathtest_data: data should have a least 5 rows")
nd = names(data)
if (!(nd[1] %in% c("time", "minute")))
stop("Function breathtest_data: first data column must be <<time>> or <<minute>>. It is:<< ", nd[1], ">>")
names(data)[1] = "minute"
if (!sum(nd[-1] %in% c("pdr", "dob")) > 0)
stop("function breathtest_data: data should have either dob or pdr or both")
substrate = str_trim(substrate)
if (substrate == "") {
substrate = "octanoate"
} else {
substrates = c("octanoate", "acetate")
substrate_pattern = c("o[ck]t", "acet")
substrate = substrates[str_detect(tolower(substrate), substrate_pattern)][1]
}
if (length(substrate) == 0)
substrate = "octanoate"
if (!is.na(gender) & !match(gender, c("m", "f")))
stop("function breathtest_data: gender should be 'm' or 'f'")
if (weight <= 30 || height < 1) {
height = 180
weight = 75
}
if (!"pdr" %in% nd)
data$pdr = dob_to_pdr(data$dob, weight, height, mw = substrate)
data$minute = as.double(data$minute)
structure(
list(
patient_id = patient_id,
name = name,
first_name = first_name,
initials = initials,
dob = dob,
birth_year = birth_year,
gender = gender,
study = study,
pat_study_id = pat_study_id,
file_name = file_name,
device = device,
substrate = substrate,
record_date = as.character(record_date),
start_time = as.character(start_time),
end_time = as.character(end_time),
test_no = as.integer(test_no),
dose = 100,
height = height,
weight = weight,
t50 = t50,
gec = gec,
tlag = tlag,
data = data
),
class = "breathtest_data"
)
} |
recombination_npoint <- function(X, M, recpars = list(N = NULL)) {
assertthat::assert_that(is.matrix(X), is.numeric(X),
is.matrix(M), is.numeric(M),
assertthat::are_equal(dim(X), dim(M)),
is.null(recpars$N) ||
(assertthat::is.count(recpars$N) && is_within(recpars$N, 0, ncol(X) - 1)))
if (is.null(recpars$N) || recpars$N == 0) {
recpars$N <- sample.int(n = ncol(X) - 1,
size = nrow(X),
replace = TRUE)
} else {
recpars$N <- rep(x = recpars$N,
times = nrow(X))
}
cutlist <- lapply(recpars$N,
FUN = function(x,n){
sort(sample.int(n = n,
size = x,
replace = FALSE))
},
n = ncol(X) - 1)
makemask <- function(cuts, x){
m <- matrix(1:ncol(x),
nrow = length(cuts),
ncol = ncol(x),
byrow = TRUE)
m <- colSums(m > matrix(cuts,
nrow = nrow(m),
ncol = ncol(m),
byrow = FALSE))
return(m %% 2 == 0)
}
R <- t(vapply(X = cutlist,
FUN = makemask,
FUN.VALUE = logical(ncol(X)),
x = X))
if (stats::runif(1) < 0.5){
R <- !R
}
return(R * M + (!R) * X)
} |
get_reddit_image <-
function(subreddit,
id,
...){
if(inherits(id, 'imgur_image') || inherits(id, 'imgur_gallery_image'))
id <- id$id
out <- imgurGET(paste0('gallery/r/', subreddit, '/', id), ...)
structure(out, class = 'imgur_gallery_image')
} |
getSymbolInfo = function(token = '', live = FALSE, figi='', verbose = FALSE)
{
headers = add_headers("accept" = "application/json","Authorization"=paste("Bearer",token))
raw_data = GET(paste0('https://api-invest.tinkoff.ru/openapi/',ifelse(live == FALSE,'sandbox/',''),'market/search/by-figi?figi=',figi), headers)
if(raw_data$status_code==200)
{
data_tmp <- content(raw_data, as = "parsed")
data_result = data.table(t(data_tmp$payload))
return(data_result)
}
if(raw_data$status_code!=200)
if(verbose) return(content(raw_data, as = "parsed"))
} |
charClass <- function(x, class) .Call(C_charClass, x, class) |
context("weib_percentile")
test_that("weib_percentile calculates a value that seems probable",{
x <- rnorm(n = 10, mean = 150, sd = 10)
expect_equal(weib_percentile(x, percentile = 0.5, iterations = 20),
mean(x),
tolerance = 7)
}) |
context("ClickhouseResult")
library(DBI, warn.conflicts=F)
library(dplyr, warn.conflicts=F)
source("utils.R") |
massShift <-
function(seq, label = "none", aaShift = NULL, monoisotopic = TRUE){
label <- tolower(label)
if(!(label %in% c("none", "silac_13c", "silac_13c15n", "15n"))){
stop("Given label type unknown. Please use one of 'none', '15N', 'Silac_13C15N', or 'Silac_13C' (case-insensitive).")
}
if(!is.null(aaShift) & is.null(names(aaShift))){
stop("'aaShift' must be given as a named vector, e.g. 'aaShift = c(K = 6.020129)'.")
}
allowed <- c(aaList(), "Cterm", "Nterm")
if(!is.null(aaShift) & !all(names(aaShift) %in% allowed)){
stop(paste("Unknown amino acids defined in 'aaShift'. Only the following names are allowed:", paste(allowed, collapse = ", ")))
}
if (label == "silac_13c"){
aaShift <- c("K" = 6.020129 - 0.064229*!monoisotopic, "R" = 6.020129- 0.064229*!monoisotopic)
} else if(label == "silac_13c15n"){
aaShift <- c("K" = 8.014199 -0.071499*!monoisotopic, "R" = 10.008269-0.078669*!monoisotopic)
} else if(label == "15n"){
aaShift <- c(
A = 1,
R = 4,
N = 2,
D = 1,
C = 1,
E = 1,
Q = 2,
G = 1,
H = 3,
I = 1,
L = 1,
K = 2,
M = 1,
F = 1,
P = 1,
S = 1,
T = 1,
W = 2,
Y = 1,
V = 1
) * 0.997035 -0.003635*!monoisotopic
}
seq <- aaCheck(seq)
unlist(
lapply(seq, function(x){
sum(aaShift[c(x)], aaShift["Nterm"], aaShift["Cterm"], na.rm = TRUE)
}))
} |
autoDataprep <- function(data, target = NULL, missimpute = "default",
auto_mar = FALSE, mar_object = NULL, dummyvar = TRUE, char_var_limit = 12,
aucv = 0.02, corr = 0.99, outlier_flag = FALSE, interaction_var = FALSE,
frequent_var = FALSE, uid = NULL, onlykeep = NULL, drop = NULL, verbose = FALSE){
if (!is.data.frame(data)) stop ("Input data is not a data frame" )
if (is.null(target)) stop ("target variable is missing" )
cl <- match.call()
data <- clean_data(data)
data[, paste0(target) := ifelse(is.na( get(target)), 0, get(target))]
setDF(data)
datstrain <- ExpData(data, type = 1)
datstrain1 <- ExpData(data, type = 2)
if (!is.null( onlykeep)) data <- data[ unique( c( onlykeep, uid))]
mar_variable <- character()
if (!is.null(mar_object) & isFALSE(auto_mar)) {
stop ( "IF mar_object is given then auto_mar option should be TRUE" )
}
if (auto_mar == TRUE) {
if (!is.null(mar_object)){
if (class(mar_object) != "autoMAR") stop ("mar object should be autoMAR output")
mar_variable <- mar_object$auc_features$Variable
} else {
xx <- subset(data, select = setdiff(names(data), c(uid, drop)))
amrobj <- autoMAR(xx, aucv = 0.9, mar_method = "glm")
mar_variable <- amrobj$auc_features$Variable
}
}
names(data) <- trimws( gsub("[][!
all_names <- names(data)
data <- data[, !duplicated(colnames(data))]
if (!is.null(drop)) {
data <- subset(data, select = setdiff(all_names, drop))
}
num_var <- unique(names(data)[sapply(data, is.numeric)],
names(data)[sapply(data, is.integer)])
char_var <- names(data)[sapply(data, is.character)]
factor_var <- names(data)[sapply(data, is.factor)]
logical_var <- names(data)[sapply(data, is.logical)]
date_var <- names(data)[unlist(lapply(data, function(x)
class(x) == "Date" | class(x) == "POSIXct" ))]
date_flag <- unique_var <- character()
if (!is.null(uid)){
unique_var <- unique(c(unique_var, uid))
}
if (length(date_var) > 0){
invisible(lapply(date_var, function(x) set(data, which(is.na(data[[x]])), j = x, value = 0)))
date_flag <- date_var[sapply(data[date_var], function(x) length(unique(x)) > 1 & length(unique(x)) <= 5)]
if (length(date_flag) > 0){
data[date_flag] <- lapply(data[date_flag], function(x) as.character(x))
}
}
ch_fact_var <- c(factor_var, char_var, logical_var)
factor_flag <- num_var_cnt <- num_flag <- character()
if (length(ch_fact_var) > 0) {
factor_flag <- ch_fact_var[sapply(data[ch_fact_var], function(x) length(unique(x)) %in% c(2 : char_var_limit))]
}
if (length(num_var) > 0){
num_var_cnt <- sapply(data[num_var], function(x){
x[is.na(x)] <- 0
length(unique(x))
})
num_flag <- num_var[num_var_cnt == 2 | num_var_cnt == 3]
num_var <- num_var[num_var_cnt > 3]
num_var <- setdiff(num_var, unique_var)
num_flag <- setdiff(num_flag, c(unique_var, target))
}
final_dum_var <- setdiff(unique(c(factor_flag, date_flag, num_flag)), c(unique_var, target))
mar_list_var <- unique(c(setdiff(c(final_dum_var, num_var, target, date_var), unique_var), mar_variable))
XX <- data[mar_list_var]
if (ncol(XX) < 2) stop (cat(" Data preparation for ML model is incomplete due to less number of features", "\n", "Please check the input data / function parameters..."))
invisible(lapply(names(XX), function(x) set(XX, which(is.infinite(XX[[x]])), j = x, value = NA)))
invisible(lapply(names(XX), function(x) set(XX, which(is.nan(XX[[x]])), j = x, value = NA)))
if (length(mar_variable) >= 1){
if (verbose == TRUE) cat("autoDataprep < MAR variable computation.... >", "\n")
setDT(XX)
XX[, (paste0("Y_", mar_variable)) := lapply(mar_variable, function(x) ifelse(is.na(get(x)), 1, 0))]
setDF(XX)
}
if (anyNA(XX)){
if (verbose == TRUE) cat("autoDataprep < missing imputation.... >", "\n")
mis_imp_df <- "default"
mis_chk <- mis_imp_df[mis_imp_df %in% missimpute]
if (length(mis_chk) > 0) {
imp <- impute(XX, classes = list(factor = imputeMode(), integer = imputeMean(),
numeric = imputeMedian(),
character = imputeConstant(const = 99999)))
} else {
lenimp <- length(missimpute)
if (lenimp == 1) imp <- impute(XX, classes = missimpute$classes)
if (lenimp == 2) imp <- impute(XX, target = target, classes = missimpute$classes)
}
XX <- imp$data
}
out_summary <- date_summary <- out_summary1 <- dumvarnam <- NULL
if (outlier_flag == TRUE) {
if (verbose == TRUE) cat("autoDataprep < Outlier treatment based on Tukey method....>", "\n")
out_summary <- generateFeature(XX, num_var, type = "Outlier", method = "flag")
out_summary1 <- generateFeature(XX, num_var, type = "Outlier", method = "caping")
if (ncol(out_summary) > 0) XX <- cbind(XX, out_summary)
if (ncol(out_summary1) > 0) XX <- cbind(XX, out_summary1)
}
out_flag_var <- unique(c(names(out_summary), names(out_summary1)))
date_trans_var <- inter_variables <- freq_variables <- freq_vklist <- character()
if (length(date_var) > 0) {
if (verbose == TRUE) cat("autoDataprep < Date transformer....>", "\n")
date_summary <- generateFeature(XX, date_var, type = "date")
date_trans_var <- names(date_summary)
if (length(date_trans_var) > 0) XX <- cbind(XX, date_summary)
rm(date_summary)
}
if (frequent_var == TRUE) {
freq_vklist <- setdiff(factor_flag, c(target, num_flag))
if (length(freq_vklist) > 0){
if (verbose == TRUE) cat("autoDataprep < Frequent transformer....>", "\n")
if (length(freq_vklist) > 10) freq_vklist <- freq_vklist[sample(1:length(freq_vklist), 10)]
freq_var_data <- generateFeature(XX, varlist = freq_vklist, type = "Frequent", method = "Frequency")
if (ncol(freq_var_data) > 0) XX <- cbind(XX, freq_var_data)
freq_variables <- names(freq_var_data)
}
}
if (interaction_var == TRUE) {
if (length(num_var) > 1){
if (verbose == TRUE) cat("autoDataprep < Interactions transformer....>", "\n")
interaction_var <- num_var
if (length(num_var) > 10) interaction_var <- num_var[sample(1 : length(num_var), 10)]
inter_var_data <- generateFeature(XX, varlist = interaction_var, type = "Interaction", method = "multiply")
inter_variables <- names(inter_var_data)
if (length(inter_variables) > 0 ) XX <- cbind(XX, inter_var_data)
}
}
varbucket <- list("A" = factor_flag, "B" = date_flag, "C" = num_flag, "D" = num_var, "E" = final_dum_var, "F" = mar_variable, "G" = date_var, "H" = interaction_var, "I" = freq_vklist)
if (dummyvar == TRUE){
if (verbose == TRUE) cat("autoDataprep < Categorical variable - one hot encoding....>", "\n")
final_dum_var <- setdiff(final_dum_var, c(target, num_flag))
if (length(final_dum_var) > 0){
sparseMtx <- generateFeature(XX, varlist = final_dum_var, type = "Dummy", method = NULL)
XX <- cbind(XX, sparseMtx)
dumvarnam <- c(colnames(sparseMtx), num_flag)
}
}
all_variable <- setdiff(unique(c(num_var, dumvarnam, out_flag_var, freq_variables, inter_variables, date_trans_var)), c(unique_var, target))
drop_var <- setdiff(all_names, c(unique_var, num_var, factor_flag, final_dum_var, date_var))
if (length(mar_variable) >= 1)
all_variable <- setdiff(unique(c(num_var, dumvarnam, freq_variables, inter_variables, date_trans_var, out_flag_var, paste0("Y_", mar_variable))), c(unique_var, target))
if (verbose == TRUE) cat("autoDataprep < variable reduction - zero variance method.... >", "\n")
master_variable <- all_variable
varSel_auc <- corNms <- zeroNms <- character()
mynms <- c(out_flag_var, dumvarnam, date_trans_var)
if (length(mynms) > 0) {
configureMlr(show.info = FALSE)
XXvar <- removeConstantFeatures(XX[mynms])
zeroNms <- setdiff(mynms, names(XXvar))
master_variable <- setdiff(master_variable, zeroNms)
}
if (verbose == TRUE) cat("autoDataprep < variable selection - pearson correlation method.... >", "\n")
myDF <- NULL
mynms <- c(out_flag_var, inter_variables, num_var, date_trans_var)
mynms <- setdiff(mynms, zeroNms)
if (length(mynms) > 1){
suppressWarnings(myDF <- cor (XX[mynms], use = "pairwise.complete.obs"))
myDF <- as.matrix (myDF)
myDF <- ifelse (is.na(myDF), 0, myDF)
myCor <- findCorrelation (myDF, cutoff = corr)
corNms <- mynms[myCor]
}
master_variable <- setdiff(master_variable, corNms)
if (verbose == TRUE) cat("autoDataprep < variable selection - AUC method.... >", "\n")
targetv <- XX[target][, 1]
targetv <- ifelse(is.na(targetv), 0, targetv)
varSel_summary <- calc_auc_df(XX, targetv, master_variable, impvalue = aucv)
varSel_auc <- varSel_summary[[1]]
varSel_auc1 <- varSel_summary[[2]]
low_auc_var <- setdiff(master_variable, varSel_auc)
master_variable <- varSel_auc
mydata <- cbind(data[c(unique_var, target)], XX)
mydata <- mydata[, !duplicated(colnames(mydata))]
cl[[1]] <- as.name("autoDataprep")
fit <- list(call = cl,
datasummary = list(type1 = datstrain, type2 = datstrain1),
master_data = mydata,
raw_list = list("Num_Correlation" = myDF, "AUC_value" = varSel_auc1),
var_list = list("All_columns" = all_names, "Numeric_col" = num_var, "Character_col" = char_var, "Factor_col" = factor_var,
"Logical_col" = logical_var, "Date_col" = date_var, "Unique_col" = unique_var, "MAR_col" = mar_variable,
"Dummy_col" = dumvarnam, "Dropped_col" = drop_var, "Low_auc_col" = low_auc_var,
"first_set_var" = varbucket, "final_var_list" = master_variable, "cor_var" = corNms,
"auc_var" = varSel_auc, "overall_variable" = all_variable, "zerovariance" = zeroNms,
"outlier_summary" = out_flag_var, "mydata_var" = unique(c(unique_var, target, master_variable))))
attr(fit, "class") <- "autoDataprep"
invisible(gc(verbose = FALSE))
return(fit)
} |
suppressPackageStartupMessages({
library(dsos)
library(testthat)
})
set.seed(123456)
n <- 1e4
alpha <- 0.05
test_that("Inliers", {
x1 <- data.frame(x = rnorm(n, sd = 1))
x2 <- data.frame(x = rnorm(n, sd = 1 / 2))
expect_lt(cp_ss(x1, x2)$p_value, alpha)
})
test_that("Outliers", {
x1 <- data.frame(x = rnorm(n, sd = 1))
x2 <- data.frame(x = rnorm(n, sd = 3 / 2))
expect_lt(cp_ss(x1, x2)$p_value, alpha)
})
test_that("Same distribution", {
x1 <- data.frame(x = rnorm(n))
x2 <- data.frame(x = rnorm(n))
expect_gt(cp_ss(x1, x2)$p_value, alpha)
}) |
print.select <- function(x, ...){
if(!inherits(x, "select")) {
stop("Input should be a 'select' object, as obtained from 'atom.select()'")
}
cat("\n Call: ", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n", sep = "")
cat( paste0("\n Atom Indices
"\n XYZ Indices
if( length(x$atom) != (length(x$xyz)/3) )
warning("Atom and XYZ Indices Miss-Match")
i <- paste(attributes(x)$names, collapse = ", ")
cat(strwrap(paste(" + attr:", i), width = 45, exdent = 8), sep = "\n")
} |
context("Testing AHR functionality")
test_that("Test AHR function", {
y <- c(rep(1, 10), rep(0, 10))
phat <- seq(1, 0, length = length(y))
Metric <- AHR(y, phat)
expect_equal(Metric, 1)
}) |
deviance.bess=function(object,...){
n=object$nsample
if(object$family!="bess_gaussian"){
deviance=object$deviance
nulldeviance=object$nulldeviance
out=c(nulldeviance, deviance)
}else{
deviance=n*log(object$mse)
nulldeviance=n*log(object$nullmse)
out=c(nulldeviance, deviance)
}
names(out)=c('nulldeviance',colnames(object$beta))
return(out)
}
deviance.bess.one=function(object,...)
{
n=object$nsample
if(object$family!="bess_gaussian"){
deviance=object$deviance
nulldeviance=object$nulldeviance
out=c(nulldeviance, deviance)
}else{
deviance=n*log(object$mse)
nulldeviance=n*log(object$nullmse)
out=c(nulldeviance, deviance)
}
names(out)=c('nulldeviance','deviance')
return(out)
} |
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "GFS.GCCL"
set.seed(2)
training <- twoClassSim(30, linearVars = 2)
testing <- twoClassSim(30, linearVars = 2)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all")
cctrl2 <- trainControl(method = "LOOCV")
cctrl3 <- trainControl(method = "none")
cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_class_cv_model <- train(trainX, trainY,
method = "GFS.GCCL",
trControl = cctrl1,
tuneLength = 2,
preProc = c("center", "scale"))
set.seed(849)
test_class_cv_form <- train(Class ~ ., data = training,
method = "GFS.GCCL",
trControl = cctrl1,
tuneLength = 2,
preProc = c("center", "scale"))
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)])
set.seed(849)
test_class_rand <- train(trainX, trainY,
method = "GFS.GCCL",
trControl = cctrlR,
tuneLength = 4)
set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "GFS.GCCL",
trControl = cctrl2,
tuneLength = 2,
preProc = c("center", "scale"))
set.seed(849)
test_class_none_model <- train(trainX, trainY,
method = "GFS.GCCL",
trControl = cctrl3,
tuneGrid = test_class_cv_model$bestTune,
preProc = c("center", "scale"))
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
set.seed(849)
test_class_rec <- train(x = rec_cls,
data = training,
method = "GFS.GCCL",
tuneLength = 2,
trControl = cctrl1)
if(
!isTRUE(
all.equal(test_class_cv_model$results,
test_class_rec$results))
)
stop("CV weights not giving the same results")
test_class_imp_rec <- varImp(test_class_rec)
test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)])
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
if(!interactive())
q("no") |
vanWaerdenTest <- function(x, ...) UseMethod("vanWaerdenTest")
vanWaerdenTest.default <-
function(x, g, ...)
{
if (is.list(x)) {
if (length(x) < 2L)
stop("'x' must be a list with at least 2 elements")
DNAME <- deparse(substitute(x))
x <- lapply(x, function(u) u <- u[complete.cases(u)])
k <- length(x)
l <- sapply(x, "length")
if (any(l == 0))
stop("all groups must contain data")
g <- factor(rep(1 : k, l))
x <- unlist(x)
}
else {
if (length(x) != length(g))
stop("'x' and 'g' must have the same length")
DNAME <- paste(deparse(substitute(x)), "and",
deparse(substitute(g)))
OK <- complete.cases(x, g)
x <- x[OK]
g <- g[OK]
if (!all(is.finite(g)))
stop("all group levels must be finite")
g <- factor(g)
k <- nlevels(g)
if (k < 2)
stop("all observations are in the same group")
}
n <- length(x)
if (n < 2)
stop("not enough observations")
r <- rank(x)
zscores <- qnorm(r / (n+1))
AJ <- tapply(zscores, g, sum)
NJ <- tapply(zscores, g, length)
s2 <- sum(zscores^2) / (n - 1)
STATISTIC <- (1 / s2) * sum(AJ^2 / NJ)
PARAMETER <- k - 1
PVAL <- pchisq(STATISTIC, PARAMETER, lower.tail = FALSE)
names(STATISTIC) <- "Van der Waerden chi-squared"
names(PARAMETER) <- "df"
RVAL <- list(statistic = STATISTIC,
parameter = PARAMETER,
p.value = PVAL,
method = "Van der Waerden normal scores test",
data.name = DNAME)
class(RVAL) <- "htest"
return(RVAL)
}
vanWaerdenTest.formula <-
function(formula, data, subset, na.action, ...)
{
if(missing(formula) || (length(formula) != 3L))
stop("'formula' missing or incorrect")
m <- match.call(expand.dots = FALSE)
if(is.matrix(eval(m$data, parent.frame())))
m$data <- as.data.frame(data)
m[[1L]] <- quote(stats::model.frame)
mf <- eval(m, parent.frame())
if(length(mf) > 2L)
stop("'formula' should be of the form response ~ group")
DNAME <- paste(names(mf), collapse = " by ")
names(mf) <- NULL
y <- do.call("vanWaerdenTest", as.list(mf))
y$data.name <- DNAME
y
} |
context("autowin function")
test_that("AutoWinOutput has created an output", {
data(Mass, envir = environment())
data(MassClimate, envir = environment())
single <- singlewin(xvar = list(Temp = MassClimate$Temp), cdate = MassClimate$Date, bdate = Mass$Date,
baseline = lm(Mass ~ 1, data = Mass), range = c(1, 1),
stat = "mean", func = "lin",
type = "relative", cmissing = FALSE, cinterval = "day")
test <- autowin(reference = single,
xvar = list(Temp = MassClimate$Temp), cdate = MassClimate$Date, bdate = Mass$Date,
baseline = lm(Mass ~ 1, data = Mass), range = c(2, 1),
stat = "mean", func = "lin", type = "relative", cmissing = FALSE, cinterval = "day")
furthest <- 2
closest <- 1
duration <- (furthest - closest) + 1
maxmodno <- (duration * (duration + 1))/2
expect_true(exists("test"))
expect_equal(length(which(is.na(test))), 0)
expect_true(ncol(test) >= 7)
expect_equal(maxmodno, nrow(test))
expect_true(round(test$cor[2], 1) == 0.8)
expect_true(test$BestWindowOpen[1] == 1 & test$BestWindowOpen[1] == 1)
})
test_that("Spatial replication works with autowin", {
data(Mass, envir = environment())
Mass$Plot <- c(rep(c("A", "B"), 23), "A")
data(MassClimate, envir = environment())
MassClimate$Plot <- "A"
MassClimate2 <- MassClimate
MassClimate2$Plot <- "B"
Clim <- rbind(MassClimate, MassClimate2)
single <- singlewin(xvar = list(Temp = Clim$Temp), cdate = Clim$Date, bdate = Mass$Date,
baseline = lm(Mass ~ 1, data = Mass), range = c(1, 1),
stat = "mean", func = "lin",
type = "relative", cmissing = FALSE, cinterval = "day",
spatial = list(Mass$Plot, Clim$Plot))
test <- autowin(reference = single,
xvar = list(Temp = Clim$Temp), cdate = Clim$Date, bdate = Mass$Date,
baseline = lm(Mass ~ 1, data = Mass), range = c(2, 1),
stat = "mean", func = "lin", type = "relative", cmissing = FALSE, cinterval = "day",
spatial = list(Mass$Plot, Clim$Plot))
furthest <- 2
closest <- 1
duration <- (furthest - closest) + 1
maxmodno <- (duration * (duration + 1))/2
expect_true(exists("test"))
expect_equal(length(which(is.na(test))), 0)
expect_true(ncol(test) >= 7)
expect_equal(maxmodno, nrow(test))
expect_true(round(test$cor[2], 1) == 0.8)
expect_true(test$BestWindowOpen[1] == 1 & test$BestWindowOpen[1] == 1)
}) |
load_claim_data<-function(GT.startDate = "2004-01-03", GT.endDate = "2016-12-31"){
icnsa=read.csv(system.file("extdata", "ICNSA.csv", package = "PRISM.forecast"), header=T)
fmt <- "%Y-%m-%d"
date.all = as.Date(icnsa[,1],fmt)
claim.all = xts::xts(icnsa[,2],date.all)
colnames(claim.all) <- "icnsa"
startDate = '1980-01-05'
fmt='%Y-%m-%d'
startIdx = which(time(claim.all)==as.Date(startDate,fmt))
endIdx = which(time(claim.all)==as.Date(GT.startDate,fmt))-1
claim.earlyData=claim.all[startIdx:endIdx]
startIdx=which(time(claim.all)==as.Date(GT.startDate,fmt))
endIdx=which(time(claim.all)==as.Date(GT.endDate,fmt))
claim.data=claim.all[startIdx:endIdx]
data_all <- list()
data_all$claim.earlyData <- claim.earlyData
data_all$claim.all <- claim.all
data_all$claim.data <- claim.data
data_all
} |
summary.monthglm<-function(object, ...){
if (class(object)!="monthglm"){stop("Object must be of class 'monthglm'")}
z<-qnorm(0.975)
s<-summary(object$glm)
type<-as.character(object$call$family)[1]
out<-as.data.frame(matrix(data=NA,nrow=nrow(s$coef),ncol=5))
names(out)<-c('mean','lower','upper','zvalue','pvalue')
row.names(out)<-row.names(s$coef)
out$mean<-s$coef[,1]
out$lower<-s$coef[,1]-(z*s$coef[,2])
out$upper<-s$coef[,1]+(z*s$coef[,2])
out$zvalue<-s$coef[,3]
out$pvalue<-s$coef[,4]
if (type=="poisson"|type=="binomial"){
out$mean<-exp(out$mean)
out$lower<-exp(out$lower)
out$upper<-exp(out$upper)
}
index<-grep("months",row.names(out),ignore.case=TRUE,value=FALSE)
totable<-out[index,]
effect<-''
if (type=="poisson"){effect='RR'}
if (type=="binomial"){effect='OR'}
ret<-list()
ret$n=length(object$residuals)
ret$month.ests=totable
ret$month.effect=effect
class(ret) <- "summary.monthglm"
ret
} |
`mgee` <-
function (formula = formula(data), id = id, data = parent.frame(),
subset, na.action, R = NULL, b = NULL, tol = 0.001, maxiter = 25,
family = gaussian, corstr = "independence", Mv = 1, silent = TRUE,
contrasts = NULL, scale.fix = FALSE, scale.value = 1, v4.4compat = FALSE)
{
call <- match.call()
call[[1]]<-as.name("gee")
geeOutput<-eval(call)
out<-geeUOmega(geeOutput)
out
} |
options(prompt = "R> ", continue = "+ ", width = 70, useFancyQuotes = FALSE)
library("ordinal")
library("xtable")
clm_args <- gsub("function ", "clm", deparse(args(clm)))
cat(paste(clm_args[-length(clm_args)], "\n"))
cc_args <- gsub("function ", "clm.control", deparse(args(clm.control)))
cat(paste(cc_args[-length(cc_args)], "\n"))
tab <- with(wine, table(temp:contact, rating))
mat <- cbind(rep(c("cold", "warm"), each = 2),
rep(c("no", "yes"), 2),
tab)
colnames(mat) <- c("Temperature", "Contact",
paste("~~", 1:5, sep = ""))
xtab <- xtable(mat)
print(xtab, only.contents=TRUE, include.rownames=FALSE,
sanitize.text.function = function(x) x)
library("ordinal")
fm1 <- clm(rating ~ temp + contact, data=wine)
summary(fm1)
anova(fm1, type="III")
fm2 <- clm(rating ~ temp, data=wine)
anova(fm2, fm1)
drop1(fm1, test="Chi")
fm0 <- clm(rating ~ 1, data=wine)
add1(fm0, scope = ~ temp + contact, test="Chi")
confint(fm1)
fm.nom <- clm(rating ~ temp, nominal = ~ contact, data=wine)
summary(fm.nom)
fm.nom$Theta
anova(fm1, fm.nom)
fm.nom2 <- clm(rating ~ temp + contact, nominal = ~ contact, data=wine)
fm.nom2
nominal_test(fm1)
fm.sca <- clm(rating ~ temp + contact, scale = ~ temp, data=wine)
summary(fm.sca)
scale_test(fm1)
fm.equi <- clm(rating ~ temp + contact, data=wine,
threshold="equidistant")
summary(fm.equi)
drop(fm.equi$tJac %*% coef(fm.equi)[c("threshold.1", "spacing")])
mean(diff(coef(fm1)[1:4]))
anova(fm1, fm.equi)
pr1 <- profile(fm1, alpha=1e-4)
plot(pr1)
plot(pr1, which.par=1)
plot(pr1, which.par=2)
slice.fm1 <- slice(fm1, lambda = 5)
par(mfrow = c(2, 3))
plot(slice.fm1)
plot(slice.fm1, parm = 1)
plot(slice.fm1, parm = 2)
plot(slice.fm1, parm = 3)
plot(slice.fm1, parm = 4)
plot(slice.fm1, parm = 5)
plot(slice.fm1, parm = 6)
slice2.fm1 <- slice(fm1, parm = 4:5, lambda = 1e-5)
par(mfrow = c(1, 2))
plot(slice2.fm1)
plot(slice2.fm1, parm = 1)
plot(slice2.fm1, parm = 2)
convergence(fm1)
head(pred <- predict(fm1, newdata = subset(wine, select = -rating))$fit)
stopifnot(isTRUE(all.equal(fitted(fm1), t(pred)[t(col(pred) == wine$rating)])),
isTRUE(all.equal(fitted(fm1), predict(fm1, newdata=wine)$fit)))
newData <- expand.grid(temp = levels(wine$temp),
contact = levels(wine$contact))
cbind(newData, round(predict(fm1, newdata=newData)$fit, 3),
"class"=predict(fm1, newdata=newData, type="class")$fit)
head(apply(pred, 1, function(x) round(weighted.mean(1:5, x))))
p1 <- apply(predict(fm1, newdata = subset(wine, select=-rating))$fit, 1,
function(x) round(weighted.mean(1:5, x)))
p2 <- as.numeric(as.character(predict(fm1, type="class")$fit))
stopifnot(isTRUE(all.equal(p1, p2, check.attributes = FALSE)))
predictions <- predict(fm1, se.fit=TRUE, interval=TRUE)
head(do.call("cbind", predictions))
wine <- within(wine, {
rating_comb3 <- rating
levels(rating_comb3) <- c("1", "2-4", "2-4", "2-4", "5")
})
ftable(rating_comb3 ~ temp, data=wine)
fm.comb3 <- clm(rating_comb3 ~ temp, data=wine)
summary(fm.comb3)
fm.comb3_b <- clm(rating_comb3 ~ 1, data=wine)
anova(fm.comb3, fm.comb3_b)
fm.nom2 <- clm(rating ~ contact, nominal = ~ temp, data=wine)
summary(fm.nom2)
fm.soup <- clm(SURENESS ~ PRODID * DAY, data=soup)
summary(fm.soup)
with(soup, table(DAY, PRODID))
wine <- within(wine, {
rating_comb2 <- rating
levels(rating_comb2) <- c("1-2", "1-2", "3-5", "3-5", "3-5")
})
ftable(rating_comb2 ~ contact, data=wine)
fm.comb2 <- clm(rating_comb2 ~ contact, scale = ~ contact, data=wine)
summary(fm.comb2)
wine <- within(wine, {
rating_comb3b <- rating
levels(rating_comb3b) <- c("1-2", "1-2", "3", "4-5", "4-5")
})
wine$rating_comb3b[1] <- "4-5"
ftable(rating_comb3b ~ temp + contact, data=wine)
fm.comb3_c <- clm(rating_comb3b ~ contact * temp, scale=~contact * temp,
nominal=~contact, data=wine)
summary(fm.comb3_c)
convergence(fm.comb3_c)
rho <- update(fm1, doFit=FALSE)
names(rho)
rho$clm.nll(rho)
c(rho$clm.grad(rho))
rho$clm.nll(rho, par=coef(fm1))
print(c(rho$clm.grad(rho)), digits=3)
nll <- function(par, envir) {
envir$par <- par
envir$clm.nll(envir)
}
grad <- function(par, envir) {
envir$par <- par
envir$clm.nll(envir)
envir$clm.grad(envir)
}
nlminb(rho$par, nll, grad, upper=c(rep(Inf, 4), 2, 2), envir=rho)$par
artery <- data.frame(disease = factor(rep(0:4, 2), ordered = TRUE),
smoker = factor(rep(c("no", "yes"), each=5)),
freq = c(334, 99, 117, 159, 30, 350, 307, 345, 481, 67))
addmargins(xtabs(freq ~ smoker + disease, data = artery), margin = 2)
fm <- clm(disease ~ smoker, weights=freq, data=artery)
exp(fm$beta)
fm.nom <- clm(disease ~ 1, nominal = ~ smoker, weights=freq, data=artery,
sign.nominal = "negative")
coef(fm.nom)[5:8]
coef(fm.lm <- lm(I(coef(fm.nom)[5:8]) ~ I(0:3)))
nll2 <- function(par, envir) {
envir$par <- c(par[1:4], par[5] + par[6] * (0:3))
envir$clm.nll(envir)
}
start <- unname(c(coef(fm.nom)[1:4], coef(fm.lm)))
fit <- nlminb(start, nll2, envir=update(fm.nom, doFit=FALSE))
round(fit$par[5:6], 2) |
limit <-
function(x,nx,y,ny,conflev,lim,t){
z = qchisq(conflev,1)
px = x/nx
score= 0
while ( score < z){
a = ny*(lim-1)
b = nx*lim+ny-(x+y)*(lim-1)
c = -(x+y)
p2d = (-b+sqrt(b^2-4*a*c))/(2*a)
p1d = p2d*lim/(1+p2d*(lim-1))
score = ((nx*(px-p1d))^2)*(1/(nx*p1d*(1-p1d))+1/(ny*p2d*(1-p2d)))*(nx+ny-1)/(nx+ny)
ci = lim
if(t==0) { lim = ci/1.001 }
else{ lim = ci*1.001 }
}
return(ci)
} |
testthat::test_that("TN: initialize function works", {
lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
levels = rev(lvs))
pred <- factor(
c(
rep(lvs, times = c(54, 32)),
rep(lvs, times = c(27, 231))),
levels = rev(lvs))
xtab <- table(pred, truth)
confMatrix <- ConfMatrix$new(confMatrix = caret::confusionMatrix(xtab))
testthat::expect_is(TN$new(performance = confMatrix),
"TN")
})
testthat::test_that("TN: compute function works", {
lvs <- c("normal", "abnormal")
truth <- factor(rep(lvs, times = c(86, 258)),
levels = rev(lvs))
pred <- factor(
c(
rep(lvs, times = c(54, 32)),
rep(lvs, times = c(27, 231))),
levels = rev(lvs))
xtab <- table(pred, truth)
confMatrix <- ConfMatrix$new(confMatrix = caret::confusionMatrix(xtab))
testthat::expect_is(TN$new(performance = confMatrix)$compute(performance.output = NULL),
"character")
testthat::expect_is(TN$new(performance = NULL)$compute(performance.output = confMatrix),
"character")
})
testthat::test_that("TN: compute function checks parameter type", {
testthat::expect_error(TN$new(performance = NULL)$compute(performance.output = NULL),
"[TN][FATAL] Performance output parameter must be defined as 'MinResult' or 'ConfMatrix' type. Aborting...",
fixed = TRUE)
}) |
context("CRPS for gamma distribution")
test_that("computed values are correct", {
const <- 0.399009355
expect_equal(crps_gamma(.2, 1.1), const)
expect_equal(crps_gamma(.2 * .9, 1.1, scale = .9), const * .9)
}) |
"luzdat" |
context("read_health_facilities")
skip_if(Sys.getenv("TEST_ONE") != "")
testthat::skip_on_cran()
test_that("read_health_facilities", {
test_sf <- read_health_facilities()
expect_true(is(test_sf, "sf"))
expect_equal(nrow(test_sf), 360177)
}) |
"USA_state_boundaries_summary" |
context("daSubmodels for lmWithCov")
test_that("Correct submodels for standard data.frame and lmWithCov", {
nam<-c("SES","IQ","nAch","GPA")
cor.m<-matrix(c(
1 ,.3 ,.41 ,.33,
.3 ,1 , .16 , .57 ,
.41 , .16, 1 , .50 ,
.33 , .57, .50 , 1
),4,4,byrow=T,
dimnames=list(nam,nam)
)
lwith<-lmWithCov(GPA~SES+IQ+nAch,cor.m)
pred.matrix<-matrix(
c(0,0,0,
1,0,0,
0,1,0,
0,0,1,
1,1,0,
1,0,1,
0,1,1,
1,1,1),8,3,byrow=T)
predictors<-c("SES","IQ","nAch")
level<-c(0,1,1,1,2,2,2,3)
response<-c("GPA")
constants<-c("")
ds<-daSubmodels(lwith)
expect_that(as.numeric(ds$pred.matrix),equals(as.numeric(pred.matrix)))
expect_that(ds$predictors,equals(predictors))
expect_that(ds$response,equals(response))
expect_that(ds$level,equals(level))
}) |
context("Generic Manager")
test_that("initialization and parameter setting", {
TEST_DIRECTORY <- test_path("test_results")
generic_manager <- GenericManager$new(results_dir = TEST_DIRECTORY, attr1 = 22)
expect_equal(generic_manager$get_attribute("results_dir"), TEST_DIRECTORY)
expect_equal(generic_manager$get_attribute("attr1"), 22)
expect_error(generic_manager$sample_data <- "dummy", "Sample data should be a data frame")
generic_manager$sample_data <- as.matrix(data.frame(a = 1:4, b = 5:8))
expect_is(generic_manager$sample_data, "data.frame")
expect_silent(generic_manager$sample_data <- NULL)
expect_error(generic_manager$generators <- "dummy",
"Generators must be a list of Generator or inherited class objects")
expect_error(generic_manager$generators <- list(gen1 = "dummy", gen2 = 1:5),
"Generators must be a list of Generator or inherited class objects")
generic_manager$generators <- list(gen1 = Generator$new(), gen2 = Generator$new())
expect_named(generic_manager$generators, c("gen1", "gen2"))
expect_is(generic_manager$generators$gen1, "Generator")
expect_silent(generic_manager$generators <- NULL)
})
test_that("sample message and filename generation", {
generic_manager <- GenericManager$new()
expect_equal(generic_manager$get_message_sample("testing %s message", 1), "testing sample 1 message")
expect_equal(generic_manager$get_results_filename(2), "sample_2_results")
generic_manager$sample_data <- as.matrix(data.frame(attr1 = 3:4, attr2 = 5:6))
generic_manager$results_filename_attributes <- "pre"
expect_equal(generic_manager$get_message_sample("testing %s message", 1), "testing sample 1 message")
expect_equal(generic_manager$get_results_filename(2), "pre_2_results")
generic_manager$results_filename_attributes <- c("pre", "attr1")
expect_equal(generic_manager$get_message_sample("testing %s message", 1), "testing attr1 3 message")
expect_equal(generic_manager$get_results_filename(2), "pre_attr1_4_results")
generic_manager$results_filename_attributes <- c("pre", "attr1", "attr2", "post")
expect_equal(generic_manager$get_message_sample("testing %s message", 1), "testing attr1 3 attr2 5 message")
expect_equal(generic_manager$get_results_filename(2), "pre_attr1_4_attr2_6_post")
generic_manager$results_filename_attributes <- c("pre", "post")
expect_equal(generic_manager$get_message_sample("testing %s message", 1), "testing sample 1 message")
expect_equal(generic_manager$get_results_filename(2), "pre_2_post")
generic_manager$results_filename_attributes <- c("attr2", "post")
expect_equal(generic_manager$get_message_sample("testing %s message", 1), "testing attr2 5 message")
expect_equal(generic_manager$get_results_filename(2), "attr2_6_post")
expect_equal(generic_manager$results_ext, ".RData")
}) |
CDfriedmanV1 <- function(DATA, Jk, R, LASSO, GROUPLASSO, MaxIter){
DATA <- data.matrix(DATA)
I_Data <- dim(DATA)[1]
sumJk <- dim(DATA)[2]
eps <- 10^(-12)
if(missing(MaxIter)){
MaxIter <- 400
}
P <- matrix(stats::rnorm(sumJk * R), nrow = sumJk, ncol = R)
Pt <- t(P)
absP <- abs(P)
pen_l <- LASSO * sum(absP)
sqP <- P^2
L <- 1
pen_g <- 0
for (i in 1:length(Jk)){
U <- L + Jk[i] - 1
sqrtsumP <- sqrt(colSums(sqP[L:U, ]))/sqrt(Jk[i])
pen_g <- pen_g + GROUPLASSO * sum(sqrtsumP) * Jk[i]
L <- U + 1
}
residual <- sum(DATA ^ 2)
Lossc <- residual + pen_l + pen_g
conv <- 0
iter <- 1
Lossvec <- array()
while (conv == 0){
if (LASSO == 0 & GROUPLASSO == 0){
SVD_DATA <- svd(DATA, R, R)
Tmat <- SVD_DATA$u
}
else {
A <- Pt %*% t(DATA)
SVD_DATA <- svd(A, R, R)
Tmat <- SVD_DATA$v %*% t(SVD_DATA$u)
}
residual <- sum((DATA - Tmat %*% Pt)^2)
Lossu <- residual + pen_l + pen_g
if (LASSO == 0 & GROUPLASSO == 0){
P <- t(DATA) %*% Tmat
Pt <- t(P)
}
else{
L <- 1
for (i in 1:length(Jk)){
U <- L + Jk[i] - 1
Pt_1 <- Pt[ ,c(L:U)]
data <- DATA[ ,c(L:U)]
if (sum(abs(Pt_1)) != 0){
S_2Vec_Lambda <- soft_th(2 * t(Tmat) %*% data, LASSO)
S_2Vec_Lambda_norm <- sqrt(sum(S_2Vec_Lambda^2))
s_l2 <- 0.5 - 0.5 * GROUPLASSO * sqrt(Jk[i])/S_2Vec_Lambda_norm
if (s_l2 <= 0 | S_2Vec_Lambda_norm==0){
Pt[ ,c(L:U)] <- 0
} else if(s_l2 > 0){
Pt[ ,c(L:U)] <- s_l2 * S_2Vec_Lambda
}
}
L <- U + 1
}
P <- t(Pt)
}
pen_l <- LASSO*sum(abs(P))
sqP <- P^2
L <- 1
pen_g <- 0
for (i in 1:length(Jk)){
U <- L + Jk[i] - 1
sqrtsumP <- sqrt(colSums(sqP[L:U, ]))/sqrt(Jk[i])
pen_g <- pen_g + GROUPLASSO * sum(sqrtsumP) * Jk[i]
L <- U + 1
}
residual <- sum((DATA - Tmat %*% Pt)^2)
Lossu2 <- residual + pen_l + pen_g
if (abs(Lossc-Lossu)< 10^(-9)) {
Loss <- Lossu
residual <- residual
lassopen <- pen_l
Glassopen <- pen_g
P[abs(P) <= 2 * eps] <- 0
conv <- 1
}
else if (iter > MaxIter | LASSO == 0){
Loss <- Lossu
residual <- residual
lassopen <- pen_l
Glassopen <- pen_g
P[abs(P) <= 2 * eps] <- 0
conv <- 1
}
Lossvec[iter] <- Lossu
iter <- iter + 1
Lossc <- Lossu2
}
return_varselect <- list()
return_varselect$Pmatrix <- P
return_varselect$Tmatrix <- Tmat
return_varselect$Loss <- Loss
return_varselect$Lossvec <- Lossvec
return(return_varselect)
} |
library(simplermarkdown)
if (simplermarkdown:::has_pandoc()) {
dir <- tempdir()
dir.create(dir, recursive = TRUE, showWarnings = FALSE)
oldwd <- setwd(dir)
old_env <- Sys.getenv("R_TESTS")
Sys.setenv("R_TESTS" = "")
message("Checking iris.md")
md <- "iris.md"
r <- "iris.R"
message("Tangle file")
fn <- system.file(file.path("examples", md), package = "simplermarkdown")
mdtangle(fn)
message("Compare to reference")
lines <- readLines(r)
fn_ref <- system.file(file.path("examples_output", r),
package = "simplermarkdown")
lines_ref <- readLines(fn_ref)
stopifnot(isTRUE(all.equal(lines, lines_ref)))
message("Cleanup")
unlink(r)
message("Checking example1.md")
md <- "example1.md"
r <- "example1.R"
message("Tangle file")
fn <- system.file(file.path("examples", md), package = "simplermarkdown")
mdtangle(fn)
message("Compare to reference")
lines <- readLines(r)
fn_ref <- system.file(file.path("examples_output", r),
package = "simplermarkdown")
lines_ref <- readLines(fn_ref)
stopifnot(isTRUE(all.equal(lines, lines_ref)))
message("Cleanup")
unlink(r)
Sys.setenv("R_TESTS" = old_env)
setwd(oldwd)
} |
wasserstein <- function(X = NULL, Y = NULL, a= NULL, b = NULL, cost = NULL, tplan = NULL, p = 2, ground_p = 2,
method = transport_options(),
cost_a = NULL, cost_b = NULL, ... ) {
if (is.null(method)) method <- "networksimplex"
method <- match.arg(method)
p <- as.double(p)
if (!(p >= 1)) stop("p must be >= 1")
if (is.null(cost) & is.null(tplan)) {
args <- list(X = X, Y = Y, a = a, b = b, p = p, ground_p = ground_p,
method = method, ... )
args <- args[!duplicated(names(args))]
argn <- lapply(names(args), as.name)
f.call <- as.call(stats::setNames(c(as.name("wasserstein_calc_cost"), argn), c("", names(args))))
loss <- eval(f.call, envir = args)
} else if (is.null(tplan)) {
if (is.null(ground_p)) ground_p <- p
n1 <- nrow(cost)
n2 <- ncol(cost)
if (missing(a) || is.null(a)) {
warning("assuming all points in first group have equal mass")
a <- as.double(rep(1/n1, n1))
}
if (missing(b) || is.null(b)) {
warning("assuming all points in first group have equal mass")
b <- as.double(rep(1/n2, n2))
}
nzero_a <- a != 0
nzero_b <- b != 0
mass_x <- a[nzero_a]
mass_y <- b[nzero_b]
cost <- cost[nzero_a, nzero_b, drop = FALSE]
if (method == "sinkhorn" && isTRUE(list(...)$unbiased) ) {
cost_a <- cost_a[nzero_a, nzero_a, drop = FALSE]
cost_b <- cost_b[nzero_b, nzero_b, drop = FALSE]
if(is.null(cost_a) || is.null(cost_b)) stop("Must specify cost matrices for both separate groups for unbiased sinkhorn.")
pot <- sinkhorn_pot(mass_x = mass_x, mass_y = mass_y, p = p,
cost = cost, cost_a = cost_a, cost_b = cost_b, ...)
return((sum(mass_x * pot$f) + sum(mass_y * pot$g))^(1/p))
}
tplan <- transport_plan_given_C(mass_x, mass_y, p, cost, method, cost_a, cost_b, ...)
loss <- wasserstein_(mass_ = tplan$mass, cost_ = cost, p = p, from_ = tplan$from, to_ = tplan$to)
} else {
loss <- wasserstein_(mass_ = tplan$mass, cost_ = cost, p = p, from_ = tplan$from, to_ = tplan$to)
nzero_a <- rep(TRUE, nrow(cost))
nzero_b <- rep(TRUE, ncol(cost))
}
return(loss)
}
wasserstein_calc_cost <- function(X, Y, a = NULL, b = NULL, p = 2, ground_p = 2, observation.orientation = c("rowwise","colwise"),
method = transport_options(), ... ) {
obs <- match.arg(observation.orientation, c("colwise","rowwise"))
method <- match.arg(method)
if (missing(X)) stop("Must specify X")
if (missing(Y)) stop("Must specify Y")
if (!is.matrix(X)) {
X <- as.matrix(X)
if (dim(X)[2] == 1 & obs == "colwise") X <- t(X)
}
if (!is.matrix(Y)) {
Y <- as.matrix(Y)
if (dim(Y)[2] == 1 & obs == "colwise") Y <- t(Y)
}
p <- as.double(p)
ground_p <- as.double(ground_p)
if (!(p >= 1)) stop("p must be >= 1")
if (obs == "rowwise") {
X <- t(X)
Y <- t(Y)
obs <- "colwise"
}
stopifnot(nrow(X) == nrow(Y))
stopifnot(all(is.finite(X)))
stopifnot(all(is.finite(Y)))
if (method == "univariate.approximation" ) {
loss <- wasserstein_p_iid_(X,Y, p)
} else if ( method == "univariate.approximation.pwr") {
loss <- wasserstein_p_iid_p_(X,Y, p)
} else if (method == "univariate" | method == "hilbert" | method == "rank") {
tp <- transport_plan(X = X, Y = Y, a = a, b = b, p = p, ground_p = ground_p,
observation.orientation = obs, method = method, ...)
loss <- tp$cost
} else if (method == "sliced") {
n1 <- ncol(X)
n2 <- ncol(Y)
if (missing(a) || is.null(a)) {
a <- as.double(rep(1/n1, n1))
}
if (missing(b) || is.null(b)) {
b <- as.double(rep(1/n2, n2))
}
nzero_a <- a != 0
nzero_b <- b != 0
a <- a[nzero_a]
b <- b[nzero_b]
X <- X[, nzero_a, drop = FALSE]
Y <- Y[, nzero_b, drop = FALSE]
dots <- list(...)
tplan <- NULL
nboot <- dots$nsim
d <- nrow(X)
theta <- matrix(stats::rnorm(d * nboot), d, nboot)
theta <- sweep(theta, 2, STATS = apply(theta,2,function(x) sqrt(sum(x^2))), FUN = "/")
X_theta <- crossprod(x = X, y = theta)
Y_theta <- crossprod(x = Y, y = theta)
costs <- sapply(1:nboot, function(i) {
x <- c(X_theta[,i])
y <- c(Y_theta[,i])
trans <- general_1d_transport(X = t(x), Y = t(y),
a = a, b = b,
method = "univariate")
cost <- ((abs(x[trans$from] - y[trans$to])^ground_p)^(1/ground_p))^p %*% trans$mass
return(cost)
}
)
loss <- mean(costs)^(1/p)
} else {
n1 <- ncol(X)
n2 <- ncol(Y)
if (missing(a) || is.null(a)) {
a <- as.double(rep(1/n1, n1))
}
if (missing(b) || is.null(b)) {
b <- as.double(rep(1/n2, n2))
}
nzero_a <- a != 0
nzero_b <- b != 0
mass_x <- a[nzero_a]
mass_y <- b[nzero_b]
X <- X[, nzero_a, drop = FALSE]
Y <- Y[, nzero_b, drop = FALSE]
if (isTRUE(list(...)$unbiased) && method == "sinkhorn" ) {
cost <- cost_calc(X,Y, ground_p)
cost_a <- cost_calc(X,X, ground_p)
cost_b <- cost_calc(Y,Y, ground_p)
pot <- sinkhorn_pot(mass_x = mass_x, mass_y = mass_y, p = p,
cost = cost, cost_a = cost_a, cost_b = cost_b, ...)
return((sum(mass_x * pot$f) + sum(mass_y * pot$g))^(1/p))
}
tp <- transport_plan(X = X, Y = Y, a = a, b = b, p = p, ground_p = ground_p,
observation.orientation = obs, method = method, ...)
tplan <- tp$tplan
loss <- wasserstein_(mass_ = tplan$mass, cost_ = tp$cost, p = p, from_ = tplan$from, to_ = tplan$to)
}
return(loss)
}
wasserstein_individual <- function(X,Y, ground_p, observation.orientation = c("colwise","rowwise")) {
if (!is.matrix(X)) X <- as.matrix(X)
if (!is.matrix(Y)) Y <- as.matrix(Y)
obs <- match.arg(observation.orientation)
if (obs == "rowwise") {
X <- t(X)
Y <- t(Y)
}
Xs <- apply(X,2,sort)
Ys <- apply(Y,2,sort)
loss <- colMeans((Xs - Ys)^ground_p)
return(loss^(1/ground_p))
}
general_dist <- function(X, Y) {
idx_x <- hilbert_proj_(X) + 1
idx_y <- hilbert_proj_(Y) + 1
n <- ncol(X)
m <- ncol(Y)
mass_a <- rep(1/n, n)
mass_b <- rep(1/m, m)
cum_a <- c(cumsum(mass_a))[-n]
cum_b <- c(cumsum(mass_b))[-m]
mass <- diff(c(0,sort(c(cum_a, cum_b)),1))
cum_m <- cumsum(mass)
arep <- table(cut(cum_m, c(-Inf, cum_a, Inf)))
brep <- table(cut(cum_m, c(-Inf, cum_b, Inf)))
a_idx <- rep(idx_x, times = arep)
b_idx <- rep(idx_y, times = brep)
transport <- list(from = a_idx[order(b_idx)], to = sort(b_idx), mass = mass[order(b_idx)])
return(transport)
}
wasserstein_multimarg <- function(..., p = 2, ground_p = 2, observation.orientation = c("rowwise","colwise"),
method = c("hilbert", "univariate")) {
if (method == "univariate" | method == "hilbert" ) {
tp <- transport_plan_multimarg(..., p = p, ground_p = ground_p,
observation.orientation = observation.orientation, method = method)
loss <- tp$cost
} else {
stop("Transport method", method, "not currently supported for multimarginal problems.")
}
return(loss)
} |
ECconversion2=function(ec,soilsolution="1:1", method="USDA"){
if(method=="landon"){
if(soilsolution=="1:1"){ElectConduct=ec*2.2}
else if(soilsolution=="1:5"){ElectConduct=ec*6.4}
else if(soilsolution=="1:3"){ElectConduct=ec*3.81}
}
else if(method=="kargas"){
if(soilsolution=="1:1"){ElectConduct=ec*1.83+0.117}
else if(soilsolution=="1:5"){ElectConduct=ec*6.53-0.108}
}
else if(method=="ozkan"){
if(soilsolution=="1:1"){ElectConduct=ec*1.93-0.57}
else if(soilsolution=="1:2.5"){ElectConduct=ec*3.3-0.2}
else if(soilsolution=="1:5"){ElectConduct=ec*5.97-1.17}
}
else if(method=="USDA") {
if(soilsolution=="1:1"){ElectConduct=ec*3}
else if(soilsolution=="1:5"){ElectConduct=ec*4.5}
else if(soilsolution=="1:2"){ElectConduct=ec*5}
}
else if(method=="hogg") {
if(soilsolution=="1:1"){ElectConduct=ec*1.75-0.37}
else if(soilsolution=="1:2"){ElectConduct=ec*1.38-0.14}
}
else if(method=="zhang") {
if(soilsolution=="1:1"){ElectConduct=ec*1.79+1.46}
}
else if(method=="chi") {
if(soilsolution=="1:5"){ElectConduct=ec*11.68-5.77}
}
else if(method=="park") {
if(soilsolution=="1:5"){ElectConduct=ec*8.7}
}
else if(method=="visconti") {
if(soilsolution=="1:5"){ElectConduct=ec*6.53-0.108}
}
else if(method=="korsandi") {
if(soilsolution=="1:5"){ElectConduct=ec*5.4-0.61}
}
else if(method=="shahid") {
if(soilsolution=="1:2.5"){ElectConduct=ec*4.77}
}
else if(method=="klaustermeier") {
if(soilsolution=="1:5"){ElectConduct=10^(1.256*log10(ec) +0.766)}
}
else if(method=="he") {
if(soilsolution=="1:5"){ElectConduct=exp(0.7*log(ec)+1.78)}
}
return(ElectConduct)
} |
bowlerWktsPredict <- function(df,name,dateRange){
rpart = NULL
df=df %>% filter(date >= dateRange[1] & date <= dateRange[2])
print(names(df))
m <-rpart(wicketNo~delivery,data=df)
atitle <- paste(name,"- No of deliveries to Wicket")
rpart.plot(m,main=atitle)
} |
context("cachedPOST")
public({
clearCache()
test_that("Cache gets set on cachedPOST", {
expect_length(cacheKeys(), 0)
with_fake_http({
expect_POST(a <<- cachedPOST("https://app.crunch.io/api/"),
"https://app.crunch.io/api/")
expect_POST(b <<- cachedPOST("https://app.crunch.io/api/",
body='{"user":"me"}'),
'https://app.crunch.io/api/ {"user":"me"}')
})
expect_length(cacheKeys(), 2)
expect_true(setequal(cacheKeys(),
c("https://app.crunch.io/api/?POST",
"https://app.crunch.io/api/?POST&BODY=aec2de8a85873530777f26424e086337")))
expect_identical(a$url, "https://app.crunch.io/api/")
expect_identical(content(b), list(user="me"))
})
without_internet({
test_that("When the cache is set, can read from it even with no connection", {
expect_no_request(
expect_identical(cachedPOST("https://app.crunch.io/api/"), a)
)
expect_no_request(
expect_identical(cachedPOST("https://app.crunch.io/api/",
body='{"user":"me"}'), b)
)
})
test_that("But uncached() prevents reading from the cache", {
uncached({
expect_POST(cachedPOST("https://app.crunch.io/api/"),
"https://app.crunch.io/api/")
expect_POST(cachedPOST("https://app.crunch.io/api/",
body='{"user":"me"}'),
'https://app.crunch.io/api/ {"user":"me"}')
})
})
test_that("GETs don't read from cachedPOST cache", {
expect_GET(uncached(GET("https://app.crunch.io/api/")),
"https://app.crunch.io/api/")
})
test_that("And POSTs with different payloads don't read the wrong cache", {
expect_POST(cachedPOST("https://app.crunch.io/api/", body="wrong"),
"https://app.crunch.io/api/ wrong")
})
})
}) |
coda.samples.dic <- function (model, variable.names, n.iter, thin, ...)
{
load.module('dic')
start <- model$iter() + thin
varnames=c(variable.names, c('deviance', 'pD'))
out <- jags.samples(model, varnames, n.iter, thin,
type = "trace", ...)
deviance <- out$deviance
pD <- out$pD
out$deviance <- NULL
out$pD <- NULL
ans <- vector("list", model$nchain())
for (ch in 1:model$nchain()) {
ans.ch <- vector("list", length(out))
vnames.ch <- NULL
for (i in seq(along = out)) {
varname <- names(out)[[i]]
d <- dim(out[[i]])
if (length(d) < 3) {
stop("Invalid dimensions for sampled output")
}
vardim <- d[1:(length(d) - 2)]
nvar <- prod(vardim)
niter <- d[length(d) - 1]
nchain <- d[length(d)]
values <- as.vector(out[[i]])
var.i <- matrix(NA, nrow = niter, ncol = nvar)
for (j in 1:nvar) {
var.i[, j] <- values[j + (0:(niter - 1)) * nvar +
(ch - 1) * niter * nvar]
}
vnames.ch <- c(vnames.ch, coda.names(varname, vardim))
ans.ch[[i]] <- var.i
}
ans.ch <- do.call("cbind", ans.ch)
colnames(ans.ch) <- vnames.ch
ans[[ch]] <- mcmc(ans.ch, start = start, thin = thin)
}
dic <- list(deviance = mean(as.vector(deviance)), penalty = mean(as.vector(pD)), type = 'pD')
class(dic) <- "dic"
return(list(samples=mcmc.list(ans), dic=dic))
}
coda.names <- function(basename, dim)
{
if (prod(dim) == 1)
return(basename)
ndim <- length(dim)
lower <- rep(1, ndim)
upper <- dim
pn <- parse.varname(basename)
if (!is.null(pn) && !is.null(pn$lower) && !is.null(pn$upper)) {
if (length(pn$lower) == length(pn$upper)) {
dim2 <- pn$upper - pn$lower + 1
if (isTRUE(all.equal(dim[dim!=1], dim2[dim2!=1],
check.attributes=FALSE))) {
basename <- pn$name
lower <- pn$lower
upper <- pn$upper
ndim <- length(dim2)
}
}
}
indices <- as.character(lower[1]:upper[1])
if (ndim > 1) {
for (i in 2:ndim) {
indices <- outer(indices, lower[i]:upper[i], FUN=paste, sep=",")
}
}
paste(basename,"[",as.vector(indices),"]",sep="")
}
parse.varname <- function(varname) {
v <- try(parse(text=varname, n=1), silent=TRUE)
if (!is.expression(v) || length(v) != 1)
return(NULL)
v <- v[[1]]
if (is.name(v)) {
return(list(name=deparse(v)))
}
else if (is.call(v) && identical(deparse(v[[1]]), "[") && length(v) > 2) {
ndim <- length(v) - 2
lower <- upper <- numeric(ndim)
if (any(nchar(sapply(v, deparse)) == 0)) {
return(NULL)
}
for (i in 1:ndim) {
index <- v[[i+2]]
if (is.numeric(index)) {
lower[i] <- upper[i] <- index
}
else if (is.call(index) && length(index) == 3 &&
identical(deparse(index[[1]]), ":") &&
is.numeric(index[[2]]) && is.numeric(index[[3]]))
{
lower[i] <- index[[2]]
upper[i] <- index[[3]]
}
else return(NULL)
}
if (any(upper < lower))
return (NULL)
return(list(name = deparse(v[[2]]), lower=lower, upper=upper))
}
return(NULL)
} |
tube <- function(times = seq(0, 17.0*3600, by = 100),
yini = NULL, dyini = NULL, parms = list(),
printmescd = TRUE, method = radau,
atol = 1e-6, rtol = 1e-6, maxsteps = 1e5, ...) {
parameter <- c(nu = 1.31e-6, g = 9.8, rho = 1.0e3, rcrit = 2.3e3,
length= 1.0e3, k = 2.0e-4, d= 1.0e0, b = 2.0e2)
parameter <- overrulepar(parameter, parms, 8)
if (is.null(yini)) {
yini <- rep(0,49)
yini[19:36]<- 0.47519404529185289807e-1
yini[37:49] <-109800
}
if (is.null(dyini)) dyini <- rep(0,49)
checkini(49, yini, dyini)
if (is.null(names(yini)))
names(yini) <- c("phi1.2","phi2.3","phi2.6","phi3.4","phi3.5","phi4.5",
"phi5.10","phi6.5","phi7.4","phi7.8","phi8.5","phi8.10","phi9.8",
"phi11.9","phi11.12","phi12.7","phi12.8","phi13.11",
"lam1.2","lam2.3","lam2.6","lam3.4","lam3.5","lam4.5",
"lam5.10","lam6.5","lam7.4","lam7.8","lam8.5","lam8.10","lam9.8",
"lam11.9","lam11.12","lam12.7","lam12.8","lam13.11","p5","58",
"p1","p2","p3","p4","p6","p7","p9","p10","p11","p12","p13")
prob <- tuberprob()
ind <- c(38,11,0)
useres <- FALSE
if (is.character(method)) {
if (method %in% c("mebdfi", "daspk"))
useres <- TRUE
} else if("res" %in% names(formals(method)))
useres <- TRUE
if (useres)
tuber <- dae(y = yini, dy = dyini, times = times,
res = "tuberes", nind = ind,
dllname = "deTestSet", initfunc = "tubepar",
parms = parameter,
maxsteps = maxsteps, method = method, atol= atol, rtol=rtol, ...)
else{
a <- pi * parameter["d"]^2/4
c <- parameter["b"]/(parameter["rho"]*parameter["g"])
v <- parameter["rho"]*parameter["length"]/a
mass <- matrix(nrow = 1, ncol = 49, data = 0.)
mass[1,1:18] <- v
mass[1,37:38] <- c
tuber <- dae(y = yini, dy = dyini, times = times, nind = ind,
func = "tubefunc", mass = mass,
massup = 0, massdown = 0,
dllname = "deTestSet", initfunc = "tubepar",
parms = parameter, method = method,
maxsteps = maxsteps, atol= atol, rtol=rtol,...)
}
if(printmescd)
tuber <- printpr (tuber, prob, "tube", rtol, atol)
return(tuber)
}
tuberprob <- function(){
fullnm <- 'Water tube system'
problm <- 'water'
type <- 'DAE'
neqn <- 49
t <- matrix(1,2)
t[1] <- 0
t[2] <- 17*3600
numjac <- TRUE
mljac <- neqn
mujac <- neqn
return(list(fullnm=fullnm, problm=problm,type=type,neqn=neqn,
t=t,numjac=numjac,mljac=mljac,mujac=mujac))
} |
dtp<- function(f,data,index=c("state","year"),maxlags,initnum,conf,conf1,conf2,graph=TRUE){
data<-newframe(data,index=index)
f1<-as.formula(f)
fm<-f1
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "subset", "na.action"), names(mf), 0)
mf <- mf[c(1, m)]
ffm <- Formula::Formula(fm)
mf[[1]] <- as.name("model.frame")
mf$formula <- ffm
fffm<-update(ffm, ~ . -1| . -1|. -1)
mf <- model.frame(formula=fffm, data=data)
z2 <- model.matrix(fffm, data = mf, rhs = 1)
q <- model.matrix(fffm, data = mf, rhs = 2)
c <- model.matrix(fffm, data = mf, rhs = 3)
y<-model.response(mf)
a<-unlist(strsplit(as.character(f1),"[|]"))
instrument<-makeinstru(data,a[[2]],maxlags,initnum)
x<-as.matrix(instrument$inst)
initial<-instrument$initial
z1<-as.matrix(initial)
largeT<-data$TT
t<-data$t
yt = tr(y,largeT,t)
ct = tr(c,largeT,t)
zt1= tr(z1,largeT,t)
k=length(z2[1,]);
zt2= matrix(c(0),length(yt[,1]),k)
for(i in 1:k){
zt2[,i]=tr(z2[,i],largeT,t)
}
ii=1
qt<-0
for (i in 1:length(q)){
if (t[i]<largeT[i]){
qt[ii]<-q[i]
ii=ii+1
}
}
qt=t(qt)
xx=cbind(x,zt2)
z1hat<-xx%*%regress(zt1,xx)
zhat=cbind(z1hat,zt2)
n=length(yt[,1])
xx=cbind(zhat,tr(c,largeT,t))
k=length(xx[1,])
e=yt-xx%*%regress(yt,xx)
ss0<-sum(e^2)
s0 <- det(t(e)%*%e)
n1 <- round(.05*n)+k
n2 <- round(.95*n)-k
qs <- sort(q)
qs <- qs[n1:n2]
qs <- as.matrix(unique(qs))
qn <- nrow(qs)
sn <- matrix(0,qn,1)
r=1
for(r in 1:qn){
d <- (q<=qs[r])
xxx=cbind(xx,tr(c*d,largeT,t),tr(d,largeT,t))
xxx <- xxx-xx%*%regress(xxx,xx)
ex <- e-xxx%*%regress(e,xxx)
sn[r] <- det(t(ex)%*%ex)
}
r <- which.min(sn)
smin <- sn[r]
qhat <- qs[r]
d <- (q<=qhat)
xxx=cbind(zhat,tr(c*d,largeT,t),tr(d,largeT,t))
beta=regress(yt,xxx)
yhat=xxx%*%beta
e=yt-yhat
lr=n*(sn/smin-1)
sig2=smin/n
i=length(zhat[1,])
beta1=beta[i+1]
beta2=beta[i+3]
if (ncol(yt)> 1){
eta1 <- 1
eta2 <- 1
}else{
r1 <- (ct%*%(beta1-beta2))^2
r2 <- r1*(e^2)
qx <- cbind(t(qt^0),t(qt^1),t(qt^2))
qh <- cbind(qhat^0,qhat^1,qhat^2)
m1 <- qr.solve(qx,r1)
m2 <- qr.solve(qx,r2)
g1 <- qh%*%m1
g2 <- qh%*%m2
eta1 <- as.numeric((g2/g1)/sig2)
sigq <- sqrt(mean((qt-mean(q))^2))
hband <- 2.344*sigq/(n^(.2))
u <- (qhat-qt)/hband
u2 <- u^2
f <- mean((1-u2)*(u2<=1))*(.75/hband)
df <- -mean(-u*(u2<=1))*(1.5/(hband^2))
eps <- r1 - qx%*%m1
sige <- (t(eps)%*%eps)/(n-3)
hband <- as.vector(sige/(4*f*((m1[3]+(m1[2]+2*m1[3]*qhat)*df/f)^2)))
u2 <- ((qhat-qt)/hband)^2
kh <- ((1-u2)*.75/hband)*(u2<=1)
g1 <- mean(kh%*%r1)
g2 <- mean(kh%*%r2)
eta2 <- as.numeric((g2/g1)/sig2)
}
c1 <- -2*log(1-sqrt(conf))
lr0 <- as.numeric(lr >= c1)
lr1 <- as.numeric(lr >= (c1*eta1))
lr2 <- as.numeric(lr >= (c1*eta2))
if (!is.na(max(lr0)==1)){
qcf_0 <- cbind(qs[which.min(lr0)],qs[qn+1-which.min(rev(lr0))])
}else{
qcf_0 <- cbind(qs[1],qs[qn])
}
if (!is.na(max(lr1)==1)){
qcf_h1 <- cbind(qs[which.min(lr1)],qs[qn+1-which.min(rev(lr1))])
}else{
qcf_h1 <- cbind(qs[1],qs[qn])
}
if (!is.na(max(lr2)==1)){
qcf_h2 <- cbind(qs[which.min(lr2)],qs[qn+1-which.min(rev(lr2))])
}else{
qcf_h2 <- cbind(qs[1],qs[qn])
}
if (graph==TRUE){
par(mar = c(5,4,4,8))
mtit <- "Confidence Interval Construction for Threshold"
ytit <- "Likelihood Ratio Sequence in gamma"
xtit <- "Threshold Variable"
xxlim <- range(qs)
clr <- matrix(1,qn,1)*c1
yylim <- range(rbind(lr,clr))
if (ncol(as.matrix(y)) == 1) {clr <- cbind(clr,(clr*eta1),(clr*eta2))}
plot(qs,lr,lty=1
,xlim=xxlim,ylim=yylim,col=1,type="l",ann=0)
lines(qs,clr[,1],lty=2,col=2)
if (ncol(as.matrix(y)) == 1){
lines(qs,clr[,2],lty=1,col=3)
lines(qs,clr[,3],lty=1,col=4)
}
title(main=mtit,ylab=ytit,xlab=xtit,cex.main=0.8,cex.lab=0.8)
tit1 <- "LRn(gamma)"
tit2 <- "90% Critical"
tit3 <- "Hetero Corrected - 1"
tit4 <- "Hetero Corrected - 2"
legend(par("usr")[2],par("usr")[4],
xpd = TRUE ,
bty = "n",
c(tit1,tit2,tit3,tit4),lty=c(1,1,1,1),cex=0.6,col=c(1,2,3,4) )
}
z <- cbind(zt1,zt2)
da <- (q<=qhat)
db <- 1-da
zi=cbind(zt1,zt2,tr(c*da,largeT,t),tr(da,largeT,t),tr(c*db,largeT,t))
xi=cbind(x,zt2,tr(c*da,largeT,t),tr(da,largeT,t),tr(c*db,largeT,t))
yi=yt
out1<- gmm_linear(yi,zi,xi)
beta<-out1$beta
se <- out1$se
betal=beta-se*1.96
betau=beta+se*1.96
n=length(yt[,1])
xx=cbind(zhat,tr(c,largeT,t))
k=length(xx[1,])
e=yt-xx%*%regress(yt,xx)
s0 <- det(t(e)%*%e)
n1 <- round(.05*n)+k
n2 <- round(.95*n)-k
qs <- sort(q)
qs <- qs[n1:n2]
qs <- as.matrix(unique(qs))
qn <- nrow(qs)
sn <- matrix(0,qn,1)
for (r in 1:qn){
d <- (q<=qs[r])
xxx=cbind(xx,tr(c*d,largeT,t),tr(d,largeT,t))
xxx <- xxx-xx%*%regress(xxx,xx)
ex <- e-xxx%*%regress(e,xxx)
sn[r] <- det(t(ex)%*%ex)
}
r <- which.min(sn)
smin <- sn[r]
qhat <- qs[r]
d <- (q<=qhat)
xxx=cbind(zhat,tr(c*d,largeT,t),tr(d,largeT,t))
dd=1-d
xxx=cbind(xxx,tr(c*dd,largeT,t))
betaf=regress(yt,xxx)
yhat=xxx%*%betaf
e=yt-yhat
lr=n*(sn/smin-1)
sig2=smin/n
i=length(x[1,])
betaf1=betaf[i+1]
betaf2=beta[i+3]
if (ncol(yt)> 1){
eta1 <- 1
eta2 <- 1
}else{
r1 <- (ct%*%(betaf1-betaf2))^2
r2 <- r1*(e^2)
qx <- cbind(t(qt^0),t(qt^1),t(qt^2))
qh <- cbind(qhat^0,qhat^1,qhat^2)
m1 <- qr.solve(qx,r1)
m2 <- qr.solve(qx,r2)
g1 <- qh%*%m1
g2 <- qh%*%m2
eta1 <- as.vector((g2/g1)/sig2)
sigq <- sqrt(mean((qt-mean(q))^2))
hband <- 2.344*sigq/(n^(.2))
u <- (qhat-qt)/hband
u2 <- u^2
f <- mean((1-u2)*(u2<=1))*(.75/hband)
df <- -mean(-u*(u2<=1))*(1.5/(hband^2))
eps <- r1 - qx%*%m1
sige <- (t(eps)%*%eps)/(n-3)
hband <- as.vector(sige/(4*f*((m1[3]+(m1[2]+2*m1[3]*qhat)*df/f)^2)))
u2 <- ((qhat-qt)/hband)^2
kh <- ((1-u2)*.75/hband)*(u2<=1)
g1 <- mean(kh%*%r1)
g2 <- mean(kh%*%r2)
eta2 <- as.vector((g2/g1)/sig2)
}
c1 <- -2*log(1-sqrt(conf))
lr0 <- (lr >= c1)
lr1 <- (lr >= (c1*eta1))
lr2 <- (lr >= (c1*eta2))
if (max(lr0)==1){
qcfi_0 <- cbind(qs[which.min(lr0)],qs[qn+1-which.min(rev(lr0))])
}else{
qcfi_0 <- cbind(qs[1],qs[qn])
}
if (!is.na(max(lr1)==1)){
qcfi_1 <- cbind(qs[which.min(lr1)],qs[qn+1-which.min(rev(lr1))])
}else{
qcfi_1 <- cbind(qs[1],qs[qn])
}
if (!is.na(max(lr2)==1)){
qcfi_2 <- cbind(qs[which.min(lr2)],qs[qn+1-which.min(rev(lr2))])
}else{
qcfi_2 <- cbind(qs[1],qs[qn])
}
if (conf2==0) qcf <- qcfi_0
if (conf2==1) qcf <- qcfi_1
if (conf2==2) qcf <- qcfi_2
qq <- unique(q)
qq <- as.matrix(sort(qq))
qq <- qq[qq<=qcf[2]]
qq <- as.matrix(qq[qq>=qcf[1]])
for (i in 1:nrow(qq)){
qi <- qq[i]
dai <- (q<=qi)
dbi <- 1-dai
yi=yt
zi=cbind(zt1,zt2,tr(c*dai,largeT,t),tr(dai,largeT,t),tr(c*dbi,largeT,t))
xi=cbind(x,zt2,tr(c*dai,largeT,t),tr(dai,largeT,t),tr(c*dbi,largeT,t))
out2= gmm_linear(yi,zi,xi)
sei=out2$se
ss1<-sum(out2$e^2)
betafi<-out2$beta
betafil <- apply(t(cbind((betafi-sei*1.96),betal)),2,min)
betafiu <- apply(t(cbind((betafi+sei*1.96),betau)),2,max)
}
nz<-length(zhat[1,])
lm<- n*(ss0-ss1)/ss0
df<-ncol(xx)
lmpv<-pchisq(lm,df,lower.tail = FALSE)
N<-max(data$id)
fm<-(n*(ss0-ss1)/df)/(ss0/(n-N-k))
fmpv<-pchisq(fm,df,lower.tail = FALSE)
lgrt<-n*(log(ss0)-log(ss1))
lgrtpv<-pchisq(lgrt,df,lower.tail = FALSE)
df<-nrow(z2)-ncol(x)
alpha<-betaf[(1:nz)]
std<-se[(1:nz)]
tval<-alpha/std
pval<-2*pnorm(-abs(tval))
lw<-betafil[(1:nz)]
up<-betafiu[(1:nz)]
alpha1<-betaf[(nz+1):(nz+2)]
std1<-se[(nz+1):(nz+2)]
tval1<-alpha1/std1
pval1<-2*pnorm(-abs(tval1))
lw1<-betafil[(nz+1):(nz+2)]
up1<-betafiu[(nz+1):(nz+2)]
alpha2<-betaf[(nz+3):(nz+3)]
std2<-se[(nz+3):(nz+3)]
tval2<-alpha2/std2
pval2<-2*pnorm(-abs(tval2))
lw2<-betafil[(nz+3):(nz+3)]
up2<-betafiu[(nz+3):(nz+3)]
nmes<-colnames(z2)
out<-list(alpha=alpha,std=std,lw=lw,up=up,tval=tval,pval=pval,alpha1=alpha1,std1=std1,lw1=lw1,
up1=up1,tval1=tval1,pval1=pval1,alpha2=alpha2,std2=std2,lw2=lw2,up2=up2,tval2=tval2,pval2=pval2,
lm=lm,lmpv=lmpv,fm=fm,fmpv=fmpv,lgrt=lgrt,lgrtpv=lgrtpv,nmes=nmes,qhat=qhat,qcfi_0=qcfi_0,qcfi_1=qcfi_1,
qcfi_2=qcfi_2,da=da,db=db)
class(out) <- "dtp"
return(out)
} |
weblmListAvailableModels <- function() {
res <- weblmHttr("GET", "models")
json <- httr::content(res, "text", encoding = "UTF-8")
models <- jsonlite::fromJSON(json)$models
supportedOps <- c(unlist(unique(jsonlite::fromJSON(json)$models$supportedOperations)))
for (supportedOp in supportedOps) {
eval(parse(text = paste0(eval(supportedOp), " <- c()")))
for (model in 1:nrow(models)) {
eval(parse(text = paste0(eval(supportedOp), " <- c(", eval(supportedOp),
ifelse(supportedOp %in% models$supportedOperations[[model]], ', "supported")', ', "unsupported")'))))
}
eval(parse(text = paste0('models <- cbind(models, ', eval(supportedOp), ' = factor(',
eval(supportedOp), ', levels = c("unsupported", "supported")))')))
}
models$supportedOperations <- NULL
weblm(models, json, res$request)
} |
context("redesign")
test_that("N not changed", {
N <- 100
d <- declare_model(N = N) + NULL
expect_equal(N, 100)
expect_length(draw_data(d)$ID, 100)
others <- c(50, 100, 200, 100)
d_alt <- redesign(d, N = others)
for (i in seq_along(others)) {
expect_length(draw_data(d_alt[[i]])$ID, others[i])
}
expect_equal(N, 100)
}) |
setMethod("show", signature= "mod_imputeMulti",
def= function(object) {
cat("\n Call: \n", paste(deparse(object@mle_call), sep= "\n"),
"\n Method: ", object@method,
"\n\n Iterations: ", object@mle_iter,
"\n\n Log-Likelihood: ", object@mle_log_lik)
})
setGeneric("summary")
summary.mod_imputeMulti <- function(object, ...) {
methods::show(object)
cat("\n\n")
if (object@mle_cp != "none") {
summary(object@mle_x_y[, c("alpha", "theta_y")])
}
}
setMethod("summary", signature="mod_imputeMulti", def=summary.mod_imputeMulti)
setGeneric("get_parameters",
function(object) standardGeneric("get_parameters"))
setMethod("get_parameters", signature= "mod_imputeMulti",
function(object) {
return(object@mle_x_y)
})
setGeneric("get_prior",
function(object) standardGeneric("get_prior"))
setMethod("get_prior", signature= "mod_imputeMulti",
function(object) {
return(object@mle_cp)
})
setGeneric("get_iterations",
function(object) standardGeneric("get_iterations"))
setMethod("get_iterations", signature= "mod_imputeMulti",
function(object) {
return(object@mle_iter)
})
setGeneric("get_logLik",
function(object) standardGeneric("get_logLik"))
setMethod("get_logLik", signature= "mod_imputeMulti",
function(object) {
return(object@mle_log_lik)
})
setGeneric("get_method",
function(object) standardGeneric("get_method"))
setMethod("get_method", signature= "mod_imputeMulti",
function(object) {
return(object@method)
})
setMethod("show", signature= "imputeMulti",
def= function(object) {
cat("\n Global Call: \n", paste(deparse(object@Gcall), sep= "\n"),
"\n Call: \n", paste(deparse(object@mle_call)),
"\n Method: ", object@method,
"\n\n Iterations: ", object@mle_iter,
"\n\n Log-Likelihood: ", object@mle_log_lik,
"\n Number Missing: ", object@nmiss)
})
setGeneric("summary")
summary.imputeMulti <- function(object, ...) {
methods::show(object)
if (object@mle_cp != "none") {
summary(object@mle_x_y[, c("alpha", "theta_y")])
}
}
setMethod("summary", signature= "imputeMulti",
summary.imputeMulti)
setGeneric("get_imputations",
function(object) standardGeneric("get_imputations"))
setMethod("get_imputations", signature= "imputeMulti",
function(object) {
return(object@data$imputed_data)
})
setGeneric("n_miss",
function(object) standardGeneric("n_miss"))
setMethod("n_miss", signature= "imputeMulti",
function(object) {
return(object@nmiss)
}) |
library(geoBayes)
data(rhizoctonia)
predgrid <- mkpredgrid2d(rhizoctonia[c("Xcoord", "Ycoord")],
par.x = 100, chull = TRUE, exf = 1.2)
rhizdata <- stackdata(rhizoctonia, predgrid$grid)
corrf <- "spherical"
kappa <- 0
ssqdf <- 1
ssqsc <- 1
betm0 <- 0
betQ0 <- .01
linkp <- 20
philist <- c(100, 140, 180)
omglist <- c(0, .5, 1, 1.5)
parlist <- expand.grid(phi=philist, linkp=linkp, omg=omglist, kappa = kappa)
estimate <- list(linkp = linkp, phi = c(100, 200), omg = c(0, 2),
kappa = kappa)
Nout <- 1000
Nthin <- 10
Nbi <- 300
runs <- list()
for (i in 1:NROW(parlist)) {
runs[[i]] <- mcsglmm(Infected ~ 1, 'binomial', rhizdata, weights = Total,
atsample = ~ Xcoord + Ycoord,
Nout = Nout*c(.8, .2), Nthin = Nthin, Nbi = Nbi,
betm0 = betm0, betQ0 = betQ0, ssqdf = ssqdf, ssqsc = ssqsc,
phi = parlist$phi[i], omg = parlist$omg[i],
linkp = parlist$linkp[i], kappa = parlist$kappa[i],
corrfcn = corrf,
corrtuning = list(phi = 0, omg = 0, kappa = 0))
}
bf <- bf1skel(runs)
bfall <- bf2new(bf, phi = seq(100, 200, 10), omg = seq(0, 2, .2))
plotbf2(bfall, c("phi", "omg"))
plotbf2(bfall, c("phi", "omg"), profile = TRUE, type = "b", ylab="log(BF)")
bf2optim(bf, estimate) |
`nLogLik.trecase.A` = function(coef, phi, theta, rc, genei, hessian=FALSE){
index = rc$index
y = rc$y[genei,]
n = rc$n[genei,]
n0B = rc$n0B[genei,]
kappas = rc$kappas
out = input.checks.A(coef=coef, phi=phi, index=index, y=y, kappas=kappas, theta=theta, n=n, n0B=n0B, trecase=TRUE)
hess = NULL
twosex = max(index)>4
if(twosex){
ind.lst = lapply(1:8, function(i){which(index %in% i)})
}else{
ind.lst = lapply(1:4, function(i){which(index %in% i)})
}
nsamples = length(index)
intercept = rep(1, nsamples)
dom = as.numeric(index %in% c(1, 2, 5, 6))
xs = index[1:length(n)];xs[xs == 5] = 1;xs[xs %in% c(2, 6)] = -1
if(twosex){
sex.tot = intercept;sex.tot[index>4] = -1
X = cbind(intercept, kappas, sex.tot, dom, dom*sex.tot)
sex.ase = sex.tot[1:length(n)]
}else{
X = cbind(intercept, kappas, dom)
sex.ase = NULL
}
nll = ll.jRCI.A(coef, yi=y, ind.lst=ind.lst, X=X, twosex=twosex, sex=sex.ase,
ni=n, ni0=n0B, xs=xs, iphi=1/phi, theta=theta)
if(hessian){
tag = tryCatch({
hess = hessian(ll.jRCI.A, x=coef, yi=y, ind.lst=ind.lst, X=X, twosex=twosex, sex=sex.ase,
ni=n, ni0=n0B, xs=xs, iphi=1/phi, theta=theta)
0
}, error=function(e) {
warning("estimation of hessian failed")
1
})
}
return(list(nll=nll, hess=hess))
} |
profanity_patterns <- c(
"\\w*fuck\\w*"
) |
testthat::test_that("Initiation of saga S3 class ", {
testthat::skip_on_cran()
testthat::skip_if(is.null(saga_search()))
saga <- saga_gis()
testthat::expect_true(!is.null(saga))
testthat::expect_gt(length(saga), 0)
})
testthat::test_that("Initiation of saga S3 class using opt_lib ", {
testthat::skip_on_cran()
testthat::skip_if(is.null(saga_search()))
saga1 <- saga_gis(opt_lib = "climate_tools")
testthat::expect_true(!is.null(saga1))
testthat::expect_length(saga1, n = 1)
})
testthat::test_that("Test file caching ", {
testthat::skip_on_cran()
testthat::skip_if(is.null(saga_search()))
saga_bin <- saga_search()
saga_version <- Rsagacmd:::saga_version(saga_cmd = saga_bin)
if (saga_version < as.numeric_version("4.0.0")) {
output <- paste(
"Cannot enable grid caching or change number cores for SAGA-GIS",
"versions < 4.0.0. Please use a more recent version of SAGA-GIS"
)
testthat::expect_message(
saga_gis(grid_caching = TRUE, grid_cache_threshold = 20),
output)
} else {
cache_dir <-
file.path(tempdir(), paste0("test_caching", as.integer(runif(1, 0, 1e6))))
cache_dir <- gsub("//", "/", cache_dir)
cache_dir <- gsub("\\\\", "/", cache_dir)
dir.create(cache_dir)
saga_fc <-
saga_gis(
grid_caching = TRUE,
grid_cache_threshold = 0.001,
grid_cache_dir = cache_dir,
cores = 1
)
testthat::expect_true(!is.null(saga_fc))
testthat::expect_gt(length(saga_fc), 0)
senv <- environment(saga_fc[[1]][[1]])$senv
config_char <- readChar(
con = senv$saga_config,
nchars = file.info(senv$saga_config)$size - 1
)
config_char <- gsub("[\r]", "", config_char)
config_char <- strsplit(config_char, "\n")[[1]]
idx <- grep("GRID_CACHE_TMPDIR", config_char)
config_cache_dir <- strsplit(config_char[idx], "=")[[1]][2]
testthat::expect_equal(shQuote(cache_dir), config_cache_dir)
saga <- saga_gis()
dem <- saga$grid_calculus$random_terrain(
target_user_xmin = 0,
target_user_xmax = 1000,
target_user_ymin = 0,
target_user_ymax = 1000,
radius = 100,
iterations = 500
)
start_time <- Sys.time()
tri <- saga$ta_morphometry$terrain_ruggedness_index_tri(dem = dem)
end_time <- Sys.time()
elapsed_ram <- end_time - start_time
start_time <- Sys.time()
tri_fc <- saga_fc$ta_morphometry$terrain_ruggedness_index_tri(dem = dem)
end_time <- Sys.time()
elapsed_fc <- end_time - start_time
testthat::expect_true(elapsed_fc > elapsed_ram)
}
}) |
library(highcharter)
library(purrr)
library(dplyr)
library(htmltools)
Category <- c("Furniture","Furniture","Furniture","Furniture",
"Office Supplies","Office Supplies", "Office Supplies", "Office Supplies",
"Office Supplies", "Office Supplies", "Office Supplies", "Office Supplies",
"Office Supplies", "Technology","Technology","Technology","Technology")
SubCategory <- c("Bookcases","Chairs","Furnishings","Tables","Appliances","Art","Binders","Envelopes",
"Fasteners","Labels","Paper","Storage", "Supplies", "Accessories","Copiers","Machines",
"Phones")
sales <- c(889222.51,920892.65,239840.16,445823.93,614737.91,225594.68,281494.68,104903.88,50156.06,44269.30,
150113.36,692903.08,152196.19,463383.33,965899.78,458655.43,1005525.38)
mydf <- data.frame(Category,SubCategory,sales, color = colorize(Category))
categories_grouped <- map(unique(Category), function(x){
list(
name = x,
categories = SubCategory[Category == x]
)
})
hc <- highchart() %>%
hc_chart(type = "bar") %>%
hc_xAxis(categories = categories_grouped) %>%
hc_add_series(data = list_parse(select(mydf, y = sales, color = color)),
showInLegend = FALSE)
hc
dep <- htmlDependency(
name = "grouped-categories",
version = "1.1.0",
src = c(
href = "http://blacklabel.github.io/grouped_categories"
),
stylesheet = "css/styles.css",
script = "grouped-categories.js"
)
hc$dependencies <- c(hc$dependencies, list(dep))
hc |
cobiclust <-
function(x, K = 2, G = 3, nu_j = NULL, a = NULL, akg = FALSE, cvg_lim = 1e-05,
nbiter = 5000){
tol = 1e-04
res_init <- init_pam(x = x, nu_j = nu_j, a = a, K = K, G = G, akg = akg)
n <- nrow(x)
m <- ncol(x)
nu_j <- res_init$parameters$nu_j
mu_i <- res_init$parameters$mu_i
t_jg <- res_init$info$t_jg
s_ik <- res_init$info$s_ik
pi_c <- res_init$parameters$pi
rho_c <- res_init$parameters$rho
alpha_c <- matrix(nrow = K, ncol = G, res_init$parameters$alpha)
a0 <- res_init$parameters$a
exp_utilde <- res_init$info$exp_utilde
exp_logutilde <- res_init$info$exp_logutilde
lb <- NULL
lbtt <- NULL
j <- 0
crit <- 1
while((crit > cvg_lim) & (j < nbiter))
{
j = j+1
t_old <- t_jg
s_old <- s_ik
pi_old <- pi_c
rho_old <- rho_c
alpha_old <- alpha_c
a_old <- a0
exp_utilde_old <- exp_utilde
exp_logutilde_old <- exp_logutilde
i <- 0
crit_em1 <- 1
while(crit_em1 > cvg_lim)
{
i = i + 1
pi_old <- pi_c
alpha_old1 <- alpha_c
if (is.matrix(nu_j)){
s_ik_tmp1 <- sapply(1:K, FUN = function(k) log(pi_c[k]) +
rowSums(sapply(1:ncol(x), FUN = function(j) rowSums(
sapply(1:G, FUN = function(l)
t_jg[j, l] * x[, j] * (log(alpha_c[k, l]) + exp_logutilde[, j])
- t_jg[j, l] * mu_i * nu_j[, j] * alpha_c[k, l] * exp_utilde[, j])))))
} else {
s_ik_tmp1 <- sapply(1:K, FUN = function(k) log(pi_c[k]) +
rowSums(sapply(1:ncol(x), FUN = function(j) rowSums(
sapply(1:G, FUN = function(l)
t_jg[j, l] * x[, j] * (log(alpha_c[k, l]) + exp_logutilde[, j])
- t_jg[j, l] * mu_i * nu_j[j] * alpha_c[k, l] * exp_utilde[, j])))))
}
s_ik_tmp2 <-s_ik_tmp1 - rowMeans(s_ik_tmp1)
s_ik_tmp <- apply(s_ik_tmp2, 2, FUN = function(x) exp(x) / rowSums(exp(s_ik_tmp2)))
if (sum(is.nan(s_ik)) > 0) {
rmax <- apply(s_ik_tmp1, 1, max)
s_ik_tmp3 <- s_ik_tmp1 - rmax
s_ik <- apply(s_ik_tmp3, 2, FUN = function(x) exp(x) / rowSums(exp(s_ik_tmp3)))
}
rm(s_ik_tmp1, s_ik_tmp2, s_ik_tmp)
s_ik <- apply(s_ik, c(1, 2), FUN = function(x) if (x <= 0.5) max(tol, x)
else if (x > 0.5) min(x, 1 - tol))
s_ik[s_ik == tol] <- tol / (ncol(s_ik) - 1)
s_ik <- s_ik / rowSums(s_ik)
pi_c <- colMeans(s_ik)
alpha_c <- alpha_calculation(s_ik = s_ik, t_jg = t_jg, nu_j = nu_j, mu_i = mu_i,
K = K, G = G, x = x, exp_utilde = exp_utilde)
if (akg == FALSE) {
qu_param <- qu_calculation(s_ik = s_ik, t_jg = t_jg, x = x, mu_i = mu_i,
nu_j = nu_j, alpha_c = alpha_c, a = a0)
} else {
qu_param <- qukg_calculation(s_ik = s_ik, t_jg = t_jg, x = x, mu_i = mu_i,
nu_j = nu_j, alpha_c = alpha_c, a = a0)
}
exp_utilde <- qu_param$exp_utilde
exp_logutilde <- qu_param$exp_logutilde
crit_em1 <- sum((sort(alpha_c) - sort(alpha_old1))^2)
+ sum((sort(pi_c) - sort(pi_old))^2)
}
i <- 0
crit_em2 <- 1
while(crit_em2 > cvg_lim)
{
i = i + 1
rho_old <- rho_c
alpha_old2 <- alpha_c
t_old <- t_jg
if (is.matrix(nu_j)){
t_jg_tmp <- sapply(1:G, FUN = function(l) log(rho_c[l]) +
rowSums(sapply(1:nrow(x), FUN = function(i)
rowSums(sapply(1:K, FUN = function(k) s_ik[i, k] * x[i,]
* (log(alpha_c[k, l]) + exp_logutilde[i, ])
- s_ik[i, k] * mu_i[i] * nu_j[i,] * alpha_c[k, l]
* exp_utilde[i, ])))))
} else {
t_jg_tmp <- sapply(1:G, FUN = function(l) log(rho_c[l]) +
rowSums(sapply(1:nrow(x), FUN = function(i)
rowSums(sapply(1:K, FUN = function(k) s_ik[i, k] * x[i,]
* (log(alpha_c[k, l]) + exp_logutilde[i, ])
- s_ik[i, k] * mu_i[i] * nu_j * alpha_c[k, l]
* exp_utilde[i, ])))))
}
t_jg_tmp2 <-t_jg_tmp - rowMeans(t_jg_tmp)
t_jg <- apply(t_jg_tmp2, 2, FUN = function(x) exp(x) / rowSums(exp(t_jg_tmp2)))
if (sum(is.nan(t_jg)) > 0) {
rmax <- apply(t_jg_tmp, 1, max)
t_jg_tmp3 <- t_jg_tmp - rmax
t_jg <- apply(t_jg_tmp3, 2, FUN = function(x) exp(x) / rowSums(exp(t_jg_tmp3)))
}
t_jg <- apply(t_jg, c(1, 2), FUN = function(x) if (x <= 0.5) max(tol, x)
else if (x > 0.5) min(x, 1 - tol))
t_jg[t_jg == tol] <- (tol) / (ncol(t_jg) - 1)
t_jg <- t_jg / rowSums(t_jg)
rho_c <- colMeans(t_jg)
alpha_c <- alpha_calculation(s_ik = s_ik, t_jg = t_jg, nu_j = nu_j, mu_i = mu_i,
K = K, G = G, x = x, exp_utilde = exp_utilde)
if (akg == FALSE) {
qu_param <- qu_calculation(s_ik = s_ik, t_jg = t_jg, x = x, mu_i = mu_i, nu_j = nu_j, alpha_c = alpha_c, a = a0)
} else {
qu_param <- qukg_calculation(s_ik = s_ik, t_jg = t_jg, x = x, mu_i = mu_i,
nu_j = nu_j, alpha_c = alpha_c, a = a0)
}
exp_utilde <- qu_param$exp_utilde
exp_logutilde <- qu_param$exp_logutilde
crit_em2 <- sum((sort(rho_c) - sort(rho_old))^2)
+ sum((sort(alpha_c) - sort(alpha_old2))^2)
}
if (is.matrix(nu_j)) {
mu_i <- rowSums(x %*% t_jg) /
rowSums(s_ik * (nu_j %*% tcrossprod (t_jg, alpha_c) ) )
} else {
mu_i <- rowSums(x %*% t_jg) /
rowSums(s_ik * rowSums(matrix(nrow = K,
sapply(1:G, FUN = function(l) alpha_c[, l] *
colSums(t_jg * nu_j)[l]))))
}
lb_old <- lb
a_old <- a0
if (is.null(a)){
if (akg == FALSE){
left_bound = sum(exp_logutilde)
right_bound = sum(exp_utilde)
a0 <- dicho(x = 0.01, y = abs(max(left_bound, right_bound)), threshold = 1e-08,
nb = n * m, left_bound = left_bound, right_bound = right_bound)
} else {
left_bound = crossprod(s_ik, exp_logutilde %*% t_jg)
right_bound = crossprod(s_ik, exp_utilde %*% t_jg)
n_kg <- crossprod(s_ik, matrix(nrow = n, ncol = m, 1) %*% t_jg)
a0 <- matrix(nrow = K, ncol = G, sapply(1:(K*G),
FUN = function(g) dicho(x = 0.01, y = 100, threshold = 1e-08, nb = n_kg[g], left_bound = left_bound[g], right_bound = right_bound[g])))
}
}
if (akg == FALSE) {
qu_param <- qu_calculation(s_ik = s_ik, t_jg = t_jg, x = x,
mu_i = mu_i, nu_j = nu_j, alpha_c = alpha_c, a = a0)
} else {
qu_param <- qukg_calculation(s_ik = s_ik, t_jg = t_jg, x = x, mu_i = mu_i,
nu_j = nu_j, alpha_c = alpha_c, a = a0)
}
alpha_c <- alpha_calculation(s_ik = s_ik, t_jg = t_jg, nu_j = nu_j, mu_i = mu_i,
K = K, G = G, x = x, exp_utilde = qu_param$exp_utilde)
lb_out <- lb_calculation(x = x, qu_param = qu_param, s_ik = s_ik, pi_c = pi_c,
t_jg = t_jg, rho_c = rho_c, mu_i = mu_i,
nu_j = nu_j, alpha_c = alpha_c, a = a0, akg = akg)
lb <- lb_out$lb
if (j > 1){
crit <- abs((lb - lb_old) / lb_old)
}
lbtt <- c(lbtt, lb)
}
colclass <- apply(t_jg, 1, which.max)
rowclass <- apply(s_ik, 1, which.max)
strategy <- list(akg = akg, cvg_lim = cvg_lim)
parameters <- list(alpha = alpha_c, pi = pi_c, rho = rho_c, mu_i = mu_i, nu_j = nu_j, a = a0)
info <- list(s_ik = s_ik, t_jg = t_jg, exp_logutilde = qu_param$exp_logutilde, exp_utilde = qu_param$exp_utilde,
lb = lb, ent_ZW = lb_out$ent_ZW, nbiter = j, lbtt = lbtt, a_tilde = qu_param$a_tilde, b_tilde = qu_param$b_tilde)
output <- list(data = x, K = K, G = G, classification = list(rowclass = rowclass, colclass = colclass),
strategy = strategy, parameters = parameters, info = info)
class(output) <- append(class(output),"cobiclustering")
return(output)
} |
NULL
setGeneric('get_indicators', function(inputs, outputs, ...)
standardGeneric('get_indicators'))
setMethod('get_indicators', signature(inputs="LeMans_param", outputs='LeMans_outputs'),
function(inputs, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], prob=0.5, length_LFI=40) {
return(get_indicators(wgt=inputs@wgt, mid=inputs@mid, l_bound=inputs@l_bound, u_bound=inputs@u_bound, Linf=inputs@Linf, N=outputs@N, species=species, time_steps=time_steps, species_names=inputs@species_names, prob=prob, length_LFI=length_LFI))
})
setMethod('get_indicators', signature(inputs="LeMans_param", outputs='missing'),
function(inputs, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], prob=0.5, length_LFI=40) {
return(get_indicators(wgt=inputs@wgt, mid=inputs@mid, l_bound=inputs@l_bound, u_bound=inputs@u_bound, Linf=inputs@Linf, N=N, species=species, time_steps=time_steps, species_names=inputs@species_names, prob=prob, length_LFI=length_LFI))
})
setMethod('get_indicators', signature(inputs="missing", outputs='LeMans_outputs'),
function(wgt, mid, l_bound, u_bound, Linf, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], species_names=NULL, prob=0.5, length_LFI=40) {
return(get_indicators(wgt=wgt, mid=mid, l_bound=l_bound, u_bound=u_bound, Linf=Linf, N=outputs@N, species=species, time_steps=time_steps, species_names=species_names, prob=prob, length_LFI=length_LFI))
})
setMethod('get_indicators', signature(inputs="missing", outputs='missing'),
function(wgt, mid, l_bound, u_bound, Linf, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], species_names=NULL, prob=0.5, length_LFI=40) {
ret <- list()
ret[["LFI"]] <- get_LFI(wgt=wgt, l_bound=l_bound, u_bound=u_bound, N=N, species=species, time_steps=time_steps, species_names=species_names, length_LFI=length_LFI)
ret[["MML"]] <- get_MML(wgt=wgt, Linf=Linf, N=N, species=species, time_steps=time_steps, species_names=species_names)
ret[["TYL"]] <- get_TyL(wgt=wgt, mid=mid, N=N, species=species, time_steps=time_steps, species_names=species_names)
ret[["LQ"]] <- get_LQ(wgt=wgt, u_bound=u_bound, N=N, species=species, time_steps=time_steps, species_names=species_names, prob=prob)
return(ret)
})
setGeneric('get_LFI', function(inputs, outputs, ...)
standardGeneric('get_LFI'))
setMethod('get_LFI', signature(inputs="LeMans_param", outputs='LeMans_outputs'),
function(inputs, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], length_LFI=40) {
return(get_LFI(wgt=inputs@wgt, l_bound=inputs@l_bound, u_bound=inputs@u_bound, N=outputs@N,species=species, time_steps=time_steps, species_names=inputs@species_names, length_LFI=length_LFI))
})
setMethod('get_LFI', signature(inputs="LeMans_param", outputs='missing'),
function(inputs, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], length_LFI=40) {
return(get_LFI(wgt=inputs@wgt, l_bound=inputs@l_bound, u_bound=inputs@u_bound, N=N, species=species, time_steps=time_steps, species_names=inputs@species_names, length_LFI=length_LFI))
})
setMethod('get_LFI', signature(inputs="missing", outputs='LeMans_outputs'),
function(wgt, l_bound, u_bound, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], species_names=NULL, length_LFI=40) {
return(get_LFI(wgt=wgt, l_bound=l_bound, u_bound=u_bound, N=outputs@N, species=species, time_steps=time_steps, species_names=species_names, length_LFI=length_LFI))
})
setMethod('get_LFI', signature(inputs="missing", outputs='missing'),
function(wgt, l_bound, u_bound, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], species_names=NULL, length_LFI=40) {
if (length(length_LFI)>1){
return(sapply(length_LFI, function(wgt, l_bound, u_bound, N, species, time_steps, species_names, length_LFI){
get_LFI(wgt=wgt, l_bound=l_bound, u_bound=u_bound, N=N, species=species, time_steps=time_steps, species_names=species_names, length_LFI=length_LFI)},
wgt=wgt, l_bound=l_bound, u_bound=u_bound, N=N, species=species, time_steps=time_steps, species_names=species_names))
}
if (is.character(species)){
species <- sapply(species, function(species){which(species==species_names)})
}
bry <- which(l_bound<=length_LFI & u_bound>length_LFI)
prop <- (length_LFI-l_bound[bry])/(u_bound[bry]-l_bound[bry])
if (length(time_steps)>1){
new_n <- N[, species, time_steps]
return(apply(new_n, length(dim(new_n)), calc_LFI, wgt=wgt[,species], bry=bry, prop=prop))
}
new_n <- N[, species, time_steps]
return(calc_LFI(new_n, wgt=wgt[, species], bry=bry, prop=prop))
})
setGeneric('get_MML', function(inputs, outputs, ...)
standardGeneric('get_MML'))
setMethod('get_MML', signature(inputs="LeMans_param", outputs='LeMans_outputs'),
function(inputs,outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3]) {
return(get_MML(wgt=inputs@wgt, Linf=inputs@Linf, N=outputs@N, species=species, time_steps=time_steps, species_names=inputs@species_names))
})
setMethod('get_MML', signature(inputs="LeMans_param", outputs='missing'),
function(inputs,N, species=1:dim(N)[2], time_steps=1:dim(N)[3]) {
return(get_MML(wgt=inputs@wgt, Linf=inputs@Linf, N=N, species=species, time_steps=time_steps, species_names=inputs@species_names))
})
setMethod('get_MML', signature(inputs="missing", outputs='LeMans_outputs'),
function(wgt, Linf, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], species_names=NULL) {
return(get_MML(wgt=wgt, Linf=Linf, N=outputs@N, species=species, time_steps=time_steps, species_names=species_names))
})
setMethod('get_MML', signature(inputs="missing", outputs='missing'),
function(wgt, Linf, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], species_names=NULL) {
if (is.character(species)){
species <- sapply(species, function(species){which(species==species_names)})
}
if (length(species)==1){
return(rep(Linf[species], length(time_steps)))
}
if (length(time_steps)>1){
new_n <- N[, species, time_steps]
biomass <- apply(new_n, length(dim(new_n)), calc_biomass, wgt=wgt[, species])
return(apply(biomass, 2, weighted.mean, x=Linf[species]))
}
new_n <- N[, species, time_steps]
return(weighted.mean(Linf[species], w=calc_biomass(new_n, wgt=wgt[, species])))
})
setGeneric('get_TyL', function(inputs, outputs, ...)
standardGeneric('get_TyL'))
setMethod('get_TyL', signature(inputs="LeMans_param", outputs='LeMans_outputs'),
function(inputs, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3]) {
return(get_TyL(wgt=inputs@wgt, mid=inputs@mid, N=outputs@N, species=species, time_steps=time_steps, species_names=inputs@species_names))
})
setMethod('get_TyL', signature(inputs="LeMans_param", outputs='missing'),
function(inputs, N, species=1:dim(N)[2], time_steps=1:dim(N)[3]) {
return(get_TyL(wgt=inputs@wgt, mid=inputs@mid, N=N, species=species, time_steps=time_steps, species_names=inputs@species_names))
})
setMethod('get_TyL', signature(inputs="missing", outputs='LeMans_outputs'),
function(wgt, mid, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], species_names=NULL) {
return(get_TyL(wgt=wgt, mid=mid, N=outputs@N, species=species, time_steps=time_steps, species_names=species_names))
})
setMethod('get_TyL', signature(inputs="missing", outputs='missing'),
function(wgt, mid, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], species_names=NULL) {
if(is.character(species)){
species <- sapply(species, function(species){which(species==species_names)})
}
if (length(time_steps)>1){
new_n <- N[, species, time_steps]
return(apply(new_n, length(dim(new_n)), calc_TyL, wgt=wgt[, species], mid=mid))
}
new_n <- N[, species, time_steps]
return(calc_TyL(new_n, wgt=wgt[, species], mid=mid))
})
setGeneric('get_LQ', function(inputs, outputs, ...)
standardGeneric('get_LQ'))
setMethod('get_LQ', signature(inputs="LeMans_param", outputs='LeMans_outputs'),
function(inputs, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], prob=0.5) {
return(get_LQ(wgt=inputs@wgt, u_bound=inputs@u_bound, N=outputs@N, species=species, time_steps=time_steps, species_names=inputs@species_names, prob=prob))
})
setMethod('get_LQ', signature(inputs="LeMans_param", outputs='missing'),
function(inputs, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], prob=0.5) {
return(get_LQ(wgt=inputs@wgt, u_bound=inputs@u_bound, N=N, species=species, time_steps=time_steps, species_names=inputs@species_names, prob=prob))
})
setMethod('get_LQ', signature(inputs="missing", outputs='LeMans_outputs'),
function(wgt, u_bound, outputs, species=1:dim(outputs@N)[2], time_steps=1:dim(outputs@N)[3], species_names=NULL, prob=0.5) {
return(get_LQ(wgt=wgt, u_bound=u_bound, N=outputs@N, species=species, time_steps=time_steps, species_names=species_names, prob=prob))
})
setMethod('get_LQ', signature(inputs="missing", outputs='missing'),
function(wgt, u_bound, N, species=1:dim(N)[2], time_steps=1:dim(N)[3], species_names=NULL, prob=0.5) {
if (length(prob)>1){
return(sapply(prob, function(wgt, u_bound, N, species, time_steps, species_names, prob)
get_LQ(wgt=wgt, u_bound=u_bound, N=N, species=species, time_steps=time_steps, species_names=species_names, prob=prob),
wgt=wgt, u_bound=u_bound, N=N, species=species, time_steps=time_steps, species_names=species_names))
}
if (is.character(species)){
species <- sapply(species, function(species){which(species==species_names)})
}
if (length(time_steps)>1){
new_n <- N[,species,time_steps]
return(apply(new_n, length(dim(new_n)), calc_LQ, wgt=wgt[, species], u_bound=u_bound, prob=prob))
}
new_n <- N[,species,time_steps]
return(calc_LQ(new_n, wgt=wgt[,species], u_bound=u_bound, prob=prob))
}) |
linapprox <- function(xyin, xout)
{
x <- sort(unique(c(0, xyin[, 1])))
y <- as.vector(tapply(c(0, xyin[, 2]), c(0, xyin[, 1]), max))
n <- length(x)
xmax <- max(xout)
if (max(x) < xmax) {
x <- c(x, xmax)
y <- c(y, y[n-1] + (xmax - x[n-1])/(x[n] - x[n-1]) * (y[n] - y[n-1]))
}
approx(x, y, xout)$y
} |
dim.trackdata <- function(x)
{
c(nrow(x$index), ncol(x$data))
}
"dimnames.trackdata" <- function(x)
{
trackdata = x
dimnames(trackdata$data)
} |
emoji_p <- function(x,
names = c("laughing", "joy", "grin",
"smile", "thinking", "poop"),
cutpoints = c(1e-5, 0.001, 0.01, 0.05, 0.1),
legend = FALSE) {
stopifnot(is.numeric(x))
if (length(names) != (length(cutpoints) + 1)) {
stop("`names` and `cutpoints` must be the same length.")
}
cutpoints <- c(0, cutpoints, 1)
symbols <- vapply(names, emoji, character(1), USE.NAMES = FALSE)
if (legend) {
res <- stats::symnum(
x,
corr = FALSE,
na = FALSE,
cutpoints = cutpoints,
symbols = symbols
)
} else {
res <- symbols[as.numeric(cut(x, cutpoints))]
}
res
} |
add_variable.abstract_model <- function(.model, .variable, ...,
type = "continuous",
lb = -Inf, ub = Inf) {
add_variable_(
.model = .model,
.variable = lazyeval::as.lazy(
substitute(.variable), parent.frame()
),
type = type,
lb = lb,
ub = ub,
.dots = lazyeval::lazy_dots(...)
)
}
set_objective.abstract_model <- function(model, expression,
sense = c("max", "min")) {
set_objective_(model,
expression = lazyeval::as.lazy(
substitute(expression),
parent.frame()
),
sense = sense
)
}
add_constraint.abstract_model <- function(.model, .constraint_expr, ...,
.show_progress_bar = TRUE) {
add_constraint_(.model, lazyeval::as.lazy(
substitute(.constraint_expr),
parent.frame()
),
.dots = lazyeval::lazy_dots(...),
.show_progress_bar = .show_progress_bar
)
}
set_bounds.abstract_model <- function(.model, .variable, ...,
lb = NULL, ub = NULL) {
set_bounds_(
.model = .model,
.variable = lazyeval::as.lazy(
substitute(.variable), parent.frame()
),
lb = lb,
ub = ub,
.dots = lazyeval::lazy_dots(...)
)
}
solve_model.abstract_model <- function(model, solver) {
if (!is.function(solver)) {
stop(paste0(
"Solver is not a function Model -> Solution.\n",
"Take a look at the examples on the website on how to call",
" solve_model."
))
}
solver(model)
} |
setMethod('t', signature(x='RasterLayer'),
function(x) {
r <- raster(x)
e <- eold <- extent(r)
e@xmin <- eold@ymin
e@xmax <- eold@ymax
e@ymin <- eold@xmin
e@ymax <- eold@xmax
extent(r) <- e
dim(r) <- c(ncol(x), nrow(x))
if (! hasValues(x)) {
return(r)
}
if (canProcessInMemory(x)) {
return(setValues(r, t(as.matrix(x))))
} else {
tr <- blockSize(r)
pb <- pbCreate(tr$n)
r <- writeStart(r, filename=rasterTmpFile(), overwrite=TRUE )
for (i in 1:tr$n) {
v <- getValuesBlock(x, row=1, nrows=r@ncols, col=tr$row[i], ncols=tr$nrows[i])
v <- as.vector(matrix(v, ncol=tr$nrows[i], byrow=TRUE))
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
r <- writeStop(r)
pbClose(pb)
return(r)
}
}
)
setMethod('t', signature(x='RasterStackBrick'),
function(x) {
b <- brick(x, values=FALSE)
e <- eold <- extent(b)
e@xmin <- eold@ymin
e@xmax <- eold@ymax
e@ymin <- eold@xmin
e@ymax <- eold@xmax
extent(b) <- e
dim(b) <- c(ncol(b), nrow(b), nlayers(b))
if (! hasValues(x)) {
return(b)
}
if (canProcessInMemory(x)) {
x <- as.array(x, transpose=TRUE)
return( brick(x, xmn=xmin(b), xmx=xmax(b), ymn=ymin(b), ymx=ymax(b), crs=projection(b)) )
} else {
tr <- blockSize(b)
pb <- pbCreate(tr$n)
b <- writeStart(b, filename=rasterTmpFile(), overwrite=TRUE )
for (i in 1:tr$n) {
v <- getValuesBlock(x, row=1, nrows=b@ncols, col=tr$row[i], ncols=tr$nrows[i])
for (j in 1:ncol(v)) {
v[,j] <- as.vector(matrix(v[,j], ncol=tr$nrows[i], byrow=TRUE))
}
b <- writeValues(b, v, tr$row[i])
pbStep(pb, i)
}
b <- writeStop(b)
pbClose(pb)
return(b)
}
}
) |
context("test-update_node.R")
dkanr_setup(url = 'https://newdatacatalogstg.worldbank.org/')
meta <- list()
meta$title <- jsonlite::unbox("NEW title")
meta <- jsonlite::toJSON(meta, pretty = TRUE)
node_id <- 126571
httptest::with_mock_api({
test_that("Node is correctly created and returned", {
resp <- update_node(nid = node_id, body = meta, as = "json")
expect_is(resp, "character")
resp <- update_node(nid = node_id, body = meta, as = "list")
expect_true(is.list(resp))
})
test_that("JSON is returned by default", {
resp <- update_node(nid = node_id, body = meta)
expect_is(resp, "character")
})
}) |
if(nzchar(Sys.getenv('NOT_CRAN')))
stopifnot(grepl('tests', basename(getwd())), exists("NAME"))
rdsf <-
function(x) readRDS(file.path("_helper", "objs", NAME, sprintf("%s.rds", x)))
txtf <-
function(x) readLines(file.path("_helper", "objs", NAME, sprintf("%s.txt", x)))
srdsf <- function(x, i)
saveRDS(x, file.path("_helper", "objs", NAME, sprintf("%s.rds", i)), version=2)
stxtf <- function(x, i)
writeLines(x, file.path("_helper", "objs", NAME, sprintf("%s.txt", i)))
library(diffobj)
all.opts <- c(
list(
useFancyQuotes=FALSE,
diffobj.format="ansi8",
diffobj.color.mode="yb",
diffobj.pager="off",
width=80L,
encoding="UTF-8",
warnPartialMatchArgs=TRUE,
warnPartialMatchAttr=TRUE,
warnPartialMatchDollar=TRUE
)
)
options(c(diffobj_set_def_opts(), all.opts))
if(R.version$major >= 4 || R.version$major >= 3 && R.version$minor >= "5.0")
suppressWarnings(RNGversion("3.5.2"));
source("_helper/commonobjects.R") |
mcmcplot <- function(mcmcout, parms=NULL, regex=NULL, random=NULL, leaf.marker="[\\[_]", dir=tempdir(), filename="MCMCoutput", extension="html", title=NULL, heading=title, col=NULL, lty=1, xlim=NULL, ylim=NULL, style=c("gray", "plain"), greek=FALSE){
if (is.null(title))
title <- paste("MCMC Plots: ", deparse(substitute(mcmcout)), sep="")
if (is.null(heading))
heading <- title
style <- match.arg(style)
current.devices <- dev.list()
on.exit( sapply(dev.list(), function(dev) if(!(dev %in% current.devices)) dev.off(dev)) )
mcmcout <- convert.mcmc.list(mcmcout)
nchains <- length(mcmcout)
if (is.null(col)){
col <- mcmcplotsPalette(nchains)
}
css.file <- system.file("MCMCoutput.css", package="mcmcplots")
css.file <- paste("file:///", css.file, sep="")
htmlfile <- .html.begin(dir, filename, extension, title=title, cssfile=css.file)
if (is.null(varnames(mcmcout))){
warning("Argument 'mcmcout' did not have valid variable names, so names have been created for you.")
varnames(mcmcout) <- varnames(mcmcout, allow.null=FALSE)
}
parnames <- parms2plot(varnames(mcmcout), parms, regex, random, leaf.marker, do.unlist=FALSE)
if (length(parnames)==0)
stop("No parameters matched arguments 'parms' or 'regex'.")
np <- length(unlist(parnames))
cat('\n<div id="outer">\n', file=htmlfile, append=TRUE)
cat('<h1>', heading, '</h1>', sep="", file=htmlfile, append=TRUE)
cat('<div id="toc">\n', file=htmlfile, append=TRUE)
cat('\n<h2>Table of Contents</h2>', file=htmlfile, append=TRUE)
cat('<ul id="toc_items">\n', file=htmlfile, append=TRUE)
for (group.name in names(parnames)) {
cat(sprintf('<li class="toc_item"><a href="
}
cat('</ul></div>\n', file=htmlfile, append=TRUE)
cat('<div class="main">\n', file=htmlfile, append=TRUE)
htmlwidth <- 640
htmlheight <- 480
for (group.name in names(parnames)) {
cat(sprintf('<h2><a name="%s">Plots for %s</a></h2>\n', group.name, group.name), file=htmlfile, append=TRUE)
for (p in parnames[[group.name]]) {
pctdone <- round(100*match(p, unlist(parnames))/np)
cat("\r", rep(" ", getOption("width")), sep="")
cat("\rPreparing plots for ", group.name, ". ", pctdone, "% complete.", sep="")
gname <- paste(p, ".png", sep="")
png(file.path(dir, gname), width=htmlwidth, height=htmlheight)
plot_err <- tryCatch({
mcmcplot1(mcmcout[, p, drop=FALSE], col=col, lty=lty, xlim=xlim, ylim=ylim, style=style, greek=greek)
}, error=function(e) {e})
dev.off()
if (inherits(plot_err, "error")) {
cat(sprintf('<p class="plot_err">%s. %s</p>', p, plot_err),
file=htmlfile, append=TRUE)
} else {
.html.img(file=htmlfile, class="mcmcplot", src=gname,
width=htmlwidth, height=htmlheight)
}
}
}
cat("\r", rep(" ", getOption("width")), "\r", sep="")
cat('\n</div>\n</div>\n', file=htmlfile, append=TRUE)
.html.end(htmlfile)
full.name.path <- paste("file://", htmlfile, sep="")
browseURL(full.name.path)
invisible(full.name.path)
} |
fn_df_nlevels <- function(d){
sapply(names(d), FUN = function(x)nlevels(d[,x]))
}
fn_df_discretize <- function(d, cols = 1:NCOL(d)){
for (i in cols){
d[,i] <- factor(d[,i])
}
return(d)
}
fn_df_levels <- function(d, cols = 1:NCOL(d)){
res <- list()
for (i in cols){
res[[names(d)[i]]] <- levels(d[1,i])
}
return(res)
}
fn_numeric_to_factor <- function(
x, list_levls = rep(list(1:2), NCOL(x)), cols = 1:NCOL(x), missing = -1, offset = 0){
x <- as.data.frame(x)
for (c in cols){
lv <- list_levls[[c]]
nlv <- length(lv)
x[,c] <- factor(x[,c], levels = 1:nlv + offset)
levels(x[,c]) <- lv
}
return(x)
}
fn_apply_levels_from <- function(dest, from, cols = 1:NCOL(from)){
dest <- as.data.frame(dest)
lev <- sapply(cols, function(x)levels(from[1,x]), simplify=FALSE)
for (i in cols){
dest[,i] <- factor(dest[,i], levels = lev[[i]])
}
names(dest[,cols]) <- names(from[,cols])
return(dest)
}
fn_dataframe2num_matrix <- function(d, offset = -1, missing = -1, C_style= FALSE){
offset <- as.integer(offset); missing <- as.integer(missing)
r <- data.matrix(d) + offset
r[is.na(r)] <- missing
if(C_style){
r <- t(r)
}
class(r) <- c('matrix', 'DMVmatrix')
attr(r, 'levels') <- fn_df_levels(d)
attr(r, 'na.code') <- missing
attr(r, 'offset') <- offset
attr(r, 'C_style') <- C_style
return(r)
}
fn_df_2_C_Data <- function(df, prefix = 'array', filename = 'console'){
breakdown <- fn_dataframe2num_matrix(df, offset = -1, missing=-1, C_style=T)
n <- NROW(df)
J <- NCOL(df)
l1 <- paste('int ',prefix,'_data_raw[]= {', paste(breakdown, collapse=', '), '};\n', sep='')
l2 <- paste('int ', prefix,'_levels[]= {', paste(fn_df_nlevels(df), collapse=', '), '};\n', sep ='')
l3 <- paste('int ',prefix, '_n_glob = ', n,';\n', 'int ', prefix,'_J_glob=', J,';\n', sep='')
if(filename != 'console'){
fl = file(description = filename, open = 'w')
writeLines(strwrap(paste(l1, l2, l3, sep ='\n')), con = fl)
close(fl)
} else {
writeLines(strwrap(paste(l1, l2, l3, sep ='\n')))
}
} |
options(Encoding="UTF-8")
knitr::opts_chunk$set(
fig.width = 8,
fig.height = 5,
collapse = TRUE,
comment = "
)
library(segclust2d)
data(simulshift)
library(ggplot2)
tmpdf <- simulshift[seq(1,30000, by = 100),]
tmpdf$class <- factor(rep(c(1,2,3), each = 102)[1:300])
ggplot(tmpdf)+
geom_path(aes(x = x, y = y))+
geom_point(aes(x= x, y = y, col = factor(class)))+
scale_color_discrete("home-range")+
theme(legend.position= "top")
data(simulmode)
simulmode$abs_spatial_angle <- abs(simulmode$spatial_angle)
simulmode <- simulmode[!is.na(simulmode$abs_spatial_angle), ]
library(ggplot2)
tmpdf <- simulmode
tmpdf$class <- factor(rep(c(1,2,3), each = 20, 5))
ggplot(tmpdf)+
geom_path(aes(x = x, y = y))+
geom_point(aes(x= x, y = y, col = factor(class)))+
scale_color_discrete("behavioural mode")+
theme(legend.position= "top")
cli::cli_alert_danger("Argument {cli::col_red('type')} \\
is deprecated and should not be used")
cli::cli_alert_danger("Argument {cli::col_red('coord.names')} \\
is deprecated and should not be used")
coord.names <- c("x","y")
cli::cli_alert("Please use instead \\
{.field seg.var = {deparse(coord.names)}} and \\
{.field scale.variable = FALSE}")
shift_seg <- segmentation(simulshift,
lmin = 240, Kmax = 25,
subsample_by = 60)
Kmax = 25
cli::cli_alert_warning(
"Adjusting Kmax so that lmin*Kmax < nrow(x). Now, \\
{cli::col_yellow('Kmax = ', Kmax)}")
cli::cli_alert_danger(
"lmin*Kmax > nrow(x) and Kmax cannot be adjusted. \\
Please provide lower values for lmin")
stop("lmin*Kmax > nrow(x)")
cli::cli_alert_success("Best segmentation estimated with \\
{shift_seg$Kopt.lavielle} segments, \\
according to Lavielle's criterium")
cli::cli_text(cli::col_grey(
'Other number of segments may be selected
by looking for likelihood breaks with plot_likelihood()'))
cli::cli_text(cli::col_grey(
'Results of the segmentation may be explored with plot() and segmap()'))
plot_likelihood(shift_seg)
mode_seg <- segmentation(simulmode,
lmin = 10, Kmax = 20,
seg.var = c("speed","abs_spatial_angle"),
scale.variable = TRUE)
plot_likelihood(mode_seg)
mode_segclust <- segclust(simulmode,
Kmax = 20, lmin=10,
ncluster = c(2,3),
seg.var = c("speed","abs_spatial_angle"))
cli::cli_alert_success(
"Best segmentation/clustering estimated with \\
{mode_segclust$ncluster.BIC} clusters and \\
{mode_segclust$Kopt.BIC[mode_segclust$ncluster.BIC]} segments according to BIC")
cli::cli_text(cli::col_grey(
'{cli::symbol$arrow_right} Number of clusters should preferentially be selected
according to biological knowledge. Exploring the BIC plot with plot_BIC()
can also provide advice to select the number of clusters.'))
cli::cli_text(cli::col_grey(
'{cli::symbol$arrow_right} Once number of clusters is selected, \\
the number of segments can be selected according to BIC.'))
cli::cli_text(cli::col_grey(
'{cli::symbol$arrow_right} Results of the segmentation/clustering
may further be explored with plot() and segmap()'))
plot_BIC(mode_segclust)
mode_segclust <- segclust(simulmode,
Kmax = 20, lmin=10,
ncluster = 2:5,
seg.var = c("speed","abs_spatial_angle"),
scale.variable = TRUE)
plot_BIC(mode_segclust)
plot(mode_segclust, ncluster = 3)
plot(mode_segclust, ncluster = 4) |
test_that("system v semaphores work", {
skip_on_os("windows")
sid <- semv_open(1)
semv_wait(sid)
semv_post(sid)
semv_wait(sid)
semv_unlink(sid)
expect_error(semv_wait(sid))
expect_error(semv_post(sid))
expect_error(semv_unlink(sid))
expect_error(semv_open(-1))
})
test_that("undo works for system v semaphores", {
skip_on_os("windows")
sid <- semv_open(1)
job <- parallel::mcparallel({semv_wait(sid); semv_wait(sid); TRUE})
expect_null(parallel::mccollect(job, wait = FALSE, timeout = 1))
parallel:::mckill(job, signal = tools::SIGKILL)
semv_wait(sid)
semv_unlink(sid)
})
test_that("system v semaphores are interruptible", {
skip_on_os("windows")
sid <- semv_open(0)
ppid <- Sys.getpid()
job <- parallel::mcparallel({Sys.sleep(1); system(paste0("kill -", tools::SIGINT, " ", ppid))})
expect_true(tryCatch(semv_wait(sid), interrupt = function(i) TRUE))
expect_identical(parallel::mccollect(job)[[1]], 0L)
semv_unlink(sid)
}) |
if (getRversion() >= "2.15.1") utils::globalVariables(c("."))
factor_drop <- function(f) {
factor_levels <- levels(f)
factor(f, levels = setdiff(factor_levels, factor_levels[table(f) == 0]))
}
batchmean_simple <- function(data, markers) {
values <- data %>%
dplyr::select(.data$.id, .data$.batchvar, {{ markers }}) %>%
dplyr::group_by(.data$.batchvar) %>%
dplyr::summarize_at(
.vars = dplyr::vars(-.data$.id),
.funs = mean,
na.rm = TRUE
) %>%
dplyr::mutate_at(
.vars = dplyr::vars(-.data$.batchvar),
.funs = ~ . - mean(., na.rm = TRUE)
) %>%
tidyr::pivot_longer(
col = c(-.data$.batchvar),
names_to = "marker",
values_to = "batchmean"
)
return(list(list(values = values, models = NULL)))
}
batchmean_standardize <- function(data, markers, confounders) {
res <- data %>%
tidyr::pivot_longer(
cols = {{ markers }},
names_to = "marker",
values_to = "value"
) %>%
dplyr::filter(!is.na(.data$value)) %>%
dplyr::group_by(.data$marker) %>%
tidyr::nest(data = c(-.data$marker)) %>%
dplyr::mutate(
data = purrr::map(
.x = .data$data,
.f = ~ .x %>%
dplyr::mutate(.batchvar = factor_drop(.data$.batchvar))
),
model = purrr::map(
.x = .data$data,
.f = ~ stats::lm(
formula = stats::as.formula(paste0(
"value ~ .batchvar +",
paste(
confounders,
collapse = " + ",
sep = " + "
)
)),
data = .x
)
),
.batchvar = purrr::map(
.x = .data$data,
.f = ~ .x %>%
dplyr::pull(.data$.batchvar) %>%
levels()
)
)
values <- res %>%
tidyr::unnest(cols = .data$.batchvar) %>%
dplyr::mutate(
data = purrr::map2(
.x = .data$data,
.y = .data$.batchvar,
.f = ~ .x %>% dplyr::mutate(.batchvar = .y)
),
pred = purrr::map2(.x = .data$model, .y = .data$data, .f = stats::predict)
) %>%
dplyr::select(.data$marker, .data$.batchvar, .data$pred) %>%
tidyr::unnest(cols = .data$pred) %>%
dplyr::group_by(.data$marker, .data$.batchvar) %>%
dplyr::summarize(batchmean = mean(.data$pred, na.rm = TRUE)) %>%
dplyr::group_by(.data$marker) %>%
dplyr::mutate(markermean = mean(.data$batchmean)) %>%
dplyr::ungroup() %>%
dplyr::transmute(
marker = .data$marker,
.batchvar = .data$.batchvar,
batchmean = .data$batchmean - .data$markermean
)
return(list(list(
models = res %>% dplyr::ungroup() %>% dplyr::pull("model"),
values = values
)))
}
batchmean_ipw <- function(
data,
markers,
confounders,
truncate = c(0.025, 0.975)
) {
ipwbatch <- function(data, variable, confounders, truncate) {
data <- data %>%
dplyr::rename(variable = dplyr::one_of(variable)) %>%
dplyr::filter(!is.na(.data$variable)) %>%
dplyr::mutate(.batchvar = factor_drop(.data$.batchvar))
res <- data %>%
tidyr::nest(data = dplyr::everything()) %>%
dplyr::mutate(
num = purrr::map(
.x = .data$data,
.f = ~ nnet::multinom(
formula = .batchvar ~ 1,
data = .x,
trace = FALSE
)
),
den = purrr::map(
.x = .data$data,
.f = ~ nnet::multinom(
formula = stats::as.formula(
paste(".batchvar ~", confounders)
),
data = .x,
trace = FALSE
)
)
)
values <- res %>%
dplyr::mutate_at(
.vars = dplyr::vars(.data$num, .data$den),
.funs = ~ purrr::map(.x = ., .f = stats::predict, type = "probs") %>%
purrr::map(.x = ., .f = tibble::as_tibble) %>%
purrr::map2(
.x = .,
.y = .data$data,
.f = ~ .x %>%
dplyr::mutate(.batchvar = .y %>%
purrr::pluck(".batchvar"))
)
)
if (length(levels(factor(data$.batchvar))) == 2) {
values <- values %>%
dplyr::mutate_at(
.vars = dplyr::vars(.data$num, .data$den),
.funs = ~ purrr::map(.x = ., .f = ~ .x %>%
dplyr::mutate(
probs = dplyr::if_else(
.data$.batchvar ==
levels(factor(.data$.batchvar))[1],
true = 1 - .data$value,
false = .data$value
)
) %>%
dplyr::pull(.data$probs))
)
} else {
values <- values %>%
dplyr::mutate_at(
.vars = dplyr::vars(.data$num, .data$den),
.funs =
~ purrr::map(
.x = .,
.f = ~ .x %>%
tidyr::pivot_longer(
-.data$.batchvar,
names_to = "batch",
values_to = "prob"
) %>%
dplyr::filter(.data$batch == .data$.batchvar) %>%
dplyr::pull(.data$prob)
)
)
}
values <- values %>%
tidyr::unnest(cols = c(.data$data, .data$num, .data$den)) %>%
dplyr::mutate(
sw = .data$num / .data$den,
trunc = dplyr::case_when(
.data$sw < stats::quantile(.data$sw, truncate[1]) ~
stats::quantile(.data$sw, truncate[1]),
.data$sw > stats::quantile(.data$sw, truncate[2]) ~
stats::quantile(.data$sw, truncate[2]),
TRUE ~ .data$sw
)
)
xlev <- unique(data %>% dplyr::pull(.data$.batchvar))
values <- geepack::geeglm(
formula = variable ~ .batchvar,
data = values,
weights = values$trunc,
id = values$.id,
corstr = "independence"
) %>%
broom::tidy() %>%
dplyr::filter(!stringr::str_detect(
string = .data$term,
pattern = "(Intercept)"
)) %>%
dplyr::mutate(term = as.character(
stringr::str_remove_all(
string = .data$term,
pattern = ".batchvar"
)
)) %>%
dplyr::full_join(tibble::tibble(term = as.character(xlev)), by = "term") %>%
dplyr::mutate(
estimate = dplyr::if_else(
is.na(.data$estimate),
true = 0,
false = .data$estimate
),
estimate = .data$estimate - mean(.data$estimate),
marker = variable,
term = .data$term
) %>%
dplyr::arrange(.data$term) %>%
dplyr::select(.data$marker, .batchvar = .data$term, batchmean = .data$estimate)
list(values = values, models = res %>% dplyr::pull(.data$den))
}
purrr::map(
.x = data %>% dplyr::select({{ markers }}) %>% names(),
.f = ipwbatch,
data = data %>%
dplyr::filter(dplyr::across(dplyr::all_of(confounders), ~ !is.na(.x))),
truncate = truncate,
confounders = paste(confounders, sep = " + ", collapse = " + ")
)
}
batchrq <- function(data, variable, confounders, tau, rq_method) {
res <- data %>%
dplyr::rename(variable = {{ variable }}) %>%
dplyr::filter(!is.na(.data$variable)) %>%
dplyr::mutate(.batchvar = factor_drop(.data$.batchvar)) %>%
tidyr::nest(data = dplyr::everything()) %>%
dplyr::mutate(
un = purrr::map(
.x = .data$data,
.f = ~ quantreg::rq(
formula = variable ~ .batchvar,
data = .x,
tau = tau,
method = rq_method
)
),
ad = purrr::map(
.x = .data$data,
.f = ~ quantreg::rq(
formula = stats::reformulate(
response = "variable",
termlabels = c(".batchvar", confounders)
),
data = .x,
tau = tau,
method = rq_method
)
),
.batchvar = purrr::map(
.x = .data$data,
.f = ~ .x %>%
dplyr::pull(.data$.batchvar) %>%
levels()
)
)
values <- res %>%
tidyr::unnest(cols = .data$.batchvar) %>%
dplyr::mutate(
data = purrr::map2(
.x = .data$data,
.y = .data$.batchvar,
.f = ~ .x %>% dplyr::mutate(.batchvar = .y)
),
un = purrr::map2(.x = .data$un, .y = .data$data, .f = stats::predict),
ad = purrr::map2(.x = .data$ad, .y = .data$data, .f = stats::predict),
un = purrr::map(
.x = .data$un,
.f = tibble::as_tibble,
.name_repair = ~ c("un_lo", "un_hi")
),
ad = purrr::map(
.x = .data$ad,
.f = tibble::as_tibble,
.name_repair = ~ c("ad_lo", "ad_hi")
),
all_lo = purrr::map_dbl(
.x = .data$data,
.f = ~ stats::quantile(.x$variable, probs = 0.25)
),
all_hi = purrr::map_dbl(
.x = .data$data,
.f = ~ stats::quantile(.x$variable, probs = 0.75)
),
all_iq = .data$all_hi - .data$all_lo
) %>%
dplyr::select(
.data$.batchvar,
.data$un,
.data$ad,
.data$all_lo,
.data$all_hi,
.data$all_iq
) %>%
tidyr::unnest(cols = c(.data$un, .data$ad)) %>%
dplyr::group_by(.data$.batchvar) %>%
dplyr::summarize(
un_lo = stats::quantile(.data$un_lo, probs = 0.25),
ad_lo = stats::quantile(.data$ad_lo, probs = 0.25),
un_hi = stats::quantile(.data$un_hi, probs = 0.75),
ad_hi = stats::quantile(.data$ad_hi, probs = 0.75),
all_lo = stats::median(.data$all_lo),
all_iq = stats::median(.data$all_iq)
) %>%
dplyr::mutate(
un_iq = .data$un_hi - .data$un_lo,
ad_iq = .data$ad_hi - .data$ad_lo,
marker = {{ variable }}
)
models <- res %>% dplyr::pull(.data$ad)
return(tibble::lst(values, models))
}
batch_quantnorm <- function(var, batch) {
tibble::tibble(var, batch) %>%
tibble::rowid_to_column() %>%
tidyr::pivot_wider(names_from = batch, values_from = var) %>%
dplyr::select(-.data$rowid) %>%
dplyr::select_if(~ !all(is.na(.))) %>%
as.matrix() %>%
limma::normalizeQuantiles() %>%
tibble::as_tibble() %>%
dplyr::transmute(
result = purrr::pmap_dbl(
.l = .,
.f = function(...) {
mean(c(...), na.rm = TRUE)
}
),
result = dplyr::if_else(
is.nan(.data$result),
true = NA_real_,
false = .data$result
)
) %>%
dplyr::pull(.data$result)
}
adjust_batch <- function(
data,
markers,
batch,
method = c(
"simple",
"standardize",
"ipw",
"quantreg",
"quantnorm"
),
confounders = NULL,
suffix = "_adjX",
ipw_truncate = c(0.025, 0.975),
quantreg_tau = c(0.25, 0.75),
quantreg_method = "fn"
) {
method <- as.character(dplyr::enexpr(method))
allmethods <- c("simple", "standardize", "ipw", "quantreg", "quantnorm")
data_orig <- data %>%
dplyr::mutate(.id = dplyr::row_number())
data <- data_orig %>%
dplyr::rename(.batchvar = {{ batch }}) %>%
dplyr::mutate(
.batchvar = factor(.data$.batchvar),
.batchvar = factor_drop(.data$.batchvar)
) %>%
dplyr::select(.data$.id, .data$.batchvar, {{ markers }}, {{ confounders }})
confounders <- data %>%
dplyr::select({{ confounders }}) %>%
names()
if (!(method[1] %in% allmethods)) {
stop(paste0(
"Method '",
method[1],
"' is not implemented.\nAvailable methods: ",
paste(allmethods, collapse = ", "),
".\n",
"See: help(\"adjust_batch\")."
))
}
if (method %in% c("simple", "quantnorm") &
data %>%
dplyr::select({{ confounders }}) %>%
ncol() > 0) {
message(paste0(
"Batch effect correction via 'method = ",
method,
"' was requested.\n This method does not support ",
"adjustment for confounders (",
paste(dplyr::enexpr(confounders), sep = ", ", collapse = ", "),
"). They will be ignored."
))
data <- data %>% dplyr::select(-dplyr::any_of({{ confounders }}))
confounders <- NULL
}
if (method %in% c("simple", "standardize", "ipw")) {
if (method %in% c("standardize", "ipw") &
data %>%
dplyr::select({{ confounders }}) %>%
ncol() == 0) {
message(paste0(
"Batch effect correction via 'method = ",
method,
"' was requested,\nbut no valid confounders were provided. ",
"'method = simple' is used instead."
))
method <- "simple"
}
res <- switch(
method,
"simple" = batchmean_simple(data = data, markers = {{ markers }}),
"standardize" = batchmean_standardize(
data = data,
markers = {{ markers }},
confounders = {{ confounders }}
),
"ipw" = batchmean_ipw(
data = data,
markers = {{ markers }},
confounders = {{ confounders }},
truncate = ipw_truncate
)
)
adjust_parameters <- purrr::map_dfr(.x = res, .f = ~ purrr::pluck(.x, "values"))
method_indices <- c("simple" = 2, "standardize" = 3, "ipw" = 4)
if (suffix == "_adjX") {
suffix <- paste0("_adj", method_indices[method[1]])
}
values <- data %>%
dplyr::select(-dplyr::any_of({{ confounders }})) %>%
tidyr::pivot_longer(
cols = c(-.data$.id, -.data$.batchvar),
names_to = "marker",
values_to = "value"
) %>%
dplyr::left_join(adjust_parameters, by = c("marker", ".batchvar")) %>%
dplyr::mutate(
value_adjusted = .data$value - .data$batchmean,
marker = paste0(.data$marker, suffix)
) %>%
dplyr::select(-.data$batchmean, -.data$value)
}
if (method == "quantreg") {
res <- purrr::map(
.x = data %>% dplyr::select({{ markers }}) %>% names(),
.f = batchrq,
data = data %>%
dplyr::filter(dplyr::across(dplyr::all_of({{ confounders }}), ~ !is.na(.x))),
confounders = dplyr::if_else(
dplyr::enexpr(confounders) != "",
true = paste0(
"+ ",
paste(
dplyr::enexpr(confounders),
sep = " + ",
collapse = " + "
)
),
false = ""
),
tau = quantreg_tau,
rq_method = quantreg_method
)
adjust_parameters <- purrr::map_dfr(.x = res, .f = ~ purrr::pluck(.x, "values"))
if (suffix == "_adjX") {
suffix <- "_adj5"
}
values <- data %>%
tidyr::pivot_longer(
cols = c(
-.data$.id,
-.data$.batchvar,
-dplyr::any_of({{ confounders }})
),
names_to = "marker",
values_to = "value"
) %>%
dplyr::left_join(adjust_parameters, by = c("marker", ".batchvar")) %>%
dplyr::group_by(.data$marker) %>%
dplyr::mutate(
value_adjusted = (.data$value - .data$un_lo) /
.data$un_iq * .data$all_iq * (.data$un_iq / .data$ad_iq) +
.data$all_lo - .data$ad_lo + .data$un_lo,
marker = paste0(.data$marker, suffix)
) %>%
dplyr::select(
-dplyr::any_of({{ confounders }}),
-.data$value,
-.data$un_lo,
-.data$un_hi,
-.data$ad_lo,
-.data$ad_hi,
-.data$un_iq,
-.data$ad_iq,
-.data$all_iq,
-.data$all_lo
)
}
if (method == "quantnorm") {
if (suffix == "_adjX") {
suffix <- "_adj6"
}
values <- data %>%
dplyr::select(-dplyr::any_of({{ confounders }})) %>%
tidyr::pivot_longer(
cols = c(-.data$.id, -.data$.batchvar),
names_to = "marker",
values_to = "value"
) %>%
dplyr::mutate(marker = paste0(.data$marker, suffix)) %>%
dplyr::group_by(.data$marker) %>%
dplyr::mutate(value_adjusted = batch_quantnorm(
var = .data$value,
batch = .data$.batchvar
)) %>%
dplyr::ungroup() %>%
dplyr::select(-.data$value)
res <- list(list(res = NULL, models = NULL))
adjust_parameters <- tibble::tibble(marker = data %>%
dplyr::select({{ markers }}) %>% names())
}
values <- values %>%
tidyr::pivot_wider(
names_from = .data$marker,
values_from = .data$value_adjusted
) %>%
dplyr::select(-.data$.batchvar) %>%
dplyr::left_join(x = data_orig, by = ".id") %>%
dplyr::select(-.data$.id)
attr_list <- list(
adjust_method = method,
markers = data_orig %>% dplyr::select({{ markers }}) %>% names(),
suffix = suffix,
batchvar = data_orig %>% dplyr::select({{ batch }}) %>% names(),
confounders = dplyr::enexpr(confounders),
adjust_parameters = adjust_parameters,
model_fits = purrr::map(.x = res, .f = ~ purrr::pluck(.x, "models"))
)
class(attr_list) <- c("batchtma", class(res))
attr(values, which = ".batchtma") <- attr_list
return(values)
} |
retour_sn <- function(path){
n <- ncol(path)
res3 <- matrix(NA, nrow=nrow(path), ncol=nrow(path))
res3[1, 1] <- 0
for(i in 2: nrow(path)){
res3[i, i-1] <- path[i, n]
for(k in 1:(i-1)){
res3[i, i-1-k] <- path[i-k, res3[i, i-k]]
}
}
diag(res3) <- ncol(path)
return(res3)
}
Fpsn <- function(x, Kmax, mini=min(x), maxi=max(x)){
n <- length(x)
A <- .C("colibri_sn_R_c", signal=as.double(x), n=as.integer(n),
Kmax=as.integer(Kmax), min=as.double(mini),
max=as.double(maxi), path=integer(Kmax*n), cost=double(Kmax), allCost=double(n*Kmax)
, PACKAGE="jointseg")
A$path <- matrix(A$path, nrow=Kmax, byrow=TRUE)
A$allCost <- matrix(A$allCost, nrow=Kmax, byrow=TRUE)
A$t.est <- retour_sn(A$path)
A$K <- length(A$t.est)
A$J.est <- A$cost
return(A);
} |
PP3fastIX3 <-
function (Pvec, the.init, maxrow, k, maxcol, n, text)
{
avec <- Pvec[1:maxrow]
bvec <- Pvec[(maxrow+1):(2*maxrow)]
cvec <- Pvec[(2*maxrow+1):(3*maxrow)]
answer <- PP3ix3FromTU(the.init=the.init, avec=avec, bvec=bvec, cvec=cvec,
maxrow=maxrow, k=k, maxcol=maxcol, n=n, text=text)
return(answer)
} |
"barcode.panel" <- function(x, horizontal=TRUE, xlim=NULL, labelloc=TRUE, axisloc=TRUE,
labelouter=FALSE, nint=0, fontsize=9,
ptsize=unit(0.25, "char"), ptpch=1, bcspace=NULL,
xlab="", xlaboffset=unit(2.5, "lines"),
use.points=FALSE, buffer=0.02, log=FALSE) {
if (!is.list(x)) { stop("x must be a list") }
K <- length(x)
for (i in 1:K) x[[i]] <- x[[i]][!is.na(x[[i]])]
maxct <- 0
if (is.null(xlim)) {
minx <- min(unlist(x)) - buffer*(max(unlist(x))-min(unlist(x)))
maxx <- max(unlist(x)) + buffer*(max(unlist(x))-min(unlist(x)))
} else {
minx <- xlim[1]
maxx <- xlim[2]
}
xleftoffset <- unit(1, "strwidth", names(x)[1])
for (i in 1:K) {
y <- x[[i]]
if (length(y)>0) {
if (nint>0) z <- hist(y, breaks=pretty(unlist(x), n=nint), plot=FALSE)$counts
else z <- table(y)
maxct <- max(maxct, max(z))
xleftoffset <- max(xleftoffset, unit(1, "strwidth", names(x)[i]))
}
}
maxct <- maxct + 3
if (log) { maxct <- log(maxct) }
xleftoffset <- 1.05*xleftoffset
if (is.null(labelloc) || !labelloc) {
xrightoffset <- xleftoffset
xleftoffset <- unit(0, "npc")
xtextloc <- unit(1, "npc") - xrightoffset
xtextalign <- "left"
} else {
xrightoffset <- unit(0, "npc")
xtextloc <- xleftoffset
xtextalign <- "right"
}
if (labelouter) {
xleftoffset <- unit(0, "npc")
xrightoffset <- unit(0, "npc")
if (is.null(labelloc) || !labelloc) xtextloc <- unit(1.02, "npc")
else xtextloc <- unit(-0.02, "npc")
}
if (is.null(bcspace)) bcspace <- max(0.2, 1.5 / (maxct + 1))
pushViewport(viewport(x=xleftoffset,
y=unit(0, "npc"),
width=unit(1, "npc")-xleftoffset-xrightoffset,
height=unit(1, "npc"),
xscale=c(minx, maxx),
just=c("left", "bottom")))
if (!is.null(axisloc)) {
grid.xaxis(main=axisloc, gp=gpar(fontsize=fontsize))
if (axisloc) grid.text(xlab, x=unit(0.5, "npc"), y=unit(0, "npc") - xlaboffset)
else grid.text(xlab, x=unit(0.5, "npc"), y=unit(1, "npc") + xlaboffset)
}
popViewport(1)
for (i in 1:K) {
y <- x[[i]]
if (!is.null(labelloc))
grid.text(names(x)[i], x=xtextloc, y=unit((i-1)/K, "npc")+0.5*unit(1/K, "npc"),
just=xtextalign, gp=gpar(fontsize=fontsize))
if (nint>0) {
zhist <- hist(y, breaks=pretty(unlist(x), n=nint), plot=FALSE)
z <- zhist$counts
mids <- zhist$mids
} else {
z <- table(y)
mids <- as.numeric(names(z))
}
if (length(mids)>0) {
vp.barcode <- viewport(x=xleftoffset,
y=unit((i-1)/K, "npc") + unit(0.05/K, "npc"),
width=unit(1, "npc")-xleftoffset-xrightoffset,
height=unit(1/K, "npc")*bcspace - unit(0.05/K, "npc"),
xscale=c(minx, maxx), yscale=c(0,1),
just=c("left", "bottom"),
name="barcode", clip="off")
pushViewport(vp.barcode)
grid.segments(unit(mids[z>0], "native"), 0, unit(mids[z>0], "native"), 1)
popViewport(1)
vp.hist <- viewport(x=xleftoffset,
y=unit((i-1)/K, "npc")+unit(1/K, "npc")*bcspace,
width=unit(1, "npc")-xrightoffset-xleftoffset,
height=unit(1/K, "npc")-unit(1/K, "npc")*bcspace,
xscale=c(minx, maxx), yscale=c(0,1),
just=c("left", "bottom"),
name="hist", clip="off")
pushViewport(vp.hist)
vp.buffer <- viewport(x=0, y=0.05, width=1, height=0.9, just=c("left", "bottom"),
xscale=c(minx, maxx), yscale=c(0,1))
pushViewport(vp.buffer)
for (j in 1:length(z)) {
if (z[j]>1) {
xx <- rep(mids[j], z[j]-1)
if (log) {
yy <- ( log(2 + 1:(z[j]-1)) ) / maxct
} else { yy <- (1:(z[j]-1))/maxct }
if (use.points) grid.points(unit(xx, "native"), yy, pch=ptpch, size=ptsize)
else {
if (log) {
yy <- c(yy, log(2 + z[j]) / maxct)
} else { yy <- c(yy, (z[j])/maxct) }
grid.segments(unit(mids[j], "native"), unit(1/maxct, "npc"),
unit(mids[j], "native"), unit(max(yy), "npc"))
}
}
}
popViewport(2)
}
}
} |
qc_applications <- tibble(
application = c("developer_friendly", "user_friendly", "future_proof")
)
qc_categories <- tibble(
category = c("availability", "code_quality", "code_assurance", "documentation", "behaviour", "paper"),
color = c("
label = c("Availability", "Code quality", "Code assurance", "Documentation", "Behaviour", "Study design")
)
devtools::use_data(qc_applications, qc_categories, overwrite = TRUE, pkg = "package") |
extractCol <- function(contrastList, colName, robust = TRUE){
assertthat::assert_that(!missing(contrastList),
!is.null(contrastList),
length(unique(lapply(contrastList, colnames))) == 1,
length(unique(lapply(contrastList, dim))) == 1,
msg = "contrastList must be a list of data.frames which all have the same colnames and same row counts.")
if (any(is.null(robust),
!is.logical(robust),
length(robust) != 1)) {
warning("robust must be a singular logical value. Assigning default value TRUE.")
robust = TRUE
}
ifelse(robust,
return(.extractCol2(contrastList, colName)),
return(.extractCol1(contrastList, colName))
)
}
.extractCol1 <- function(contrastList, colName){
assertthat::assert_that("list" %in% class(contrastList),
!is.null(names(contrastList)),
msg = "contrastList must be a named list.")
assertthat::assert_that("character" %in% class(colName),
msg = "colName must be a column in the data of class 'character'.")
MyMatrix = do.call("cbind", lapply(contrastList, `[[`, colName))
rownames(MyMatrix) <- rownames(contrastList[[1]])
colnames(MyMatrix) <- names(contrastList)
return(as.data.frame(MyMatrix))
}
.extractCol2 <- function(contrastList, colName){
assertthat::assert_that("list" %in% class(contrastList),
!is.null(names(contrastList)),
msg = "contrastList must be a named list.")
assertthat::assert_that("character" %in% class(colName),
msg = "colName must be a column in the data of class 'character'.")
for (i in 1:length(contrastList)) {
newdat <- cbind(rowid = rownames(contrastList[[i]]), data.frame(contrastList[[i]], row.names = NULL))
newdat <- newdat[, c("rowid", colName)]
if (i == 1) {
dat <- newdat
} else {
dat <- merge(x = dat, y = newdat, by = "rowid", all = TRUE, sort = FALSE)
}
colnames(dat)[i + 1] <- names(contrastList[i])
}
dat <- data.frame(dat[,-c(1)], row.names = dat[,c(1)])
return(dat)
} |
get_fields <- function(es_host
, es_indices = '_all'
) {
es_url <- .ValidateAndFormatHost(es_host)
.assert(
is.character("es_indices")
, length(es_indices) > 0
)
indices <- paste(es_indices, collapse = ',')
if (nchar(indices) == 0){
msg <- paste("get_fields must be passed a valid es_indices."
, "You provided", paste(es_indices, collapse = ', ')
, 'which resulted in an empty string')
log_fatal(msg)
}
major_version <- .get_es_version(
es_host = es_host
)
if (as.integer(major_version) > 6 && indices == "_all"){
log_warn(sprintf(
paste0(
"You are running Elasticsearch version '%s.x'. _all is not supported in this version."
, " Pulling all indices with 'POST /_cat/indices' for you."
)
, major_version
))
res <- httr::RETRY(
verb = "GET"
, url = paste(
es_url
, "_cat"
, "indices?format=json"
, sep = "/"
)
, times = 3
)
indexDT <- data.table::as.data.table(
jsonlite::fromJSON(
httr::content(res, "text")
, simplifyDataFrame = TRUE
)
)
indices <- paste0(
indexDT[, unique(index)]
, collapse = ","
)
}
es_url <- paste(es_url, indices, '_mapping', sep = '/')
log_info(paste('Getting indexed fields for indices:', indices))
result <- httr::GET(
url = es_url
, httr::add_headers(c('Content-Type' = 'application/json'))
)
httr::stop_for_status(result)
resultContent <- httr::content(result, as = 'parsed')
if (as.integer(major_version) > 6){
mappingDT <- data.table::rbindlist(
l = lapply(
X = names(resultContent)
, FUN = function(index_name){
props <- resultContent[[index_name]][["mappings"]][["properties"]]
thisIndexDT <- data.table::data.table(
index = index_name
, type = NA_character_
, field = names(props)
, data_type = sapply(props, function(x){x$type})
)
return(thisIndexDT)
}
)
, fill = TRUE
)
} else {
mappingDT <- .flatten_mapping(mapping = resultContent)
}
rawAliasDT <- .get_aliases(es_host = es_host)
if (!is.null(rawAliasDT)) {
log_info("Replacing index names with aliases")
aliasDT <- data.table::rbindlist(
purrr::map2(
.x = rawAliasDT[["index"]]
, .y = rawAliasDT[["alias"]]
, .f = function(idx_name, alias_name, mappingDT){
tmpDT <- mappingDT[index == idx_name]
tmpDT[, index := alias_name]
return(tmpDT)
}
, mappingDT = mappingDT
)
, fill = TRUE
)
mappingDT <- data.table::rbindlist(
list(aliasDT, mappingDT[!(index %in% rawAliasDT[["index"]])])
, fill = TRUE
)
}
numFields <- nrow(mappingDT)
numIndex <- mappingDT[, data.table::uniqueN(index)]
log_info(paste('Retrieved', numFields, 'fields across', numIndex, 'indices'))
return(mappingDT)
}
.flatten_mapping <- function(mapping) {
flattened <- unlist(mapping)
mappingCols <- stringr::str_split_fixed(names(flattened), '\\.(mappings|properties)\\.', n = 3)
mappingDT <- data.table::data.table(
meta = mappingCols
, data_type = as.character(flattened)
)
newColNames <- c('index', 'type', 'field', 'data_type')
data.table::setnames(mappingDT, newColNames)
mappingDT <- mappingDT[stringr::str_detect(field, '\\.type$')]
metaRegEx <- '\\.(properties|fields|type)'
mappingDT[, field := stringr::str_replace_all(field, metaRegEx, '')]
return(mappingDT)
}
.get_aliases <- function(es_host) {
url <- paste0(es_host, '/_cat/aliases')
result <- httr::GET(
url = url
, httr::add_headers(c('Content-Type' = 'application/json'))
)
httr::stop_for_status(result)
resultContent <- httr::content(result, as = 'text')
if (is.null(resultContent) || identical(resultContent, "") || identical(resultContent, "[]")) {
return(invisible(NULL))
} else {
major_version <- .get_es_version(es_host)
process_alias <- switch(
major_version
, "1" = .process_legacy_alias
, "2" = .process_legacy_alias
, "5" = .process_new_alias
, "6" = .process_new_alias
, .process_new_alias
)
return(process_alias(alias_string = resultContent))
}
}
.process_legacy_alias <- function(alias_string){
aliasDT <- data.table::as.data.table(
jsonlite::fromJSON(
alias_string
, simplifyDataFrame = TRUE
, flatten = TRUE
)
)
return(aliasDT[, .(alias, index)])
}
.process_new_alias <- function(alias_string) {
aliasDT <- data.table::data.table(
utils::read.table(
text = alias_string
, stringsAsFactors = FALSE
)
)
return(aliasDT[, .(alias = V1, index = V2)])
} |
expected <- eval(parse(text="\"\\\"\\\\n\\\\f\\\\n\\\"\""));
test(id=0, code={
argv <- eval(parse(text="list(\"\\n\\f\\n\", 60L, FALSE, 69, -1L)"));
.Internal(deparse(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]]));
}, o=expected); |
setMethodS3("append", "RawGenomicSignals", function(this, other, addId=TRUE, ...) {
other <- Arguments$getInstanceOf(other, class(this)[1])
if (addId) {
if (is.null(this$id)) {
this$id <- rep(1L, times=nbrOfLoci(this))
}
if (is.null(other$id)) {
nextId <- max(this$id, na.rm=TRUE) + 1L
other$id <- rep(nextId, times=nbrOfLoci(other))
}
}
res <- rbind(this, other)
res
}) |
create_spliced_peptides<- function(i){
spliced<- lapply(i, function(pep){
lapply(seq(2, nchar(pep)-2),function(y){
a <- substr(pep, start=0, stop=y)
b <- substr(pep, start=y+1, stop=nchar(pep))
splicing<- c(list(peptide= pep, Frag1=a, Frag2=b, spliceType="forward",
spliced_peptide=paste(a,b,sep="_")), list(peptide=pep,
Frag1=b, Frag2 =a, spliceType="reverse", spliced_peptide=paste(b,a,sep="_")))
return (splicing)
})
})
x <- names(unlist(spliced, recursive = T))
x <- x[-grep("\\.Frag1|\\.Frag2|\\.spliceType|\\.spliced_peptide", x)]
counts<-seq(1, length(x))
x <- gsub("\\.peptide",".x" , x)
x<- paste0(x, counts)
spliced_df<- data.frame(matrix(unlist(spliced), ncol=5, byrow=TRUE), stringsAsFactors = FALSE,row.names= x)
colnames(spliced_df)<- c("Peptide", "Fragment1", "Fragment2", "spliceType", "spliced_peptide")
return(spliced_df)
} |
FKM.med <- function (X, k, m, RS, stand, startU, index,alpha,conv, maxit, seed = NULL)
{
if (missing(X))
stop("The data set must be given")
if (is.null(X))
stop("The data set X is empty")
X=data.matrix(X)
n=nrow(X)
p=ncol(X)
if(p==1){
stop("Dataset X must contain more than one dimension")
}
if (is.null(rownames(X)))
rn=paste("Obj",1:n,sep=" ")
else
rn=rownames(X)
if (is.null(colnames(X)))
cn=paste("Var",1:p,sep=" ")
else
cn=colnames(X)
if (any(is.na(X)))
stop("The data set X must not contain NA values")
if (!is.numeric(X))
stop("The data set X is not a numeric data.frame or matrix")
if ((missing(startU)) || (is.null(startU)))
{
check=1
checkMiss = missing(k) || is.null(k) || !is.numeric(k)
if (checkMiss)
{
k= 2:6
cat("The default value k=2:6 has been set ",fill=TRUE)
}
nk <- length(k)
if(nk != 1){
if(!checkMiss){
checkK = any(k <= 1) | any((k-as.integer(k)) != 0)
if(checkK)
{
k = 2:6
nk <- length(k)
cat("The number of clusters k must be greter than 1, integer and numeric: the default value k=2:6 will be used ",fill=TRUE)
}else{
k <- sort(unique(k))
nk <- length(k)
}
}
if (missing(index))
{
index = "SIL.F"
cat("The default index SIL.F has been set ",fill=TRUE)
}else{
if(length(index) != 1)
{
index = "SIL.F"
cat("The index must be a single value: SIL.F will be used ",fill=TRUE)
}else{
if(all(index!=c("PC","PE","MPC","SIL","SIL.F","XB"))){
index = "SIL.F"
cat("No match found for the index name: SIL.F will be used ", fill = TRUE)
}
}
}
if(index == "SIL.F"){
if (missing(alpha))
{
alpha=1
cat("The default value alpha=1 has been set for computing SIL.F ",fill=TRUE)
}else{
if (!is.numeric(alpha))
{
alpha=1
cat("The weighting coefficient alpha is not numeric: the default value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
if (alpha<0)
{
alpha=1
cat("The number of clusters k must be non negative: the value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
}
}else{
alpha = 1
}
}else{
nk <- 1
if (missing(index))
{
index = "SIL.F"
}else{
if(length(index) != 1)
{
index = "SIL.F"
cat("The index must be a single value: SIL.F will be used ",fill=TRUE)
}else{
if(!any(index==c("PC","PE","MPC","SIL","SIL.F","XB"))){
index = "SIL.F"
cat("No match found for the index name: SIL.F will be used ", fill = TRUE)
}
}
}
if(index == "SIL.F"){
if (missing(alpha))
{
alpha=1
}else{
if (!is.numeric(alpha))
{
alpha=1
cat("The weighting coefficient alpha is not numeric: the default value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
if (alpha<0)
{
alpha=1
cat("The number of clusters k must be non negative: the value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
}
}else{
alpha = 1
}
if (!is.numeric(k))
{
k=2
cat("The number of clusters k is not numeric: the default value k=2 will be used ",fill=TRUE)
}
if ((k>ceiling(n/2)) || (k<2))
{
k=2
cat("The number of clusters k must be an integer in {2, 3, ..., ceiling(n/2)}: the default value k=2 will be used ",fill=TRUE)
}
if (k%%ceiling(k)>0)
{
k=ceiling(k)
cat("The number of clusters k must be an integer in {2, 3, ..., ceiling(nrow(X)/2)}: the value ceiling(k) will be used ",fill=TRUE)
}
}
}else
{
startU=as.matrix(startU)
ns=nrow(startU)
k=ncol(startU)
check=0
nk = 1
if (any(is.na(startU)))
{
k=2
cat("The rational start must not contain NA values: the default value k=2 and a random start will be used ",fill=TRUE)
check=1
}
if (!is.numeric(startU))
{
k=2
cat("The rational start is not a numeric data.frame or matrix: the default value k=2 and a random start will be used ",fill=TRUE)
check=1
}
if ((k>ceiling(n/2)) || (k<2))
{
k=2
cat("The number of clusters k must be an integer in {2, 3, ..., ceiling(n/2)}: the default value k=2 and a random start will be used ",fill=TRUE)
check=1
}
if ((ns!=n) && (check=0))
{
cat("The number of rows of startU is different from that of X: k=ncol(startU) and a random start will be used ",fill=TRUE)
check=1
}
if (any(apply(startU,1,sum)!=1))
{
startU=startU/apply(startU,1,sum)
cat("The sums of the rows of startU must be equal to 1: the rows of startU will be normalized to unit row-wise sum ",fill=TRUE)
}
if (missing(index))
{
index = "SIL.F"
}else{
if(length(index) != 1)
{
index = "SIL.F"
cat("The index must be a single value: SIL.F will be used ",fill=TRUE)
}else{
if(!any(index==c("PC","PE","MPC","SIL","SIL.F","XB"))){
index = "SIL.F"
cat("No match found for the index name: SIL.F will be used ", fill = TRUE)
}
}
}
if(index == "SIL.F"){
if (missing(alpha))
{
alpha=1
}else{
if (!is.numeric(alpha))
{
alpha=1
cat("The weighting coefficient alpha is not numeric: the default value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
if (alpha<0)
{
alpha=1
cat("The number of clusters k must be non negative: the value alpha=1 will be used for computing SIL.F ",fill=TRUE)
}
}
}else{
alpha = 1
}
}
if (missing(m))
{
m=1.5
}
if(length(m) != 1){
m = 1.5
cat("The parameter of fuzziness m must be a single value: the default value m=1.5 will be used",fill=TRUE)
}
if (!is.numeric(m))
{
m=1.5
cat("The parameter of fuzziness m is not numeric: the default value m=1.5 will be used ",fill=TRUE)
}
if (m<=1)
{
m=1.5
cat("The parameter of fuzziness m must be >1: the default value m=1.5 will be used ",fill=TRUE)
}
if (missing(RS))
{
RS=1
}
if (!is.numeric(RS))
{
cat("The number of starts RS is not numeric: the default value RS=1 will be used ",fill=TRUE)
RS=1
}
if (RS<1)
{
cat("The number of starts RS must be an integer >=1: the default value RS=1 will be used ",fill=TRUE)
RS=1
}
if (RS%%ceiling(RS)>0)
{
cat("The number of starts RS must be an integer >=1: the value ceiling(RS) will be used ",fill=TRUE)
RS=ceiling(RS)
}
if (missing(conv))
conv=1e-9
if (!is.numeric(conv))
{
cat("The convergence criterion conv is not numeric: the default value conv=1e-9 will be used ",fill=TRUE)
conv=1e-9
}
if (conv<=0)
{
cat("The convergence criterion conv must be a (small) value >0: the default value conv=1e-9 will be used ",fill=TRUE)
conv=1e-9
}
if (missing(maxit))
maxit=1e+6
if (!is.numeric(maxit))
{
cat("The maximum number of iterations maxit is not numeric: the default value maxit=1e+6 will be used ",fill=TRUE)
maxit=1e+6
}
if (maxit<=0)
{
cat("The maximum number of iterations maxit must be an integer >0: the default value maxit=1e+6 will be used ",fill=TRUE)
maxit=1e+6
}
if (maxit%%ceiling(maxit)>0)
{
cat("The maximum number of iterations maxit must be an integer >0: the value ceiling(maxit) will be used ",fill=TRUE)
maxit=ceiling(maxit)
}
if(!is.null(seed))
{
if (!is.numeric(seed))
{
cat("The seed value is not numeric: set.seed(NULL) will be used ",fill=TRUE)
set.seed(NULL)
}else{
set.seed(seed)
}
}
Xraw=X
rownames(Xraw)=rownames(X)
colnames(Xraw)=colnames(X)
if (missing(stand))
stand=0
if (!is.numeric(stand))
stand=0
if (stand==1)
X=scale(X,center=TRUE,scale=TRUE)[,]
crit.f <- rep(NA,nk)
crit = 0
for(c in 1:nk)
{
if ((check!=1))
{
main.temp <- mainFKM_med_U(data = X, m = m, n = n, p = p, k = k[c], U = startU, conv = conv, maxit = maxit,index = index,alpha = alpha)
}else{
main.temp <- mainFKM_med(data = X, m = m, n = n, p = p, k = k[c], rs = RS, conv = conv, maxit = maxit,index = index,alpha = alpha)
}
crit.temp = main.temp$index_max
crit.f[c] = main.temp$index
if(c == 1 | crit < crit.temp)
{
main = main.temp
crit = crit.temp
}
}
value = as.vector(main$value)
it = as.vector(main$iter)
U.opt = main$U
H.opt = main$H
medoid.opt = as.vector(main$medoid)
names(crit.f) = paste(index," ","k=",k,sep="")
k = main$k
rownames(H.opt)=paste("Clus",1:k,sep=" ")
colnames(H.opt)=cn
rownames(U.opt)=rn
colnames(U.opt)=rownames(H.opt)
names(value)=paste("Start",1:RS,sep=" ")
names(it)=names(value)
names(k)=c("Number of clusters")
names(m)=c("Parameter of fuzziness")
if (stand!=1)
stand=0
names(stand)=c("Standardization (1=Yes, 0=No)")
clus=cl.memb(U.opt)
out=list(U=U.opt,
H=H.opt,
F=NULL,
clus=clus,
medoid=medoid.opt,
value=value,
criterion = crit.f,
iter=it,
k=k,
m=m,
ent=NULL,
b=NULL,
vp=NULL,
delta=NULL,
stand=stand,
Xca=X,
X=Xraw,
D=NULL,
call=match.call())
class(out)=c("fclust")
return(out)
} |
trace_coverage_log <- function(eventlog,
threshold = NULL) {
relative <- NULL
trace_coverage_trace(eventlog) -> raw
raw %>%
pull(relative) %>%
summary_statistics() -> output
attr(output, "raw") <- raw
return(output)
} |
get.lars.solution <- function(rho.m, corr.x, activeS, qr.tol, eps.tol) {
rhom.sign <- sign(rho.m[activeS])
activeS.sign <- rhom.sign/rhom.sign[1]
first.coord <- activeS[1]
Q.active <- t(sapply(activeS, function(i) {corr.x[[i]][activeS]}))
gmma <- qr.solve(Q.active, activeS.sign, tol = qr.tol)/activeS.sign
Dl <- rho.m/rho.m[first.coord]
Rl.den <- 1
Rl.num <- rowSums(sapply(1:length(activeS), function(j) {
corr.x[[activeS[j]]] * activeS.sign[j] * gmma[j]}), na.rm = TRUE)
Rl <- Rl.num / Rl.den
num <- Dl - Rl
nu.limit <- (1 - abs(num)/(1 - Rl * sign(num))) / Rl.den
lr.PlusOne.candidates <- which.min.ind(nu.limit, c(activeS, which(nu.limit < eps.tol)))
if (length(lr.PlusOne.candidates) > 0) {
lr.PlusOne <- resample(lr.PlusOne.candidates)
nu.limit <- nu.limit[lr.PlusOne]
}
else {
lr.PlusOne <- resample(which.min.ind(nu.limit, activeS))
nu.limit <- eps.tol
}
return(list(nu.limit = nu.limit, lr.PlusOne = lr.PlusOne,
gmma = gmma, active.set.sign = activeS.sign))
} |
data(hgsc)
hgsc <- hgsc[1:40, 1:30]
test_that("No algorithms means all algorithms, output is an array", {
x1 <- consensus_cluster(hgsc, nk = 4, reps = 1, progress = FALSE)
expect_error(x1, NA)
expect_is(x1, "array")
})
test_that("Output can be saved with or without time in file name", {
x1 <- consensus_cluster(hgsc, nk = 2:4, reps = 5, algorithms = "hc",
progress = FALSE, file.name = "CCOutput")
x2 <- consensus_cluster(hgsc, nk = 2:4, reps = 5, algorithms = "hc",
progress = FALSE, file.name = "CCOutput",
time.saved = TRUE)
expect_identical(x1, x2)
file.remove(list.files(pattern = "CCOutput"))
})
test_that("Progress bar increments across entire function call", {
assign("my_dist", function(x) stats::dist(x, method = "manhattan"), pos = 1)
x3 <- consensus_cluster(hgsc, nk = 2, reps = 5,
algorithms = c("nmf", "hc", "ap"),
distance = c("spear", "my_dist"), nmf.method = "lee",
progress = TRUE)
expect_error(x3, NA)
})
test_that("Able to call only spearman distance", {
x4 <- consensus_cluster(hgsc, nk = 2, reps = 5, algorithms = "hc",
distance = "spear")
expect_error(x4, NA)
})
test_that("Data preparation on bootstrap samples works", {
x5 <- consensus_cluster(hgsc, nk = 3, reps = 3,
algorithms = c("nmf", "hc", "ap"), nmf.method = "lee",
prep.data = "sampled")
expect_error(x5, NA)
})
test_that("no scaling means only choose complete cases and high signal vars", {
x6 <- consensus_cluster(hgsc, nk = 2, reps = 2, algorithms = "hc",
scale = FALSE)
expect_error(x6, NA)
})
test_that("t-SNE dimension reduction works", {
x7 <- consensus_cluster(hgsc, nk = 4, reps = 1, algorithms = c("hc", "km"),
type = "tsne")
expect_error(x7, NA)
}) |
[
{
"title": "Public and Public plus Private debt to GDP",
"href": "http://plausibel.blogspot.com/2013/01/public-and-public-plus-private-debt-to.html"
},
{
"title": "Data visualization videos",
"href": "http://robjhyndman.com/hyndsight/data-visualization-videos/?utm_source=rss&utm_medium=rss&utm_campaign=data-visualization-videos"
},
{
"title": "Which functions in R base call internal code?",
"href": "https://4dpiecharts.com/2010/09/14/which-functions-in-r-base-call-internal-code/"
},
{
"title": "The Uncertainty of Predictions",
"href": "http://statistical-research.com/the-uncertainty-of-predictions/?utm_source=rss&utm_medium=rss&utm_campaign=the-uncertainty-of-predictions"
},
{
"title": "Let pacman Eat Up library and require",
"href": "http://data-steve.github.io/let-pacman-eat-up-library-and-require/"
},
{
"title": "Performance of the divide-and-conquer SVD algorithm",
"href": "http://gallery.rcpp.org/articles/divide-and-concquer-svd/"
},
{
"title": "2012 Summer Olympics: Home Court Advantage – How Will the Brits Perform?",
"href": "https://feedproxy.google.com/~r/graphoftheweek/fzVA/~3/Tln2O_3Hbz4/summer-olympics-home-court-advantage.html"
},
{
"title": "project euler — problem 68",
"href": "https://web.archive.org/web/http://ygc.name/2012/12/12/problem-68/"
},
{
"title": "Reflections on John Chambers’ UserR! 2014 Keynote Address",
"href": "http://blog.revolutionanalytics.com/2014/07/reflections-on-john-chambers-userr-2014-keynote-address.html"
},
{
"title": "Oracle R Distribution for R 2.15.2 available on public-yum",
"href": "https://blogs.oracle.com/R/entry/oracle_r_distribution_for_r"
},
{
"title": "Bill Veanables Workshop (Augsburg University, Germany :: 2-3 July 2012)",
"href": "https://www.r-bloggers.com/bill-veanables-workshop-augsburg-university-germany-2-3-july-2012/"
},
{
"title": "Mortgage Refinance Calculator",
"href": "http://biostatmatt.com/archives/1908"
},
{
"title": "Comparing two-dimensional data sets in R; take II",
"href": "http://blog.mckuhn.de/2011/03/comparing-two-dimensional-data-sets-in_10.html"
},
{
"title": "Propensity Modeling, Causal Inference, and Discovering Drivers of Growth",
"href": "http://blog.echen.me/2014/08/15/propensity-modeling-causal-inference-and-discovering-drivers-of-growth/"
},
{
"title": "The Golden Section Search Method: Modifying the Bisection Method with the Golden Ratio for Numerical Optimization",
"href": "https://chemicalstatistician.wordpress.com/2013/04/22/using-the-bisection-method-with-the-golden-ratio-for-numerical-optimization/"
},
{
"title": "Everything you need to make R Commander locally (packages, dependencies, zip files)",
"href": "https://robertgrantstats.wordpress.com/2015/10/22/everything-you-need-to-make-r-commander-locally-packages-dependencies-zip-files/"
},
{
"title": "Another Way to Look at Vanguard and Pimco",
"href": "http://timelyportfolio.blogspot.com/2013/02/another-way-to-look-at-vanguard-and.html"
},
{
"title": "Forecasting with Neural Network (using SAP HANA and R)",
"href": "http://blagrants.blogspot.com/2013/08/forecasting-with-neural-network-using.html"
},
{
"title": "Adding watermarks to plots",
"href": "https://web.archive.org/web/http://blog.ggplot2.org/post/23537012922"
},
{
"title": "Because it’s Friday: Foxes on a Trampoline",
"href": "http://blog.revolutionanalytics.com/2010/08/because-its-friday-foxes-on-a-trampoline.html"
},
{
"title": "Bitsanity",
"href": "http://www.econometricsbysimulation.com/2014/04/bitsanity.html"
},
{
"title": "ggplot2 themes examples",
"href": "http://datascienceplus.com/ggplot2-themes-examples/"
},
{
"title": "RODM Article on the Oracle Technology Network",
"href": "http://www.r-chart.com/2010/08/rodm-article-on-oracle-technology.html"
},
{
"title": "Who are Turkopticon’s Top Contributors?",
"href": "http://www.econometricsbysimulation.com/2016/01/who-are-turkopticons-top-contributors.html"
},
{
"title": "Using TeXmacs as an interface for R (part 1)",
"href": "https://mltthinks.wordpress.com/2012/12/03/15/"
},
{
"title": "Free e-book: Data Science with SQL Server 2016",
"href": "http://blog.revolutionanalytics.com/2016/10/data-science-with-sql-server-2016.html"
},
{
"title": "knitr: nice alternative for Sweave",
"href": "http://zvfak.blogspot.com/2011/12/knitr-nice-alternative-for-sweave.html"
},
{
"title": "Random matrix theory and APT’s daily global model",
"href": "https://cartesianfaith.com/2012/01/25/random-matrix-theory-and-apts-daily-global-model/"
},
{
"title": "Wilcoxon Champagne test",
"href": "https://statisfaction.wordpress.com/2011/06/14/wilcoxon/"
},
{
"title": "Zurich, June 24/25, 2011 – Modern Portfolio Design with Rmetrics",
"href": "https://web.archive.org/web/https://www.rmetrics.org/zurich2011"
},
{
"title": "R / Finance 2016 Call for Papers",
"href": "http://dirk.eddelbuettel.com/blog/2015/10/15/"
},
{
"title": "Introducing pipeR 0.4",
"href": "https://renkun.me/blog/2014/08/04/introducing-pipeR-0.4.html"
},
{
"title": "Shiny for Interactive Application Development using R",
"href": "http://www.analyticsandvisualization.com/2015/02/shiny-for-interactive-application.html"
},
{
"title": "Martin Maechler Invited Talk at useR! 2014 – Good Practices in R Programming",
"href": "http://datascience.la/martin-maechler-invited-talk-at-user-2014-good-practices-in-r-programming/"
},
{
"title": "Matlab goes deep [learning]",
"href": "https://xianblog.wordpress.com/2016/09/05/matlab-goes-deep-learning/"
},
{
"title": "R from source",
"href": "http://blog.nguyenvq.com/blog/2011/07/11/r-from-source/"
},
{
"title": "i Before e Except After c",
"href": "http://jason.bryer.org/posts/2013-03-26/i_Before_e_Except_After_c.html"
},
{
"title": "New housedata release 20100923",
"href": "http://offensivepolitics.net/blog/2010/09/new-housedata-release-20100923/"
},
{
"title": "Analyzing the first Presidential Debate",
"href": "http://datascienceplus.com/analyzing-the-first-presidential-debate/"
},
{
"title": "knitr, Slideshows, and Dropbox",
"href": "http://christophergandrud.blogspot.com/2012/05/knitr-slideshows-and-dropbox.html"
},
{
"title": "Evaluating term popularity with twitteR",
"href": "http://is-r.tumblr.com/post/37468761327/evaluating-term-popularity-with-twitter"
},
{
"title": "R twitteR Analysis: How HOT is the Lynas Rare Earths Mining Malaysia?",
"href": "https://web.archive.org/web/http://blog.cloudstat.org/post/18296357801"
},
{
"title": "Bio7 2.4 for Windows and Mac Released",
"href": "http://bio7.org/?p=2737"
},
{
"title": "First meeting of Toronto R User Group this Friday",
"href": "http://blog.revolutionanalytics.com/2011/01/first-meeting-of-toronto-r-user-group-this-friday.html"
},
{
"title": "Statistics meets rhetoric: A text analysis of \"I Have a Dream\" in R",
"href": "http://anythingbutrbitrary.blogspot.com/2014/01/statistics-meets-rhetoric-text-analysis.html"
},
{
"title": "Functional programming with lambda.r",
"href": "https://cartesianfaith.com/2012/11/20/functional-programming-with-lambda-r/"
},
{
"title": "R in a 64 bit world",
"href": "http://www.win-vector.com/blog/2015/06/r-in-a-64-bit-world/"
},
{
"title": "Using Data Tools to Find Data Tools, the Yo Dawg of Data Hacking",
"href": "http://www.dataists.com/2010/10/using-data-tools-to-find-data-tools-the-yo-dawg-of-data-hacking/"
},
{
"title": "plot.xts is wonderful",
"href": "http://timelyportfolio.blogspot.com/2012/08/plotxts-is-wonderful.html"
},
{
"title": "ggplot2: Creating a custom plot with two different geoms",
"href": "https://rforwork.info/2012/06/10/ggplot2-creating-a-custom-plot-with-two-different-geoms/"
}
] |
context("pg_search_es")
test_that("pg_search_es", {
vcr::use_cassette("pg_search_es", {
aa <- pg_search_es()
}, preserve_exact_body_bytes = TRUE)
expect_is(aa, "tbl_df")
expect_is(aa, "data.frame")
expect_is(attributes(aa), "list")
expect_type(attr(aa, "total"), "integer")
expect_type(attr(aa, "max_score"), "double")
expect_type(aa$`_index`, "character")
expect_type(aa$`_source.eastBoundLongitude`, "double")
})
test_that("pg_search_es parameters work", {
vcr::use_cassette("pg_search_es_pagination", {
aa <- pg_search_es(size = 1)
}, preserve_exact_body_bytes = TRUE)
expect_is(aa, "tbl_df")
expect_equal(NROW(aa), 1)
})
test_that("fails well", {
skip_on_cran()
expect_error(pg_search_es(size = "asdffd"),
"size must be of class: numeric, integer")
expect_error(pg_search_es(from = "asdffd"),
"from must be of class: numeric, integer")
expect_error(pg_search_es(source = 5),
"source must be of class: character")
expect_error(pg_search_es(analyze_wildcard = "asdffd"),
"analyze_wildcard must be of class: logical")
}) |
print.uiprobit<-function(x,digits=3,digitsci=digits,digitsui=digits, ...){
if(sum(is.na(x$ui))>0){
ui<-x$uirough
ci<-x$cirough
}else{
ui<-x$ui
ci<-x$ci
}
w<-which(x$rho==0)
ci<-apply(ci[,w,],1,function(x){interv.p(x,digitsci)})
ui<-apply(ui,1,function(x){interv.p(x,digitsui)})
cat("\nCall:\n", deparse(x$call), "\n\n\n", sep = "")
cat("Confidence intervals (CI) derived assuming ignorable dropout (rho=0)","\n",sep="")
cat("Uncertainty intervals (UI) derived assuming ",min(x$rho),"<=rho<=", max(x$rho),"\n","\n",sep="")
Tab<-data.frame(Est=round(x$coef[,w],digits),ci=ci,ui=ui)
print(Tab)
if(sum(is.na(x$ui))>0){cat("\n","Note that the standard errors are not exact.","\n", "For an exact uncertainty interval choose se = TRUE instead.",sep="")}
} |
miss_sim <- function(dat,p=.2,type="MAR",seed_nr=123) {
set.seed(seed_nr)
dim <- dim(dat)[2]
if (type=="MAR") {
cor_param <- 2*stats::runif(dim * (dim - 1) / 2)-1
cor_matrix <- stats::cov2cor(copula::p2P(cor_param) %*% t(copula::p2P(cor_param)))
cor_matrix <- copula::P2p(cor_matrix)
} else if (type=="MCAR") {
cor_matrix <- diag(dim)
cor_matrix <- copula::P2p(cor_matrix)
} else stop("Provide valid type")
myCop <- copula::normalCopula(param=cor_matrix, dim , dispstr = "un")
myMvd <- copula::mvdc(copula=myCop, margins=c("binom"), marginsIdentical = TRUE, paramMargins=list(list(size=1,prob=p)) )
mis_ind <- copula::rMvdc(dim(dat)[1], myMvd)
mis_ind_NA <- sapply(mis_ind,function(x) ifelse(x==1,NA,x))
return (dat+mis_ind_NA)
} |
OpalFileResourceGetter <- R6::R6Class(
"OpalFileResourceGetter",
inherit = FileResourceGetter,
public = list(
initialize = function() {},
isFor = function(resource) {
if (super$isFor(resource)) {
url <- super$parseURL(resource)
scheme <- url$scheme
path <- url$path
(scheme == "opal+http" || scheme == "opal+https") && startsWith(path, "ws/files/")
} else {
FALSE
}
},
downloadFile = function(resource, ...) {
if (self$isFor(resource)) {
fileName <- super$extractFileName(resource)
downloadDir <- super$makeDownloadDir()
path <- file.path(downloadDir, fileName)
url <- super$parseURL(resource)
if (url$scheme == "opal+https") {
url$scheme <- "https"
} else if (url$scheme == "opal+http") {
url$scheme <- "http"
}
urlstr <- super$buildURL(url)
httr::GET(urlstr, private$addHeaders(resource), write_disk(path, overwrite = TRUE))
super$newFileObject(path, temp = TRUE)
} else {
NULL
}
}
),
private = list(
addHeaders = function(resource) {
if (!is.null(resource$identity) && nchar(resource$identity)>0 && !is.null(resource$secret) && nchar(resource$secret)>0) {
httr::add_headers(Authorization = jsonlite::base64_enc(paste0("X-Opal-Auth ", resource$identity, ":", resource$secret)))
} else if (!is.null(resource$secret) && nchar(resource$secret)>0) {
httr::add_headers("X-Opal-Auth" = resource$secret)
} else {
httr::add_headers()
}
}
)
) |
CoxBenchmark <- function(theData = NULL, theOutcome = "Class", reps = 100, trainFraction = 0.5,referenceCV = NULL,referenceName = "Reference",referenceFilterName="COX.BSWiMS")
{
if (!requireNamespace("BeSS", quietly = TRUE)) {
install.packages("BeSS", dependencies = TRUE)
}
if (!requireNamespace("survminer", quietly = TRUE)) {
install.packages("survminer", dependencies = TRUE)
}
if (is.null(theData))
{
if (exists("theDataSet", envir=FRESAcacheEnv))
{
theData <- get("theDataSet", envir=FRESAcacheEnv);
theOutcome <- get("theDataOutcome", envir=FRESAcacheEnv);
}
}
else
{
assign("theDataSet",theData,FRESAcacheEnv);
assign("theDataOutcome",theOutcome,FRESAcacheEnv);
}
aucTable <- NULL
accciTable <- NULL
errorciTable <- NULL
senTable <- NULL
speTable <- NULL
aucTable_filter <- NULL
accciTable_filter <- NULL
errorciTable_filter <- NULL
senTable_filter <- NULL
speTable_filter <- NULL
CIFollowUPTable <- NULL
CIRisksTable <- NULL
LogRankTable <- NULL
CIFollowUPTable_filter <- NULL
CIRisksTable_filter <- NULL
LogRankTable_filter <- NULL
fmeth_0 <- NULL;
FilterMethod <- function(clasfun = survival::coxph, classname = "", center = FALSE, ...)
{
rcvFilter_reference <- FRESA.CAD::randomCV(theData,theOutcome,clasfun,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = referenceCV$selectedFeaturesSet);
cStats <- predictionStats_survival(rcvFilter_reference$survMedianTest,plotname="Cox with BSWiMS");
CIFollowUPTable_filter <- rbind(CIFollowUPTable_filter,cStats$CIFollowUp);
CIRisksTable_filter <- rbind(CIRisksTable_filter,cStats$CIRisk);
LogRankTable_filter <- rbind(LogRankTable_filter,cStats$LogRank);
binaryPreds <- rcvFilter_reference$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"Cox with BSWiMS")
accciTable_filter <- rbind(accciTable_filter,binaryStats$accc)
errorciTable_filter <- rbind(errorciTable_filter,binaryStats$berror)
aucTable_filter <- rbind(aucTable_filter,binaryStats$aucs)
senTable_filter <- rbind(senTable_filter,binaryStats$sensitivity)
speTable_filter <- rbind(speTable_filter,binaryStats$specificity)
rcvFilter_LASSO <- try(FRESA.CAD::randomCV(theData,theOutcome,clasfun,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = rcvLASSO$selectedFeaturesSet));
if (!inherits(rcvLASSO, "try-error"))
{
cStats <- predictionStats_survival(rcvFilter_LASSO$survMedianTest,plotname="Cox with LASSO");
CIFollowUPTable_filter <- rbind(CIFollowUPTable_filter,cStats$CIFollowUp);
CIRisksTable_filter <- rbind(CIRisksTable_filter,cStats$CIRisk);
LogRankTable_filter <- rbind(LogRankTable_filter,cStats$LogRank);
binaryPreds <- rcvFilter_LASSO$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"Cox with Lasso")
accciTable_filter <- rbind(accciTable_filter,binaryStats$accc)
errorciTable_filter <- rbind(errorciTable_filter,binaryStats$berror)
aucTable_filter <- rbind(aucTable_filter,binaryStats$aucs)
senTable_filter <- rbind(senTable_filter,binaryStats$sensitivity)
speTable_filter <- rbind(speTable_filter,binaryStats$specificity)
}
rcvFilter_BESS <- try(FRESA.CAD::randomCV(theData,theOutcome,clasfun,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = rcvBESS$selectedFeaturesSet));
if (!inherits(rcvLASSO, "try-error"))
{
cStats <- predictionStats_survival(rcvFilter_BESS$survMedianTest,plotname="Cox with BESS");
CIFollowUPTable_filter <- rbind(CIFollowUPTable_filter,cStats$CIFollowUp);
CIRisksTable_filter <- rbind(CIRisksTable_filter,cStats$CIRisk);
LogRankTable_filter <- rbind(LogRankTable_filter,cStats$LogRank);
binaryStats <- predictionStats_binary(rcvFilter_BESS$survMedianTest[,c("Outcome","LinearPredictorsMedian")],"Cox with BeSS")
accciTable_filter <- rbind(accciTable_filter,binaryStats$accc)
errorciTable_filter <- rbind(errorciTable_filter,binaryStats$berror)
aucTable_filter <- rbind(aucTable_filter,binaryStats$aucs)
senTable_filter <- rbind(senTable_filter,binaryStats$sensitivity)
speTable_filter <- rbind(speTable_filter,binaryStats$specificity)
}
cat("Univariate cox Feature Selection: ");
rcvFilter_UniCox <- try(FRESA.CAD::randomCV(theData,theOutcome,clasfun,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = univariate_cox));
if (!inherits(rcvLASSO, "try-error"))
{
cStats <- predictionStats_survival(rcvFilter_UniCox$survMedianTest,"Cox with Univariate cox Feature Selection");
CIFollowUPTable_filter <- rbind(CIFollowUPTable_filter,cStats$CIFollowUp);
CIRisksTable_filter <- rbind(CIRisksTable_filter,cStats$CIRisk);
LogRankTable_filter <- rbind(LogRankTable_filter,cStats$LogRank);
binaryStats <- predictionStats_binary(rcvFilter_UniCox$survMedianTest[,c("Outcome","LinearPredictorsMedian")],"Unicox")
accciTable_filter <- rbind(accciTable_filter,binaryStats$accc)
errorciTable_filter <- rbind(errorciTable_filter,binaryStats$berror)
aucTable_filter <- rbind(aucTable_filter,binaryStats$aucs)
senTable_filter <- rbind(senTable_filter,binaryStats$sensitivity)
speTable_filter <- rbind(speTable_filter,binaryStats$specificity)
}
result <- list(CIFollowUPTable_filter = CIFollowUPTable_filter,
CIRisksTable_filter = CIRisksTable_filter,
LogRankTable_filter = LogRankTable_filter,
accciTable_filter = accciTable_filter,
errorciTable_filter = errorciTable_filter,
aucTable_filter = aucTable_filter,
senTable_filter = senTable_filter,
speTable_filter = speTable_filter,
rcvFilter_reference = rcvFilter_reference,
rcvFilter_LASSO = rcvFilter_LASSO,
rcvFilter_BESS = rcvFilter_BESS,
rcvFilter_UniCox = rcvFilter_UniCox
)
return(result);
}
theFiltersets <- character();
theClassMethod <- character();
elapcol <- character();
cputimes <- list();
jaccard <- NULL;
featsize <- NULL;
TheCVEvaluations = list();
times <- list();
jaccard_filter <- list();
selFrequency <- data.frame(colnames(theData));
rownames(selFrequency) <- colnames(theData);
if (is.null(referenceCV))
{
cat("Modeling BSWiMS: + Model found, - No Model \n");
referenceCV <- FRESA.CAD::randomCV(theData,theOutcome,BSWiMS.model,trainFraction = trainFraction,repetitions = reps,featureSelectionFunction = "Self");
referenceName = "BSWiMS";
referenceFilterName = "Cox.BSWiMS";
methods <- c(referenceName);
theFiltersets <- c(referenceName);
}
if (class(referenceCV) == "list")
{
elapcol <- names(referenceCV[[1]]$theTimes) == "elapsed"
TheCVEvaluations <- referenceCV;
for (i in 1:length(referenceCV))
{
cStats <- predictionStats_survival(referenceCV[[i]]$survMedianTest,plotname = names(referenceCV)[i]);
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- referenceCV[[i]]$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"BSWiMS")
accciTable <- rbind(accciTable,binaryStats$accc)
errorciTable <- rbind(errorciTable,binaryStats$berror)
aucTable <- rbind(aucTable,binaryStats$aucs);
senTable <- rbind(senTable,binaryStats$sensitivity);
speTable <- rbind(speTable,binaryStats$specificity);
cputimes[[i]] = mean(referenceCV[[i]]$theTimes[ elapcol ]);
times[[i]] <- referenceCV[[i]]$theTimes;
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(referenceCV[[i]]$featureFrequency),ncol(selFrequency)] <- referenceCV[[i]]$featureFrequency;
jaccard_filter[[i]] <- referenceCV[[i]]$jaccard;
}
referenceName <- names(referenceCV);
referenceFilterName <- paste("FS",names(referenceCV),sep="_");
referenceCV <- referenceCV[[1]];
class(referenceCV) <- "list"
}
else
{
cStats <- predictionStats_survival(referenceCV$survMedianTest,plotname = referenceName);
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- referenceCV$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"BSWiMS")
accciTable <- rbind(accciTable,binaryStats$accc)
errorciTable <- rbind(errorciTable,binaryStats$berror)
aucTable <- rbind(aucTable,binaryStats$aucs)
senTable <- rbind(senTable,binaryStats$sensitivity)
speTable <- rbind(speTable,binaryStats$specificity)
TheCVEvaluations$Reference <- referenceCV;
times[[1]] <- referenceCV$theTimes;
elapcol <- names(referenceCV$theTimes) == "elapsed"
cputimes[[1]] = mean(referenceCV$theTimes[ elapcol ]);
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(referenceCV$featureFrequency),ncol(selFrequency)] <- referenceCV$featureFrequency;
jaccard_filter[[1]] <- referenceCV$jaccard;
}
reps <- referenceCV$repetitions;
test_Predictions <- referenceCV$survMedianTest;
tnames <- rownames(test_Predictions)
rcvLASSO <- try(FRESA.CAD::randomCV(theData,theOutcome,LASSO_MIN,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = "Self"));
if (!inherits(rcvLASSO, "try-error"))
{
methods <- cbind(methods,"LASSO");
cStats <- predictionStats_survival(rcvLASSO$survMedianTest,plotname = "LASSO");
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- rcvLASSO$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"Lasso")
accciTable <- rbind(accciTable,binaryStats$accc)
errorciTable <- rbind(errorciTable,binaryStats$berror)
aucTable <- rbind(aucTable,binaryStats$aucs)
senTable <- rbind(senTable,binaryStats$sensitivity)
speTable <- rbind(speTable,binaryStats$specificity)
TheCVEvaluations$LASSO <- rcvLASSO;
times$LASSO <- rcvLASSO$theTimes
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(rcvLASSO$featureFrequency),ncol(selFrequency)] <- rcvLASSO$featureFrequency;
theFiltersets <- c(theFiltersets,"LASSO");
jaccard_filter$LASSO <- rcvLASSO$jaccard;
test_Predictions <- cbind(test_Predictions,rcvLASSO$survMedianTest[tnames,3],rcvLASSO$survMedianTest[tnames,4],rcvLASSO$survMedianTest[tnames,5],rcvLASSO$survMedianTest[tnames,6])
cputimes$LASSO = mean(rcvLASSO$theTimes[ elapcol ])
}
rcvGLMNET_RIDGE <- try(FRESA.CAD::randomCV(theData,theOutcome,GLMNET_RIDGE_MIN,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = "Self"));
if (!inherits(rcvGLMNET_RIDGE, "try-error"))
{
methods <- cbind(methods,"RIDGE");
cStats <- predictionStats_survival(rcvGLMNET_RIDGE$survMedianTest,plotname = "GLMNET_RIDGE");
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- rcvGLMNET_RIDGE$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"Ridge")
accciTable <- rbind(accciTable,binaryStats$accc)
errorciTable <- rbind(errorciTable,binaryStats$berror)
aucTable <- rbind(aucTable,binaryStats$aucs)
senTable <- rbind(senTable,binaryStats$sensitivity)
speTable <- rbind(speTable,binaryStats$specificity)
TheCVEvaluations$RIDGE <- rcvGLMNET_RIDGE;
times$RIDGE <- rcvGLMNET_RIDGE$theTimes
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(rcvGLMNET_RIDGE$featureFrequency),ncol(selFrequency)] <- rcvGLMNET_RIDGE$featureFrequency;
theFiltersets <- c(theFiltersets,"RIDGE");
jaccard_filter$RIDGE <- rcvGLMNET_RIDGE$jaccard;
test_Predictions <- cbind(test_Predictions,rcvGLMNET_RIDGE$survMedianTest[tnames,3],rcvGLMNET_RIDGE$survMedianTest[tnames,4],rcvGLMNET_RIDGE$survMedianTest[tnames,5],rcvGLMNET_RIDGE$survMedianTest[tnames,6])
cputimes$RIDGE = mean(rcvGLMNET_RIDGE$theTimes[ elapcol ])
}
rcvGLMNET_ELASTICNET <- try(FRESA.CAD::randomCV(theData,theOutcome,GLMNET_ELASTICNET_MIN,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = "Self"));
if (!inherits(rcvGLMNET_ELASTICNET, "try-error"))
{
methods <- cbind(methods,"ELASTICNET");
cStats <- predictionStats_survival(rcvGLMNET_ELASTICNET$survMedianTest,plotname = "GLMNET_ELASTICNET");
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- rcvGLMNET_ELASTICNET$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"ElasticNet")
accciTable <- rbind(accciTable,binaryStats$accc)
errorciTable <- rbind(errorciTable,binaryStats$berror)
aucTable <- rbind(aucTable,binaryStats$aucs)
senTable <- rbind(senTable,binaryStats$sensitivity)
speTable <- rbind(speTable,binaryStats$specificity)
TheCVEvaluations$ELASTICNET <- rcvGLMNET_ELASTICNET;
times$ELASTICNET <- rcvGLMNET_ELASTICNET$theTimes
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(rcvGLMNET_ELASTICNET$featureFrequency),ncol(selFrequency)] <- rcvGLMNET_ELASTICNET$featureFrequency;
theFiltersets <- c(theFiltersets,"ELASTICNET");
jaccard_filter$ELASTICNET <- rcvGLMNET_ELASTICNET$jaccard;
test_Predictions <- cbind(test_Predictions,rcvGLMNET_ELASTICNET$survMedianTest[tnames,3],rcvGLMNET_ELASTICNET$survMedianTest[tnames,4],rcvGLMNET_ELASTICNET$survMedianTest[tnames,5],rcvGLMNET_ELASTICNET$survMedianTest[tnames,6])
cputimes$ELASTICNET = mean(rcvGLMNET_ELASTICNET$theTimes[ elapcol ])
}
rcvBESS <- try(FRESA.CAD::randomCV(theData,theOutcome,BESS,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = "Self",method="gsection"));
if (!inherits(rcvBESS, "try-error"))
{
methods <- cbind(methods,"BESS");
cStats <- predictionStats_survival(rcvBESS$survMedianTest,plotname = "BeSS");
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- rcvBESS$survMedianTest[,c("Outcome","LinearPredictorsMedian")];
binaryStats <- predictionStats_binary(binaryPreds,"BeSS");
accciTable <- rbind(accciTable,binaryStats$accc);
errorciTable <- rbind(errorciTable,binaryStats$berror);
aucTable <- rbind(aucTable,binaryStats$aucs);
senTable <- rbind(senTable,binaryStats$sensitivity);
speTable <- rbind(speTable,binaryStats$specificity);
TheCVEvaluations$BESS <- rcvBESS;
times$BESS <- rcvBESS$theTimes
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(rcvBESS$featureFrequency),ncol(selFrequency)] <- rcvBESS$featureFrequency;
theFiltersets <- c(theFiltersets,"BESS");
jaccard_filter$BESS <- rcvBESS$jaccard;
test_Predictions <- cbind(test_Predictions,rcvBESS$survMedianTest[tnames,3],rcvBESS$survMedianTest[tnames,4],rcvBESS$survMedianTest[tnames,5],rcvBESS$survMedianTest[tnames,6])
cputimes$BESS = mean(rcvBESS$theTimes[ elapcol ])
}
rcvBESSSequential <- try(FRESA.CAD::randomCV(theData,theOutcome,BESS,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = "Self",method="sequential",ic.type="GIC"));
if (!inherits(rcvBESSSequential, "try-error"))
{
methods <- cbind(methods,"BeSS.SEQUENTIAL");
cStats <- predictionStats_survival(rcvBESSSequential$survMedianTest,plotname = "BeSS.SEQUENTIAL");
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- rcvBESSSequential$survMedianTest[,c("Outcome","LinearPredictorsMedian")];
binaryStats <- predictionStats_binary(binaryPreds,"BeSS.SEQUENTIAL");
accciTable <- rbind(accciTable,binaryStats$accc);
errorciTable <- rbind(errorciTable,binaryStats$berror);
aucTable <- rbind(aucTable,binaryStats$aucs);
senTable <- rbind(senTable,binaryStats$sensitivity);
speTable <- rbind(speTable,binaryStats$specificity);
TheCVEvaluations$BESS.SEQUENTIAL <- rcvBESSSequential;
times$BESS.SEQUENTIAL <- rcvBESSSequential$theTimes
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(rcvBESSSequential$featureFrequency),ncol(selFrequency)] <- rcvBESSSequential$featureFrequency;
theFiltersets <- c(theFiltersets,"BESS.SEQUENTIAL");
jaccard_filter$BESS.SEQUENTIAL <- rcvBESSSequential$jaccard;
test_Predictions <- cbind(test_Predictions,rcvBESSSequential$survMedianTest[tnames,3],rcvBESSSequential$survMedianTest[tnames,4],rcvBESSSequential$survMedianTest[tnames,5],rcvBESSSequential$survMedianTest[tnames,6])
cputimes$BESS.SEQUENTIAL = mean(rcvBESSSequential$theTimes[ elapcol ])
}
rcvBESSSequentialBIC <- try(FRESA.CAD::randomCV(theData,theOutcome,BESS,trainSampleSets = referenceCV$trainSamplesSets,featureSelectionFunction = "Self"));
if (!inherits(rcvBESSSequentialBIC, "try-error"))
{
methods <- cbind(methods,"BeSS.SEQUENTIAL.BIC");
cStats <- predictionStats_survival(rcvBESSSequentialBIC$survMedianTest,plotname = "BeSS.SEQUENTIAL.BIC");
CIFollowUPTable <- rbind(CIFollowUPTable,cStats$CIFollowUp);
CIRisksTable <- rbind(CIRisksTable,cStats$CIRisk);
LogRankTable <- rbind(LogRankTable,cStats$LogRank);
binaryPreds <- rcvBESSSequentialBIC$survMedianTest[,c("Outcome","LinearPredictorsMedian")]
binaryStats <- predictionStats_binary(binaryPreds,"BeSS.SEQUENTIAL.BIC")
accciTable <- rbind(accciTable,binaryStats$accc);
errorciTable <- rbind(errorciTable,binaryStats$berror);
aucTable <- rbind(aucTable,binaryStats$aucs);
senTable <- rbind(senTable,binaryStats$sensitivity);
speTable <- rbind(speTable,binaryStats$specificity);
TheCVEvaluations$BESS.SEQUENTIAL.BIC <- rcvBESSSequentialBIC;
times$BESS.SEQUENTIAL.BIC <- rcvBESSSequentialBIC$theTimes
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
selFrequency[names(rcvBESSSequentialBIC$featureFrequency),ncol(selFrequency)] <- rcvBESSSequentialBIC$featureFrequency;
theFiltersets <- c(theFiltersets,"BESS.SEQUENTIAL.BIC");
jaccard_filter$BESS.SEQUENTIAL.BIC <- rcvBESSSequentialBIC$jaccard;
test_Predictions <- cbind(test_Predictions,rcvBESSSequentialBIC$survMedianTest[tnames,3],rcvBESSSequentialBIC$survMedianTest[tnames,4],rcvBESSSequentialBIC$survMedianTest[tnames,5],rcvBESSSequentialBIC$survMedianTest[tnames,6])
cputimes$BESS.SEQUENTIAL.BIC = mean(rcvBESSSequentialBIC$theTimes[ elapcol ])
}
predictions <- c("MartinGale","LinearPredictors","FollowUpTimes","Risks");
columnNamesMethods <- NULL;
for(x in methods)
{
for(y in predictions)
{
columnNamesMethods <- cbind(columnNamesMethods,paste(x,y,sep=""))
}
}
colnames(test_Predictions) <- c("Times","Outcome",columnNamesMethods);
thesets <- c("Survival Algorithm")
theMethod <- methods;
rownames(CIFollowUPTable) <- theMethod;
rownames(CIRisksTable) <- theMethod;
rownames(LogRankTable) <- theMethod;
rownames(accciTable) <- theMethod;
rownames(errorciTable) <- theMethod;
rownames(aucTable) <- theMethod;
rownames(senTable) <- theMethod;
rownames(speTable) <- theMethod;
cputimes <- unlist(cputimes);
names(cputimes) <- theMethod;
if (class(referenceCV) != "list")
{
classnames <- colnames(test_Predictions);
cat("Cox\n")
fmeth <- FilterMethod(survival::coxph,"Cox")
CIFollowUPTable_filter <- rbind(CIFollowUPTable_filter,fmeth$CIFollowUPTable_filter);
CIRisksTable_filter <- rbind(CIRisksTable_filter,fmeth$CIFollowUPTable_filter);
LogRankTable_filter <- rbind(LogRankTable_filter,fmeth$LogRankTable_filter);
accciTable_filter <- rbind(accciTable_filter,fmeth$accciTable_filter)
errorciTable_filter <- rbind(errorciTable_filter,fmeth$errorciTable_filter)
aucTable_filter <- rbind(aucTable_filter,fmeth$aucTable_filter)
senTable_filter <- rbind(senTable_filter,fmeth$senTable_filter)
speTable_filter <- rbind(speTable_filter,fmeth$speTable_filter)
TheCVEvaluations$Cox.Reference <- fmeth$rcvFilter_reference;
TheCVEvaluations$Cox.LASSO = fmeth$rcvFilter_LASSO;
TheCVEvaluations$Cox.BESS = fmeth$rcvFilter_BESS;
TheCVEvaluations$Cox.Unicox = fmeth$rcvFilter_UniCox;
test_Predictions <- cbind(test_Predictions,fmeth$rcvFilter_reference$survMedianTest[tnames,3],fmeth$rcvFilter_reference$survMedianTest[tnames,4],fmeth$rcvFilter_reference$survMedianTest[tnames,5],fmeth$rcvFilter_reference$survMedianTest[tnames,6]);
filters = c("COX.BSWiMS");
if (!inherits(fmeth$rcvFilter_LASSO, "try-error"))
{
test_Predictions <- cbind(test_Predictions,fmeth$rcvFilter_LASSO$survMedianTest[tnames,3],fmeth$rcvFilter_LASSO$survMedianTest[tnames,4],fmeth$rcvFilter_LASSO$survMedianTest[tnames,5],fmeth$rcvFilter_LASSO$survMedianTest[tnames,6]);
filters = c(filters,"COX.LASSO");
}
if (!inherits(fmeth$rcvFilter_BESS, "try-error"))
{
test_Predictions <- cbind(test_Predictions,fmeth$rcvFilter_BESS$survMedianTest[tnames,3],fmeth$rcvFilter_BESS$survMedianTest[tnames,4],fmeth$rcvFilter_BESS$survMedianTest[tnames,5],fmeth$rcvFilter_BESS$survMedianTest[tnames,6]);
filters = c(filters,"COX.BESS");
}
if (!inherits(fmeth$rcvFilter_UniCox, "try-error"))
{
test_Predictions <- cbind(test_Predictions,fmeth$rcvFilter_UniCox$survMedianTest[tnames,3],fmeth$rcvFilter_UniCox$survMedianTest[tnames,4],fmeth$rcvFilter_UniCox$survMedianTest[tnames,5],fmeth$rcvFilter_UniCox$survMedianTest[tnames,6]);
filters = c(filters,"COX.UnivariateCox");
}
columnNamesMethods <- NULL;
for(x in filters)
{
for(y in predictions)
{
columnNamesMethods <- cbind(columnNamesMethods,paste(x,y,sep=""))
}
}
colnames(test_Predictions) <- c(classnames,columnNamesMethods);
selFrequency <- cbind(selFrequency,numeric(ncol(theData)));
if (!inherits(fmeth$rcvFilter_UniCox, "try-error"))
{
selFrequency[names(fmeth$rcvFilter_UniCox$featureFrequency),ncol(selFrequency)] <- fmeth$rcvFilter_UniCox$featureFrequency;
theFiltersets <- c(theFiltersets,"Cox.Unicox");
jaccard_filter$kendall <- fmeth$rcvFilter_UniCox$jaccard;
}
}
featsize <- unlist(lapply(jaccard_filter, `[`, c('averageLength')))
names(featsize) <- theFiltersets;
jaccard <- unlist(lapply(jaccard_filter, `[`, c('Jaccard.SM')))
names(jaccard) <- theFiltersets;
selFrequency <- as.data.frame(selFrequency[,-1])
selFrequency <- selFrequency/reps;
colnames(selFrequency) <- theFiltersets;
totsum <- apply(selFrequency,1,sum);
selFrequency <- selFrequency[order(-totsum),];
totsum <- totsum[order(-totsum)];
selFrequency <- selFrequency[totsum>0,];
test_Predictions <- as.data.frame(test_Predictions)
for (i in 2:ncol(test_Predictions))
{
if (test_Predictions[,i] < -1)
{
test_Predictions[,i] <- 1.0/(1.0+exp(-test_Predictions[,i] ));
}
}
result <- list(errorciTable = errorciTable,accciTable = accciTable,aucTable = aucTable,senTable = senTable,speTable = speTable,
errorciTable_filter = errorciTable_filter,accciTable_filter = accciTable_filter,aucTable_filter = aucTable_filter,senTable_filter = senTable_filter,speTable_filter = speTable_filter,
CIRisksTable = CIRisksTable,CIFollowUPTable = CIFollowUPTable,LogRankTable = LogRankTable,
CIRisksTable_filter = CIRisksTable_filter,CIFollowUPTable_filter = CIFollowUPTable_filter,LogRankTable_filter = LogRankTable_filter,
times = list(Reference = referenceCV$theTimes,LASSO = rcvLASSO$theTimes, RIDGE = rcvGLMNET_RIDGE$theTimes, ELASTICNET = rcvGLMNET_ELASTICNET, BESS = rcvBESS$theTimes, BESS.SEQUENTIAL = rcvBESSSequential$theTimes, BESS.SEQUENTIAL.BIC=rcvBESSSequentialBIC$theTimes),
jaccard = jaccard,
featsize = featsize,
TheCVEvaluations = TheCVEvaluations,
thesets = thesets,
theMethod = theMethod,
theFiltersets = theFiltersets,
testPredictions = test_Predictions,
featureSelectionFrequency = selFrequency,
cpuElapsedTimes=cputimes
)
class(result) <- c("FRESA_benchmark","Survival.COX");
return(result)
} |
tam_print_computation_time <- function(object)
{
cat( "Date of Analysis:", paste(object$time[2]), "\n" )
cat("Computation time:", print(object$time[2] - object$time[1]), "\n\n")
} |
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
library(xgboost)
modelX <- "xgbDART"
for(i in getModelInfo(modelX)[[1]]$library)
do.call("requireNamespace", list(package = i))
xgbGrid <- expand.grid(nrounds = c(1, 10),
max_depth = 2,
eta = 0.30,
rate_drop = 0.10,
skip_drop = 0.10,
colsample_bytree = 0.90,
min_child_weight = 2,
subsample = 0.75,
gamma = 0.10)
set.seed(2)
training <- twoClassSim(100, linearVars = 2)
testing <- twoClassSim(500, linearVars = 2)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
train_sparse <- xgb.DMatrix(as.matrix(trainX))
cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary)
cctrl2 <- trainControl(method = "LOOCV",
classProbs = TRUE, summaryFunction = twoClassSummary)
cctrl3 <- trainControl(method = "oob")
cctrl4 <- trainControl(method = "none",
classProbs = TRUE, summaryFunction = twoClassSummary)
cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(649)
test_class_cv_model <- train(trainX, trainY,
method = modelX,
trControl = cctrl1,
metric = "ROC",
preProc = c("center", "scale"),
tuneGrid = xgbGrid)
set.seed(649)
test_class_cv_model_sp <- train(train_sparse, trainY,
method = modelX,
trControl = cctrl1,
metric = "ROC",
tuneGrid = xgbGrid)
set.seed(649)
test_class_cv_form <- train(Class ~ ., data = training,
method = modelX,
trControl = cctrl1,
metric = "ROC",
preProc = c("center", "scale"),
tuneGrid = xgbGrid)
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob")
test_class_pred_form <- predict(test_class_cv_form, testing[, -ncol(testing)])
test_class_prob_form <- predict(test_class_cv_form, testing[, -ncol(testing)], type = "prob")
set.seed(649)
test_class_rand <- train(trainX, trainY,
method = modelX,
trControl = cctrlR,
tuneLength = 4)
set.seed(649)
test_class_loo_model <- train(trainX, trainY,
method = modelX,
trControl = cctrl2,
metric = "ROC",
preProc = c("center", "scale"),
tuneGrid = xgbGrid)
set.seed(649)
test_class_none_model <- train(trainX, trainY,
method = modelX,
trControl = cctrl4,
tuneGrid = xgbGrid[nrow(xgbGrid),],
metric = "ROC",
preProc = c("center", "scale"))
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob")
set.seed(649)
test_class_rec <- train(x = rec_cls,
data = training,
method = modelX,
trControl = cctrl1,
metric = "ROC",
tuneGrid = xgbGrid)
if(!isTRUE( all.equal(test_class_cv_model$results, test_class_rec$results))){
stop("CV weights not giving the same results")
}
test_class_imp_rec <- varImp(test_class_rec)
test_class_pred_rec <- predict(test_class_rec, testing[, -ncol(testing)])
test_class_prob_rec <- predict(test_class_rec, testing[, -ncol(testing)], type = "prob")
rep_eval_of_predict_cls = sapply( 1:100, function(x)
predict(test_class_rec, newdata = testing[1, -ncol(testing)], type="prob")[,1])
if(length(unique(rep_eval_of_predict_cls))>1){
stop("Repeated evaluation do not return the same result (classification).")
}
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
library(caret)
library(plyr)
library(recipes)
library(dplyr)
set.seed(1)
training <- SLC14_1(75)
testing <- SLC14_1(100)
trainX <- training[, -ncol(training)]
trainY <- training$y
rec_reg <- recipe(y ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
testX <- trainX[, -ncol(training)]
testY <- trainX$y
train_sparse <- xgb.DMatrix(as.matrix(trainX))
rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all")
rctrl2 <- trainControl(method = "LOOCV")
rctrl3 <- trainControl(method = "oob")
rctrl4 <- trainControl(method = "none")
rctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(649)
test_reg_cv_model <- train(trainX, trainY,
method = modelX,
trControl = rctrl1,
preProc = c("center", "scale"),
tuneGrid = xgbGrid)
test_reg_pred <- predict(test_reg_cv_model, testX)
set.seed(649)
test_reg_cv_model_sp <- train(train_sparse, trainY,
method = modelX,
trControl = rctrl1,
tuneGrid = xgbGrid)
test_reg_pred_sp <- predict(test_reg_cv_model_sp, testX)
set.seed(649)
test_reg_cv_form <- train(y ~ ., data = training,
method = modelX,
trControl = rctrl1,
preProc = c("center", "scale"),
tuneGrid = xgbGrid)
test_reg_pred_form <- predict(test_reg_cv_form, testX)
set.seed(649)
test_reg_rand <- train(trainX, trainY,
method = modelX,
trControl = rctrlR,
tuneLength = 4)
set.seed(649)
test_reg_loo_model <- train(trainX, trainY,
method = modelX,
trControl = rctrl2,
preProc = c("center", "scale"),
tuneGrid = xgbGrid)
set.seed(649)
test_reg_none_model <- train(trainX, trainY,
method = modelX,
trControl = rctrl4,
tuneGrid = xgbGrid[nrow(xgbGrid),],
preProc = c("center", "scale"))
test_reg_none_pred <- predict(test_reg_none_model, testX)
set.seed(649)
test_reg_rec <- train(x = rec_reg,
data = training,
method = modelX,
trControl = rctrl1,
tuneGrid = xgbGrid)
if( !isTRUE( all.equal(test_reg_cv_model$results, test_reg_rec$results))){
stop("CV weights not giving the same optimal parameters")
}
test_reg_imp_rec <- varImp(test_reg_rec)
test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)])
rep_eval_of_predict_reg = sapply(1:100, function(x)
predict(test_reg_rec, newdata = testing[1, -ncol(testing)]))
if(length(unique(rep_eval_of_predict_reg))>1){
stop("Repeated evaluation do not return the same result (regression).")
}
test_class_predictors1 <- predictors(test_class_cv_model)
test_reg_predictors1 <- predictors(test_reg_cv_model)
test_class_imp <- varImp(test_class_cv_model)
test_reg_imp <- varImp(test_reg_cv_model)
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(modelX, ".RData", sep = "")))
if(!interactive()) q("no") |
elx_fetch_data <- function(url, type = c("title","text","ids","notice"),
language_1 = "en", language_2 = "fr", language_3 = "de",
include_breaks = TRUE){
stopifnot("url must be specified" = !missing(url),
"type must be specified" = !missing(type),
"type must be correctly specified" = type %in% c("title","text","ids","notice"))
language <- paste(language_1,", ",language_2,";q=0.8, ",language_3,";q=0.7", sep = "")
if (stringr::str_detect(url,"celex.*[\\(|\\)|\\/]")){
clx <- stringr::str_extract(url, "(?<=celex\\/).*") %>%
stringr::str_replace_all("\\(","%28") %>%
stringr::str_replace_all("\\)","%29") %>%
stringr::str_replace_all("\\/","%2F")
url <- paste("http://publications.europa.eu/resource/celex/",
clx,
sep = "")
}
if (type == "title"){
response <- graceful_http(url,
headers = httr::add_headers('Accept-Language' = language,
'Accept' = 'application/xml; notice=object'),
verb = "GET")
if (httr::status_code(response)==200){
out <- httr::content(response) %>%
xml2::xml_find_first("//EXPRESSION_TITLE") %>%
xml2::xml_find_first("VALUE") %>%
xml2::xml_text()
} else {out <- httr::status_code(response)}
}
if (type == "text"){
response <- graceful_http(url,
headers = httr::add_headers('Accept-Language' = language,
'Content-Language' = language,
'Accept' = 'text/html, text/html;type=simplified, text/plain, application/xhtml+xml, application/xhtml+xml;type=simplified, application/pdf, application/pdf;type=pdf1x, application/pdf;type=pdfa1a, application/pdf;type=pdfx, application/pdf;type=pdfa1b, application/msword'),
verb = "GET")
if (httr::status_code(response)==200){
out <- elx_read_text(response)
}
else if (httr::status_code(response)==300){
links <- response %>%
httr::content(as = "text") %>%
xml2::read_html() %>%
rvest::html_node("body") %>%
rvest::html_nodes("a") %>%
rvest::html_attrs() %>%
unlist()
names(links) <- NULL
multiout <- ""
for (q in 1:length(links)){
multiresponse <- graceful_http(links[q],
headers = httr::add_headers('Accept-Language' = language,
'Content-Language' = language,
'Accept' = 'text/html, text/html;type=simplified, text/plain, application/xhtml+xml, application/xhtml+xml;type=simplified, application/pdf, application/pdf;type=pdf1x, application/pdf;type=pdfa1a, application/pdf;type=pdfx, application/pdf;type=pdfa1b, application/msword'),
verb = "GET")
if (httr::status_code(multiresponse)==200){
multiout[q] <- elx_read_text(multiresponse)
multiout <- paste0(multiout, collapse = " ---documentbreak--- ")
} else {
multiout <- NA_character_
names(multiout) <- "missingdoc"
}
}
names(multiout) <- "multidocs"
out <- multiout
}
else if (httr::status_code(response)==406){
out <- NA
names(out) <- "missingdoc"
}
if (include_breaks == FALSE){
out <- stringr::str_remove_all(out,"---pagebreak---|---documentbreak---")
}
}
if (type == "ids"){
response <- graceful_http(url,
headers = httr::add_headers('Accept-Language' = language,
'Accept' = 'application/xml; notice=identifiers'),
verb = "GET")
if (httr::status_code(response)==200){
out <- httr::content(response) %>%
xml2::xml_children() %>%
xml2::xml_find_all(".//VALUE") %>%
xml2::xml_text()
} else {out <- httr::status_code(response)}
}
if (type == "notice"){
response <- graceful_http(url,
headers = httr::add_headers('Accept-Language' = language,
'Accept' = 'application/xml; notice=branch'),
verb = "GET")
if (httr::status_code(response)==200){
out <- httr::content(response)
} else {out <- httr::status_code(response)}
}
return(out)
}
elx_read_text <- function(http_response){
if (stringr::str_detect(http_response$headers$`content-type`,"html")){
out <- http_response %>%
xml2::read_html() %>%
rvest::html_node("body") %>%
rvest::html_text() %>%
paste0(collapse = " ---pagebreak--- ")
names(out) <- "html"
}
else if (stringr::str_detect(http_response$headers$`content-type`,"pdf")){
out <- http_response$url %>%
pdftools::pdf_text() %>%
paste0(collapse = " ---pagebreak--- ")
names(out) <- "pdf"
}
else if (stringr::str_detect(http_response$headers$`content-type`,"msword")){
out <- http_response$url %>%
antiword::antiword() %>%
paste0(collapse = " ---pagebreak--- ")
names(out) <- "word"
} else {
out <- "unsupported format"
names(out) <- "unsupported"
}
return(out)
} |
ggmatrix_progress <- function(
format = " plot: [:plot_i,:plot_j] [:bar]:percent est::eta ",
clear = TRUE,
show_after = 0,
...
) {
ret <- function(pm, ...) {
progress::progress_bar$new(
format = format,
clear = clear,
show_after = show_after,
total = pm$ncol * pm$nrow,
...
)
}
ret
}
as_ggmatrix_progress <- function(x, total, ...) {
if (isFALSE(x)) {
return(FALSE)
}
if (isTRUE(x)) {
return(ggmatrix_progress(...))
}
if (is.null(x)) {
shouldDisplay <- interactive() && total > 15
if (!shouldDisplay) {
return(FALSE)
} else {
return(ggmatrix_progress(...))
}
}
if (is.function(x)) {
return(x)
}
stop(
"as_ggmatrix_progress only knows how to handle TRUE, FALSE, NULL, or a function.",
" If a function, it must return a new progress_bar"
)
}
isFALSE <- function(x) {
identical(FALSE, x)
} |
NULL
collapse_labels_lines <- function(labels) {
is_exp <- vapply(labels, function(l) length(l) > 0 && is.expression(l[[1]]), logical(1))
out <- do.call("Map", c(list(paste, sep = ", "), labels))
label <- list(unname(unlist(out)))
if (all(is_exp)) {
label <- lapply(label, function(l) list(parse(text = paste0("list(", l, ")"))))
}
label
}
label_value <- function(labels, multi_line = TRUE) {
labels <- lapply(labels, as.character)
if (multi_line) {
labels
} else {
collapse_labels_lines(labels)
}
}
class(label_value) <- c("function", "labeller")
label_variable <- function(labels, multi_line = TRUE) {
if (multi_line) {
row <- as.list(names(labels))
} else {
row <- list(paste(names(labels), collapse = ", "))
}
lapply(row, rep, nrow(labels) %||% length(labels[[1]]))
}
label_both <- function(labels, multi_line = TRUE, sep = ": ") {
value <- label_value(labels, multi_line = multi_line)
variable <- label_variable(labels, multi_line = multi_line)
if (multi_line) {
out <- vector("list", length(value))
for (i in seq_along(out)) {
out[[i]] <- paste(variable[[i]], value[[i]], sep = sep)
}
} else {
value <- do.call("paste", c(value, sep = ", "))
variable <- do.call("paste", c(variable, sep = ", "))
out <- Map(paste, variable, value, sep = sep)
out <- list(unname(unlist(out)))
}
out
}
class(label_both) <- c("function", "labeller")
label_context <- function(labels, multi_line = TRUE, sep = ": ") {
if (length(labels) == 1) {
label_value(labels, multi_line)
} else {
label_both(labels, multi_line)
}
}
class(label_context) <- c("function", "labeller")
label_parsed <- function(labels, multi_line = TRUE) {
labels <- label_value(labels, multi_line = multi_line)
if (multi_line) {
lapply(unname(labels), lapply, function(values) {
c(parse(text = as.character(values)))
})
} else {
lapply(labels, function(values) {
values <- paste0("list(", values, ")")
lapply(values, function(expr) c(parse(text = expr)))
})
}
}
class(label_parsed) <- c("function", "labeller")
find_names <- function(expr) {
if (is.call(expr)) {
unlist(lapply(expr[-1], find_names))
} else if (is.name(expr)) {
as.character(expr)
}
}
label_bquote <- function(rows = NULL, cols = NULL,
default) {
cols_quoted <- substitute(cols)
rows_quoted <- substitute(rows)
has_warned <- FALSE
call_env <- env_parent()
fun <- function(labels) {
quoted <- resolve_labeller(rows_quoted, cols_quoted, labels)
if (is.null(quoted)) {
return(label_value(labels))
}
evaluate <- function(...) {
params <- list(...)
if ("x" %in% find_names(quoted) && !"x" %in% names(params)) {
if (!has_warned) {
warn("Referring to `x` is deprecated, use variable name instead")
has_warned <<- TRUE
}
params$x <- params[[1]]
}
params <- as_environment(params, call_env)
eval(substitute(bquote(expr, params), list(expr = quoted)))
}
list(do.call("Map", c(list(f = evaluate), labels)))
}
structure(fun, class = "labeller")
}
utils::globalVariables(c("x", "."))
label_wrap_gen <- function(width = 25, multi_line = TRUE) {
fun <- function(labels) {
labels <- label_value(labels, multi_line = multi_line)
lapply(labels, function(x) {
x <- strwrap(x, width = width, simplify = FALSE)
vapply(x, paste, character(1), collapse = "\n")
})
}
structure(fun, class = "labeller")
}
is_labeller <- function(x) inherits(x, "labeller")
resolve_labeller <- function(rows, cols, labels) {
if (is.null(cols) && is.null(rows)) {
abort("Supply one of rows or cols")
}
if (attr(labels, "facet") == "wrap") {
if (!is.null(cols) && !is.null(rows)) {
abort("Cannot supply both rows and cols to facet_wrap()")
}
cols %||% rows
} else {
if (attr(labels, "type") == "rows") {
rows
} else {
cols
}
}
}
as_labeller <- function(x, default = label_value, multi_line = TRUE) {
force(x)
fun <- function(labels) {
labels <- lapply(labels, as.character)
default <- dispatch_args(default, multi_line = multi_line)
if (is_labeller(x)) {
x <- dispatch_args(x, multi_line = multi_line)
x(labels)
} else if (is.function(x)) {
default(lapply(labels, x))
} else if (is.formula(x)) {
default(lapply(labels, as_function(x)))
} else if (is.character(x)) {
default(lapply(labels, function(label) x[label]))
} else {
default(labels)
}
}
structure(fun, class = "labeller")
}
labeller <- function(..., .rows = NULL, .cols = NULL,
keep.as.numeric = NULL, .multi_line = TRUE,
.default = label_value) {
if (!is.null(keep.as.numeric)) {
.Deprecated(old = "keep.as.numeric")
}
dots <- list(...)
.default <- as_labeller(.default)
function(labels) {
if (!is.null(.rows) || !is.null(.cols)) {
margin_labeller <- resolve_labeller(.rows, .cols, labels)
} else {
margin_labeller <- NULL
}
if (is.null(margin_labeller)) {
labellers <- lapply(dots, as_labeller, default = .default)
} else {
margin_labeller <- as_labeller(margin_labeller, default = .default,
multi_line = .multi_line)
if (any(names(dots) %in% names(labels))) {
abort(glue(
"Conflict between .{attr(labels, 'type')} and ",
glue_collapse(names(dots), ", ", last = " and ")
))
}
}
if (is.null(margin_labeller)) {
out <- lapply(names(labels), function(label) {
if (label %in% names(labellers)) {
labellers[[label]](labels[label])[[1]]
} else {
.default(labels[label])[[1]]
}
})
names(out) <- names(labels)
if (.multi_line) {
out
} else {
collapse_labels_lines(out)
}
} else {
margin_labeller(labels)
}
}
}
build_strip <- function(label_df, labeller, theme, horizontal) {
labeller <- match.fun(labeller)
if (empty(label_df)) {
return(if (horizontal) {
list(top = NULL, bottom = NULL)
} else {
list(left = NULL, right = NULL)
})
}
labels <- lapply(labeller(label_df), cbind)
labels <- do.call("cbind", labels)
ncol <- ncol(labels)
nrow <- nrow(labels)
if (horizontal) {
grobs_top <- lapply(labels, element_render, theme = theme,
element = "strip.text.x.top", margin_x = TRUE,
margin_y = TRUE)
grobs_top <- assemble_strips(matrix(grobs_top, ncol = ncol, nrow = nrow),
theme, horizontal, clip = "on")
grobs_bottom <- lapply(labels, element_render, theme = theme,
element = "strip.text.x.bottom", margin_x = TRUE,
margin_y = TRUE)
grobs_bottom <- assemble_strips(matrix(grobs_bottom, ncol = ncol, nrow = nrow),
theme, horizontal, clip = "on")
list(
top = grobs_top,
bottom = grobs_bottom
)
} else {
grobs_left <- lapply(labels, element_render, theme = theme,
element = "strip.text.y.left", margin_x = TRUE,
margin_y = TRUE)
grobs_left <- assemble_strips(matrix(grobs_left, ncol = ncol, nrow = nrow),
theme, horizontal, clip = "on")
grobs_right <- lapply(labels[, rev(seq_len(ncol(labels))), drop = FALSE],
element_render, theme = theme,
element = "strip.text.y.right", margin_x = TRUE,
margin_y = TRUE)
grobs_right <- assemble_strips(matrix(grobs_right, ncol = ncol, nrow = nrow),
theme, horizontal, clip = "on")
list(
left = grobs_left,
right = grobs_right
)
}
}
assemble_strips <- function(grobs, theme, horizontal = TRUE, clip) {
if (length(grobs) == 0 || is.zero(grobs[[1]])) {
grobs <- grobs[seq_len(NROW(grobs))]
return(grobs)
}
grobs[] <- lapply(grobs, function(g) {
if (inherits(g, "titleGrob")) return(g)
add_margins(gList(g), grobHeight(g), grobWidth(g), margin_x = TRUE, margin_y = TRUE)
})
if (horizontal) {
height <- max_height(lapply(grobs, function(x) x$heights[2]))
width <- unit(1, "null")
} else {
height <- unit(1, "null")
width <- max_width(lapply(grobs, function(x) x$widths[2]))
}
grobs[] <- lapply(grobs, function(x) {
x$widths <- unit.c(x$widths[1], width, x$widths[c(-1, -2)])
x$heights <- unit.c(x$heights[1], height, x$heights[c(-1, -2)])
x$vp$parent$layout$widths <- unit.c(x$vp$parent$layout$widths[1], width, x$vp$parent$layout$widths[c(-1, -2)])
x$vp$parent$layout$heights <- unit.c(x$vp$parent$layout$heights[1], height, x$vp$parent$layout$heights[c(-1, -2)])
x
})
if (horizontal) {
height <- sum(grobs[[1]]$heights)
} else {
width <- sum(grobs[[1]]$widths)
}
background <- if (horizontal) "strip.background.x" else "strip.background.y"
background <- element_render(theme, background)
grobs[] <- lapply(grobs, function(x) {
ggname("strip", gTree(children = gList(background, x)))
})
apply(grobs, 1, function(x) {
if (horizontal) {
mat <- matrix(x, ncol = 1)
} else {
mat <- matrix(x, nrow = 1)
}
gtable_matrix("strip", mat, rep(width, ncol(mat)), rep(height, nrow(mat)), clip = clip)
})
}
check_labeller <- function(labeller) {
labeller <- match.fun(labeller)
is_deprecated <- all(c("variable", "value") %in% names(formals(labeller)))
if (is_deprecated) {
old_labeller <- labeller
labeller <- function(labels) {
Map(old_labeller, names(labels), labels)
}
warn(glue(
"The labeller API has been updated. Labellers taking `variable` ",
"and `value` arguments are now deprecated. See labellers documentation."))
}
labeller
} |
assign("rbf.tcv",
function(formula, data, eta, rho, n.neigh, func){
z = extractFormula(formula, data, newdata=data)$z
s = coordinates(data)
rbf.pred <- as.data.frame(matrix(NA,nrow= length(z), ncol=8))
colnames(rbf.pred) <- c("var1.pred","var1.var","observed","residual","zscore","fold","x","y")
pb <- txtProgressBar(min = 0, max = length(z), char = "=", style = 3)
for(i in 1:(length(z))){
rbf.pred[i,1] <- rbf(formula, data[-i,], eta, rho, newdata=data[i,], n.neigh, func)[,3]
rbf.pred[i,6] <- i
setTxtProgressBar(pb, i)
}
close(pb)
rbf.pred[,3]<- z
rbf.pred[,7:8]<-s
rbf.pred[,4]<- rbf.pred[,3]-rbf.pred[,1]
rbf.pred
}
) |
v1 = c('A', 'B','C')
v1
class(v1)
(v2 = c(1,2,3))
v2
class(v2)
(v3 = c(TRUE, FALSE, TRUE))
class(v3)
V3a <- c(T,F,T)
v4 = 100:200
length(v4)
v4
v5 = seq(1,10,2)
v4; v5
v4
v4[-c(1,3,4)]
v4[v4 > 150]
v7 = c('A','C')
v1
v1[!v1 %in% v7]
v1
v1['A']
v1[1]
v1
v4(v8 = 10:15)
names(v8) = c('E','F','G','H','I','J')
v8
v8['G']
v8[c('G','I')]
v8[3:5]
str(v8)
str(v1)
class(v8)
class(v1)
rollno=c(1,2,3)
name=c('Rohit','Lalit', 'Hitesh')
course=c('MBA','BBA','MCA')
dept=c('Dept1','Dept1','Dept2')
marks=floor(rnorm(3,50,10))
?rnorm
rnorm(3,50,10)
students = data.frame(rollno, name, course, dept, marks)
students
class(students)
str(students)
summary(students)
df = data.frame(rollno=c(1,2,3), name=c('Rohit','Lalit', 'Hitesh'), course=c('MBA','BBA','MCA'), dept=c('Dept1','Dept1','Dept2'),marks=floor(runif(3,50,100)))
df
class(df)
df
str(df)
class(df)
summary(df)
listL1 = list('dhiraj', v1, students, mymatrix, myarray)
listL1
ls()
rm(list=ls())
ls()
(mylist1 = list( 1, df, v4))
?matrix
'a':'Z'
mym = matrix(c('a','b',2,'d'), ncol=2)
mym
1:24
(mymatrix = matrix(1:24,ncol=6,byrow=T))
length(11:35)
mymatrix[,1]
mymatrix[2:4,3:4]
mymatrix[5,3]
mymatrix
?matrix
(mymatrix = matrix(1:24,ncol=4, byrow=TRUE))
rows1= c('R_1','R_2')
1:6
rn = paste('R',1:6, sep='-')
cn = paste('C',1:4, sep='-')
dimnames(mymatrix) = list(c(rn), c(cn))
mymatrix
?dimnames
dimnames(mymatrix) = list(c(paste('R',1:6, sep='_')), c(paste('C',1:4,sep='')))
mymatrix
paste('C',1:4, sep='')
mymatrix[c('R-1'),]
mymatrix[,c('C-3')]
mymatrix[c('R-1','R-3'),]
mymatrix[c(1,3),]
mymatrix
colSums(mymatrix)
rowSums(mymatrix)
rowMeans(mymatrix)
colMeans(mymatrix)
(myarray = array(101:124, dim=c(4,3,2)))
(myarray = array(1:24, dim=c(3,2,4)))
(myarray = array(1:24, dim=c(4,3,2), dimnames = list(c('S1','S2','S3','S4'), c('Sub1','Sub2','Sub3'), c('Dept1','Dept2'))))
myarray
apply(myarray,3,sum)
apply(myarray,2,mean)
apply(myarray,3,sum)
apply(myarray,c(2,3),mean)
apply(myarray,c(1,3),sd)
apply(myarray,c(1,2),max)
name = c('S1','S2','S3','S4','S5')
course = c('PHD', 'MTECH', 'BTECH','BTECH','PHD')
gender = c('M', 'F', 'M', 'F','M')
grades = c('A','B','C','A','F')
marks = c(runif(5, 50, 100))
df = data.frame(name, course, gender, grades, marks)
df
str(df)
df[1:2,]
df[,1:3]
df$name = as.character(df$name)
str(df)
df$grades = factor(df$grades, ordered=F, levels=c('A','B','C','D','E','F'))
str(df)
df$grades
df$gender = factor(df$gender, ordered=T, levels=c('M','F'))
df$gender
students
df
df=fix(df)
df[3:4,1:2]
df
df$course
df$name
df$gender = c('M','F','M','M')
df
str(df)
df$gender = factor(df$gender)
str(df)
df$grades = c('A', 'B', 'A', 'C')
df
str(df)
df$grades = factor(df$grades, ordered=T)
str(df)
df$grades
df$grades = factor(df$grades, ordered=T, levels=c('C','B','A'))
df$grades
table(df$course,df$gender)
mymatrix
apply(mymatrix, 1, sum)
apply(mymatrix, 2, sum)
apply(mymatrix, 2, sd)
myarray
apply(myarray, 1, sum)
df
?apply
df
tapply(df$marks, df$gender, mean)
?tapply
df
df$gender = NULL
df
df[df$dept == 'Dept1',]
df[df$marks >= 80,] |
search_anymatch <- function(x, wt = "json", raw = FALSE, ...) {
out <- itis_GET("searchForAnyMatch", list(srchKey = x), wt, ...)
if (raw || wt == "xml") return(out)
x <- parse_raw(out)$anyMatchList
tmp <- dr_op(bindlist(x$commonNameList.commonNames), "class")
if (NROW(tmp) == 0) return(tibble::tibble())
names(tmp) <- paste0("common_", names(tmp))
x <- suppressWarnings(
cbind(
dr_op(x, c("commonNameList.commonNames", "commonNameList.class",
"commonNameList.tsn", "class")),
tmp
)
)
tibble::as_tibble(x)
} |
estimate.model.lnre.fzm <- function (model, spc, param.names,
method, cost.function, m.max=15,
runs=1, debug=FALSE, ...)
{
if (! inherits(model, "lnre.fzm")) stop("argument must be object of class 'lnre.fzm'")
if (runs > 1) warning("multiple estimation runs not yet implemented for Custom method (please set runs=1)")
B.root.function <- function (B, N, V, model) {
B <- B
model <- model$util$update(model, list(B=B))
E.V <- EV(model, N)
E.V - V
}
compute.B <- function(model, spc) {
alpha <- model$param$alpha
A <- model$param$A
N <- N(spc)
V <- V(spc)
term1 <- (N ^ alpha) * Igamma(1 - alpha, N * A, lower=FALSE)
term2 <- (A ^ (-alpha)) * (1 - exp(-N * A))
C <- alpha * V / (term1 + term2)
B <- ( (1 - alpha) / C + A ^ (1 - alpha) ) ^ (1 / (1 - alpha))
if (B > 1e6) {
if (debug) warning("Estimate B = ",B," > 1e6 from inexact model, adjusting to 1e6")
B <- 1e6
}
if (model$exact) {
.eps <- 10 * .Machine$double.eps
upper.B <- B
lower.B <- upper.B
.diff <- B.root.function(lower.B, N, V, model)
if (.diff >= 0) {
if (debug) warning("Can't adjust estimate B = ",B," from inexact model ",
"since E[V] - V = ",.diff," > 0")
}
else {
while ((lower.B - A) > .eps && .diff < 0) {
lower.B <- (lower.B + A) / 2
.diff <- B.root.function(lower.B, N, V, model)
}
if (.diff < 0) {
if (debug) warning("Can't find exact estimate for B, since lowest possible value ",
"B = ",lower.B," has E[V] - V = ",.diff," < 0")
}
else {
res <- uniroot(B.root.function, lower=lower.B, upper=upper.B, tol=.eps * B,
N=N, V=V, model=model)
if (abs(res$f.root) > .5) {
if (debug) warning("No exact estimate for B found. Best guess was ",
"B = ",res$root," with E[V] - V = ",res$f.root)
}
else {
B <- res$root
}
}
}
}
B
}
if ("B" %in% param.names) {
param.names <- param.names[param.names != "B"]
}
else {
warning("parameter B cannot be fixed in fZM estimation, ignoring specified value")
}
param.values <- rep(0, length(param.names))
if ("alpha" %in% param.names) {
tmp <- list(alpha=Vm(spc, 1) / V(spc))
tmp <- model$util$transform(tmp)
param.values[param.names == "alpha"] <- tmp$alpha
}
compute.cost <- function (P.vector, param.names, model, spc, m.max=15, debug=FALSE)
{
P.trans <- as.list(P.vector)
names(P.trans) <- param.names
P <- model$util$transform(P.trans, inverse=TRUE)
P$B <- max(1, 10 * P$A)
model <- model$util$update(model, P)
B <- compute.B(model, spc)
model <- model$util$update(model, list(B=B))
cost <- cost.function(model, spc, m.max)
if (debug) {
report <- as.data.frame(model$param)
report$cost <- round(cost, digits=2)
rownames(report) <- ""
print(report)
}
cost
}
if (length(param.names) > 1) {
result <- optim(param.values, compute.cost, method="Nelder-Mead",
control=list(trace=debug, reltol=1e-12),
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug)
res.conv <- result$convergence
if (res.conv > 1) stop("parameter estimation failed (code ", res.conv, ")")
if (res.conv > 0)
warning("iteration limit exceeded, estimated parameter values may be incorrect (code 1)")
P.estimate <- as.list(result$par)
names(P.estimate) <- param.names
model <- model$util$update(model, P.estimate, transformed=TRUE)
}
else if (length(param.names) >= 1) {
result <- nlm(compute.cost, param.values, print.level=debug, stepmax=10, steptol=1e-12,
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug)
res.code <- result$code
if (res.code > 3) stop("parameter estimation failed (code ", res.code,")")
if (res.code == 3) warning("estimated parameter values may be incorrect (code 3)")
P.estimate <- as.list(result$estimate)
names(P.estimate) <- param.names
model <- model$util$update(model, P.estimate, transformed=TRUE)
}
B <- compute.B(model, spc)
model <- model$util$update(model, list(B=B))
model$gof <- lnre.goodness.of.fit(model, spc, n.estimated=length(param.names) + 1)
model
} |
stri_startswith <- function(str, ..., fixed, coll, charclass)
{
providedarg <- c(
fixed = !missing(fixed),
coll = !missing(coll),
charclass = !missing(charclass))
if (sum(providedarg) != 1)
stop("you have to specify either `fixed`, `coll`, or `charclass`")
if (providedarg["fixed"])
stri_startswith_fixed(str, fixed, ...)
else if (providedarg["coll"])
stri_startswith_coll(str, coll, ...)
else if (providedarg["charclass"])
stri_startswith_charclass(str, charclass, ...)
}
stri_endswith <- function(str, ..., fixed, coll, charclass)
{
providedarg <- c(
fixed = !missing(fixed),
coll = !missing(coll),
charclass = !missing(charclass))
if (sum(providedarg) != 1)
stop("you have to specify either `fixed`, `coll`, or `charclass`")
if (providedarg["fixed"])
stri_endswith_fixed(str, fixed, ...)
else if (providedarg["coll"])
stri_endswith_coll(str, coll, ...)
else if (providedarg["charclass"])
stri_endswith_charclass(str, charclass, ...)
}
stri_startswith_fixed <- function(str, pattern, from = 1L,
negate = FALSE, ..., opts_fixed = NULL)
{
if (!missing(...))
opts_fixed <- do.call(stri_opts_fixed, as.list(c(opts_fixed, ...)))
.Call(C_stri_startswith_fixed, str, pattern, from, negate, opts_fixed)
}
stri_endswith_fixed <- function(str, pattern, to = -1L,
negate = FALSE, ..., opts_fixed = NULL)
{
if (!missing(...))
opts_fixed <- do.call(stri_opts_fixed, as.list(c(opts_fixed, ...)))
.Call(C_stri_endswith_fixed, str, pattern, to, negate, opts_fixed)
}
stri_startswith_charclass <- function(str, pattern, from = 1L, negate = FALSE)
{
.Call(C_stri_startswith_charclass, str, pattern, from, negate)
}
stri_endswith_charclass <- function(str, pattern, to = -1L, negate = FALSE)
{
.Call(C_stri_endswith_charclass, str, pattern, to, negate)
}
stri_startswith_coll <- function(str, pattern, from = 1L,
negate = FALSE, ..., opts_collator = NULL)
{
if (!missing(...))
opts_collator <- do.call(stri_opts_collator, as.list(c(opts_collator, ...)))
.Call(C_stri_startswith_coll, str, pattern, from, negate, opts_collator)
}
stri_endswith_coll <- function(str, pattern, to = -1L,
negate = FALSE, ..., opts_collator = NULL)
{
if (!missing(...))
opts_collator <- do.call(stri_opts_collator, as.list(c(opts_collator, ...)))
.Call(C_stri_endswith_coll, str, pattern, to, negate, opts_collator)
} |
library(openxlsx)
library(magrittr)
library(huxtable)
doc <- openxlsx::createWorkbook()
show_add <- function(doc, ht, message) {
if (is_hux(ht)) {
caption(ht) <- message
if (caption_pos(ht) == "top") caption_pos(ht) <- "bottom"
}
sheet <- substr(message, 1, 20)
sheet <- make.names(sheet)
if (is_hux(ht)) doc <- as_Workbook(ht, Workbook = doc, sheet = sheet)
}
ht_orig <- huxtable(a = c('Foo', 'Bar', 'Baz'), b = 2:4)
ht <- ht_orig
doc %<>% show_add(ht, 'Basic table')
huxtable::bold(ht)[1, 1:2] <- TRUE
huxtable::italic(ht)[1:2, 1] <- TRUE
doc %<>% show_add(ht, 'Bold + Italic')
top_border(ht)[1,] <- 1
top_border(ht)[2,] <- 2
top_border(ht)[3,] <- 1
left_border(ht)[1,1] <- 1
right_border(ht)[2,2] <- 1
doc %<>% show_add(ht, 'Borders: second top should be thicker')
ht <- set_all_border_colors(ht, 1:2, 1, 'blue')
ht <- set_all_border_colors(ht, 2:3, 2, 'red')
doc %<>% show_add(ht, 'Border colors: left/top blue, bottom/right red')
font_size(ht)[2,2] <- 16
font(ht)[3,1] <- 'Arial'
doc %<>% show_add(ht, 'Font size and font')
ht <- hux(a = c('short', 'much longer', 'short', 'short'), b = 1:4)
align(ht)[1, 1] <- 'left'
align(ht)[2, 1] <- 'left'
align(ht)[3, 1] <- 'center'
align(ht)[4, 1] <- 'right'
doc %<>% show_add(ht, 'Horizontal alignment')
na_string(ht) <- '--'
ht[1,1] <- NA
doc %<>% show_add(ht, 'NA string --')
ht$a <- c('top', 'middle', 'bottom', 'top')
valign(ht)[,1] <- ht$a
font_size(ht)[, 2] <- 16
doc %<>% show_add(ht, 'Vertical alignment')
ht <- ht_orig
ht <- set_all_borders(ht, , , 1)
doc %<>% show_add(ht, 'Width: nothing specified')
width(ht) <- .75
col_width(ht) <- c(.7, .3)
doc %<>% show_add(ht, 'Width: .7/.3, total .75')
col_width(ht) <- c(.2, .8)
doc %<>% show_add(ht, 'Width: .2/.8, total .75')
ht <- ht_orig
background_color(ht)[1,] <- 'yellow'
background_color(ht)[1,2] <- 'orange'
background_color(ht)[2,] <- grey(.95)
background_color(ht)[3,] <- '
doc %<>% show_add(ht, 'Background color')
ht <- ht_orig
text_color(ht)[, 1] <- 'blue'
text_color(ht)[, 2] <- 'red'
doc %<>% show_add(ht, 'Text color')
ht <- ht_orig
ht <- set_all_borders(ht, 1)
colspan(ht)[2,1] <- 2
doc %<>% show_add(ht, 'Body colspan')
colspan(ht)[2,1] <- 1
rowspan(ht)[2,1] <- 2
doc %<>% show_add(ht, 'Body rowspan')
colspan(ht)[2,1] <- 2
rowspan(ht)[2,1] <- 2
doc %<>% show_add(ht, 'Body row and colspan')
ht <- hux('Long title' = 1:4, 'Long title 2' = 1:4, add_colnames = TRUE)
rotation(ht)[1, 1] <- 90
doc %<>% show_add(ht, 'Rotation 90 degrees')
ht <- ht_orig
ht[1, 1:2] <- "Some very very long long long text"
wrap(ht)[1, 1] <- TRUE
doc %<>% show_add(ht, 'wrap on and off')
ht <- ht_orig
caption_pos(ht) <- "topleft"
doc %<>% show_add(ht, 'topleft caption')
caption_pos(ht) <- "topright"
doc %<>% show_add(ht, 'topright caption')
caption_pos(ht) <- "topcenter"
doc %<>% show_add(ht, 'topcenter caption')
ht$c <- ht$d <- ht$e <- ht$f <- ht$a
caption_pos(ht) <- "top"
position(ht) <- "right"
doc %<>% show_add(ht, "caption determined by pos (right)")
saveWorkbook(doc, fp <- file.path("scripts", "openxlsx-test-output.xlsx"), overwrite = TRUE)
openXL(fp) |
yini <- c(y1=1, y2=0, y3=0)
neq <- length(yini)
parms <- c(k1 = 0.04, k2 = 3e7, k3 = 1e4)
vRober <- function(y, parms) {
dy1 <- -parms["k1"]*y[1] + parms["k3"]*y[2]*y[3]
dy2 <- parms["k1"]*y[1] - parms["k2"]*y[2]*y[2] - parms["k3"]*y[2]*y[3]
dy3 <- parms["k2"]*y[2]*y[2]
c(dy1, dy2, dy3)
}
r_rober <- function(t, y, parms, psens) vRober(y, parms)
times <- 10^(seq(from = -5, to = 11, by = 0.1))
includes <- "using namespace arma;\n
pfnd <- cppXPtr(code='
int d_robertson(double t, const vec &y, vec &ydot, RObject ¶m, NumericVector &psens) {
NumericVector p(param);
ydot[0] = -p["k1"]*y[0] + p["k3"]*y[1]*y[2];
ydot[2] = p["k2"]*y[1]*y[1];
ydot[1] = -ydot[0] - ydot[2];
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
pfnj <- cppXPtr(code='
int jac_robertson(double t, const vec &y, const vec &ydot, mat &J, RObject ¶m, NumericVector &psens, vec &tmp1, vec &tmp2, vec &tmp3) {
NumericVector p(param);
J(0, 0) = -p["k1"];
J(1, 0) = p["k1"];
J(2, 0) = 0.;
J(0, 1) = p["k3"]*y[2];
J(1, 1) = -p["k3"]*y[2]-2*p["k2"]*y[1];
J(2, 1) = 2*p["k2"]*y[1];
J(0, 2) = p["k3"]*y[1];
J(1, 2) = -p["k3"]*y[1];
J(2, 2) = 0.;
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
pfnspj <- cppXPtr(code='
int spjac_robertson(double t, const vec &y, const vec &ydot, uvec &ir, uvec &pj, vec &v, int n, int nz, RObject ¶m, NumericVector &psens, vec &tmp1, vec &tmp2, vec &tmp3) {
if (nz < 8)
stop("spjac_robertson: not enough room for non zeros, must have at least 8, instead got %d", nz);
NumericVector prm(param);
int i=0;
pj[0] = 0; // init pj
// first column
ir[i] = 0;
v[i++] = -prm["k1"];
ir[i] = 1;
v[i++] = prm["k1"];
pj[1] = i;
// second column
ir[i] = 0;
v[i++] = prm["k3"]*y[2];
ir[i] = 1;
v[i++] = -prm["k3"]*y[2]-2*prm["k2"]*y[1];
ir[i] = 2;
v[i++] = 2*prm["k2"]*y[1];
pj[2] = i;
// third column
ir[i] = 0;
v[i++] = prm["k3"]*y[1];
ir[i] = 1;
v[i++] = -prm["k3"]*y[1];
ir[i] = 2;
v[i++] = 0; // just to hold the place for a full main diagonal
pj[3] = i;
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
pfnsens1 <- cppXPtr(code='
int sens_robertson1(int Ns, double t, const vec &y, const vec &ydot, int iS, const vec &yS, vec &ySdot, RObject ¶m, NumericVector &p, vec &tmp1, vec &tmp2) {
// calculate (∂f /∂y)s_i(t) + (∂f /∂p_i) for i = iS
// (∂f /∂y)s_i(t)
//print(p);
//stop("print");
ySdot[0] = -p["k1"]*yS[0] + p["k3"]*y[2]*yS[1] + p["k3"]*y[1]*yS[2];
ySdot[1] = p["k1"]*yS[0] - (p["k3"]*y[2]+2*p["k2"]*y[1])*yS[1] - p["k3"]*y[1]*yS[2];
ySdot[2] = 2*p["k2"]*y[1]*yS[1];
// + (∂f /∂p_i)
switch(iS) {
case 0:
ySdot[0] -= y[0];
ySdot[1] += y[0];
break;
case 1:
ySdot[1] -= y[1]*y[1];
ySdot[2] += y[1]*y[1];
break;
case 2:
ySdot[0] += y[1]*y[2];
ySdot[1] -= y[1]*y[2];
}
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
outr <- r2sundials::r2cvodes(yini, times, r_rober, param=parms, maxsteps=2000)
out0 <- r2sundials::r2cvodes(yini, times, pfnd, param=parms, maxsteps=2000)
test.r_vs_cpp <- function() {
checkEqualsNumeric(out0, outr, tolerance=1.e-6, msg="equivalence of R and C++ rhs callbacks")
}
out1 <- r2sundials::r2cvodes(yini, times, pfnd, param=parms, fjac=pfnspj, nz=8, maxsteps=2000)
test.sparse <- function() {
checkEqualsNumeric(out0, out1, tolerance=1.e-6, msg="equivalence of solution with sparse Jacobian and internal cvodes Jacobian")
}
out2 <- r2sundials::r2cvodes(yini, times, pfnd, param=parms, fjac=pfnj, Ns=3, psens=parms, fsens1=pfnsens1, maxsteps=2000)
test.dense <- function() {
checkEqualsNumeric(out2, out1, tolerance=1.e-6, msg="equivalence of solutions with sparse Jacobian and dense Jacobian")
}
test.sensitivity <- function() {
checkEqualsNumeric(dim(attr(out2, "sens")), c(length(yini), length(times), 3), msg="sensitivity dimension")
}
yinib <- c(x=0, y=1, vx=0.5, vy=0)
paramb <- c(g=9.81, kx=0.1, ky=0.3, nbounce=5)
timesb <- seq(0, 3, length.out=101)
pball <- cppXPtr(code='
int d_ball(double t, const vec &y, vec &ydot, RObject ¶m, NumericVector &psens) {
NumericVector p(param);
ydot[0] = y[2];
ydot[1] = y[3];
ydot[2] = y[1] > 0 ? 0. : -y[2]; // falling till y=0 then damping
ydot[3] = y[1] > 0 ? -p["g"] : -y[3]; // falling till y=0 then damping
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
proot <- cppXPtr(code='
int root_ball(double t, const vec &y, vec &vroot, RObject ¶m, NumericVector &psens) {
vroot[0] = y[1]; // y==0
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
pevt <- cppXPtr(code='
int event_ball(double t, const vec &y, vec &ynew, int Ns, std::vector<vec> &ySv, const ivec &rootsfound, RObject ¶m, NumericVector &psens) {
NumericVector p(param);
static int nbounce=0;
if (y[3] > 0) // we cross 0 in ascending trajectory, it can happen when y < 0 in limits of abstol
return(R2SUNDIALS_EVENT_IGNORE);
ynew=y;
if (++nbounce < p["nbounce"]) {
// here nbounce=1:4
ynew[2] *= 1.-p["kx"]; // horizontal speed is lowered
ynew[3] *= -(1.-p["ky"]); // vertical speed is lowered and reflected
return(R2SUNDIALS_EVENT_HOLD);
} else {
// here nbounce=5
nbounce=0; // reinit counter for possible next calls to cvode
return(R2SUNDIALS_EVENT_STOP);
}
}
', depends=c("RcppArmadillo", "r2sundials", "rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
outb <- r2sundials::r2cvodes(yinib, timesb, pball, paramb, nroot=1, froot=proot, fevent=pevt)
test.root.cpp <- function() {
checkEqualsNumeric(dim(attr(outb, "roots")), c(2, 5), msg="root finding")
}
rhs_ball_r <- function(t, y, p, psens) {
ydot <- y
ydot[1] <- y[3];
ydot[2] <- y[4];
ydot[3] <- if (y[2] > 0) 0. else -y[3]
ydot[4] <- if (y[2] > 0) -p["g"] else -y[4]
return(ydot)
}
root_ball_r <- function(t, y, p, psens) y[2]
event_ball_r <- local({
nbounce <- 0
function(t, y, Ns, ySm, rootsfound, p, psens) {
if (y[4] > 0)
return(list(flag=R2SUNDIALS_EVENT_IGNORE, ynew=y))
nbounce <<- nbounce + 1
ynew <- y;
if (nbounce < p["nbounce"]) {
ynew[3] <- ynew[3]*(1.-p["kx"])
ynew[4] <- -ynew[4]*(1.-p["ky"])
return(list(flag=R2SUNDIALS_EVENT_HOLD, ynew=ynew))
} else {
nbounce <<- 0
return(list(flag=R2SUNDIALS_EVENT_STOP, ynew=ynew))
}
}
})
outbr <- r2sundials::r2cvodes(yinib, timesb, rhs_ball_r, paramb, nroot=1, froot=root_ball_r, fevent=event_ball_r)
test.root.r <- function() {
checkEqualsNumeric(outb, outbr, msg="root finding in R")
checkEqualsNumeric(dim(attr(outbr, "roots")), c(2, 5), msg="dim root finding in R")
}
pexp <- cppXPtr(code='
int d_exp(double t, const vec &y, vec &ydot, RObject ¶m, NumericVector &psens) {
ydot[0] = -psens["nu"]*(y[0]-psens["lim"]);
return(CV_SUCCESS);
}
', depends=c("RcppArmadillo","r2sundials","rmumps"), includes=includes, cacheDir="lib", verbose=FALSE)
par_exp <- c("nu"=1, "lim"=1)
ti <- seq(0, 5, length.out=11)
oute <- r2sundials::r2cvodes(0., ti, pexp, Ns=2, psens=par_exp)
test.expdecay <- function() {
theor <- par_exp["lim"]-exp(-par_exp["nu"]*ti)
checkEqualsNumeric(oute[1,], theor, tolerance=1.e-6, msg="numeric precision in exp decay")
} |
immer_IRT_likelihood_gpcm_helper <- function(theta, b, a, dat, dat_resp=NULL)
{
dat <- as.matrix(dat)
if ( is.null(dat_resp) ){
dat_resp <- 1 - is.na(dat)
}
dat_resp <- as.matrix(dat_resp)
dat[ is.na(dat) ] <- 0
b <- as.matrix(b)
K <- ncol(b)
TP <- length(theta)
probs <- immer_gpcm_calc_probs( theta=theta, b=b, a=a )
like <- immer_irt_likelihood_gpcm( probs=probs, dat=dat, dat_resp=dat_resp, TP=TP, K=K )
attr(like, "theta") <- theta
attr(like, "prob.theta") <- NA
attr(like, "skillspace") <- NA
attr(like, "G") <- NA
return(like)
} |
leafletGeo = function(mapName,
dat = NULL,
namevar = NULL,
valuevar = NULL){
countries <- readGeoLocal(mapName)
countries$popup = countries$name
if(is.null(dat)){
return(
countries
)
}else{
if(class(dat) != 'data.frame'){
stop("dat should be a data.frame")
}
if(is.null(namevar)){
name = dat[, 1] %>% toLabel()
}else{
name = evalFormula(namevar,dat)
}
name = as.character(name) %>% toLabel()
if(is.null(valuevar)){
value = dat[, 2]
}else{
value = evalFormula(valuevar,dat)
}
countries <- readGeoLocal(mapName)
countries$label = toLabel(countries$name)
index = sapply(countries$label,function(x) which(name==x)[1])
countries$value = value[index]
countries$popup = countries$name
return(
countries
)
}
} |
SpatialPixelsDataFrame = function(points, data,
tolerance = sqrt(.Machine$double.eps),
proj4string = CRS(as.character(NA)), round = NULL, grid = NULL) {
if (is.null(points))
stop("points argument is NULL")
if (is(points, "SpatialPixels") && is.null(grid))
grid = points@grid
if (!is(points, "SpatialPoints"))
points = SpatialPoints(points, proj4string = proj4string)
points = SpatialPixels(points, tolerance = tolerance, round = round,
grid = grid)
new("SpatialPixelsDataFrame", points, data = data)
}
SpatialGridDataFrame = function(grid, data, proj4string = CRS(as.character(NA))) {
if (!is(grid, "SpatialGrid"))
grid = SpatialGrid(grid, proj4string)
new("SpatialGridDataFrame", grid, data = data)
}
setMethod("addAttrToGeom", signature(x = "SpatialPixels", y = "data.frame"),
function(x, y, match.ID, ...)
SpatialPixelsDataFrame(geometry(x), y, ...)
)
setMethod("addAttrToGeom", signature(x = "SpatialGrid", y = "data.frame"),
function(x, y, match.ID, ...)
SpatialGridDataFrame(geometry(x), y, ...)
)
as.SPixDF.SGDF = function(from) {
data = list()
n = .NumberOfCells(from@grid)
for (i in seq_along(from@data)) {
v = vector(mode(from@data[[i]]), n)
if (is.factor(from@data[[i]]))
v = factor(rep(NA, n), levels = levels(from@data[[i]]))
else
v[[email protected]] = NA
v[[email protected]] = from@data[[i]]
data[[i]] = v
}
data = data.frame(data, stringsAsFactors = FALSE)
names(data) = names(from@data)
SpatialGridDataFrame(from@grid, data, rebuild_CRS(slot(from, "proj4string")))
}
pix2grid = function(from) {
n = .NumberOfCells(from@grid)
data = data.frame(matrix(nrow = n, ncol = ncol(from@data)))
data[[email protected],] = from@data
names(data) = names(from@data)
fids = which(sapply(from@data, is.factor))
if (length(fids) > 0) {
for (fi in fids) {
v = vector(mode(from@data[[fi]]), n)
v = factor(rep(NA, n), levels = levels(from@data[[fi]]))
v[[email protected]] = from@data[[fi]]
data[,fi] = v
}
}
SpatialGridDataFrame(from@grid, data,
rebuild_CRS(slot(from, "proj4string")))
}
setAs("SpatialPixelsDataFrame", "SpatialGridDataFrame", pix2grid)
as.SGDF.SPixDF = function(from) {
sel = apply(sapply(from@data, is.na), 1, function(x) !all(x))
if (!any(sel)) {
warning("complete map seems to be NA's -- no selection was made")
sel = rep(TRUE, length(sel))
}
new("SpatialPixelsDataFrame",
new("SpatialPixels",
new("SpatialPoints", coords = coordinates(from)[sel,,drop=FALSE],
bbox = from@bbox, proj4string = from@proj4string),
grid = from@grid,
grid.index = which(sel)),
data = from@data[sel,,drop=FALSE])
}
setAs("SpatialGridDataFrame", "SpatialPixelsDataFrame", as.SGDF.SPixDF)
setAs("SpatialGridDataFrame", "SpatialPointsDataFrame",
function(from) as(as(from, "SpatialPixelsDataFrame"), "SpatialPointsDataFrame"))
setMethod("coordinates", "SpatialPixelsDataFrame",
function(obj) coordinates(as(obj, "SpatialPixels")))
setMethod("coordinates", "SpatialGridDataFrame",
function(obj) coordinates(as(obj, "SpatialGrid")))
row.names.SpatialGridDataFrame <- function(x) {
row.names(x@data)
}
as.SpPixDF.SpPoiDF = function(from)
new("SpatialPointsDataFrame", as(from, "SpatialPoints"),
data = from@data, coords.nrs = [email protected])
setAs("SpatialPixelsDataFrame", "SpatialPointsDataFrame", as.SpPixDF.SpPoiDF)
as.SpatialPolygonsDataFrame.SpatialPixelsDataFrame = function(from) {
df <- from@data
SP <- as(from, "SpatialPolygons")
row.names(df) <- row.names(SP)
SpatialPolygonsDataFrame(SP, df)
}
setAs("SpatialPixelsDataFrame", "SpatialPolygonsDataFrame",
as.SpatialPolygonsDataFrame.SpatialPixelsDataFrame)
as.matrix.SpatialPixelsDataFrame = function(x, ...) {
x = as(x, "SpatialGridDataFrame")
as.matrix(x, ...)
}
as.array.SpatialGridDataFrame = function(x,...) {
d = gridparameters(x)$cells.dim
if (ncol(x@data) > 1)
d = c(d, ncol(x@data))
array(do.call(c, x@data), dim = d)
}
setAs("SpatialGridDataFrame", "array", function(from)
as.array.SpatialGridDataFrame(from))
setAs("SpatialPixelsDataFrame", "array", function(from)
as(as(from, "SpatialGridDataFrame"), "array"))
as.matrix.SpatialGridDataFrame = function(x, ..., byrow = FALSE) {
if (ncol(x@data) > 1)
warning(
"as.matrix.SpatialGridDataFrame uses first column;\n use subset or [] for other columns")
if (byrow)
matrix(x@data[[1]], x@[email protected][2], x@[email protected][1], byrow=byrow)
else
matrix(x@data[[1]], x@[email protected][1], x@[email protected][2], byrow=byrow)
}
setAs("SpatialPixelsDataFrame", "matrix", function(from)
as.matrix.SpatialPixelsDataFrame(from))
setAs("SpatialGridDataFrame", "matrix", function(from)
as.matrix.SpatialGridDataFrame(from))
as.data.frame.SpatialPixelsDataFrame = function(x, row.names, optional, ...)
as.data.frame(as(x, "SpatialPointsDataFrame"))
as.data.frame.SpatialGridDataFrame = function(x, row.names, optional, ...)
as.data.frame(as(x, "SpatialPixelsDataFrame"))
setAs("SpatialPixelsDataFrame", "data.frame", function(from)
as.data.frame.SpatialPixelsDataFrame(from))
setAs("SpatialGridDataFrame", "data.frame", function(from)
as.data.frame.SpatialGridDataFrame(from))
setMethod("[", "SpatialPixelsDataFrame", function(x, i, j, ... , drop = FALSE) {
grid = x@grid
x = as(x, "SpatialPointsDataFrame")
missing.i = missing(i)
missing.j = missing(j)
nargs = nargs()
if (missing.i && missing.j) {
i = TRUE
j = TRUE
} else if (missing.j && !missing.i) {
if (nargs == 2) {
j = i
i = TRUE
} else {
j = TRUE
}
} else if (missing.i && !missing.j)
i = TRUE
if (is.matrix(i))
stop("matrix argument not supported in SpatialPointsDataFrame selection")
if (is(i, "Spatial"))
i = !is.na(over(x, geometry(i)))
if (any(is.na(i)))
stop("NAs not permitted in row index")
x@coords = x@coords[i, , drop = FALSE]
if (nrow(x@coords))
x@bbox = .bboxCoords(x@coords)
x@data = x@data[i, j, ..., drop = FALSE]
if (drop)
gridded(x) = TRUE
else
gridded(x) = list(TRUE, grid)
x
})
subs.SpatialGridDataFrame <- function(x, i, j, ... , drop = FALSE) {
n.args = nargs()
dots = list(...)
if (drop)
stop("argument drop needs to be FALSE")
missing.i = missing(i)
missing.j = missing(j)
if (length(dots) > 0) {
missing.k = FALSE
k = dots[[1]]
} else
missing.k = TRUE
if (missing.i && missing.j && missing.k)
return(x)
grd = x@grid
if (missing.k) {
k = TRUE
if (missing.j && n.args != 3) {
x@data = x@data[ , i, drop = FALSE]
return(x)
}
} else if (missing.j && n.args == 2) {
x@data = x@data[ , k, drop = FALSE]
return(x)
}
if (missing.i)
rows = 1:[email protected][2]
else {
if (is(i, "Spatial"))
i = !is.na(over(x, geometry(i)))
if (is.integer(i)) {
if ((length(i) > [email protected][2] && length(i) < nrow(x@data))
|| max(i) > [email protected][2]) {
if (all(i < 0)) {
i = -i
negate = TRUE
} else
negate = FALSE
i = (1:nrow(x@data)) %in% i
if (negate)
i = !i
}
}
if (length(i) == nrow(x@data)) {
if (!missing.j)
x@data = x@data[j]
x@data = data.frame(lapply(x@data, function(C) { C[!i] = NA; C }))
return(x)
}
rows = i
}
if (missing.j)
cols = 1:[email protected][1]
else
cols = j
idx = 1:prod([email protected][1:2])
m = matrix(idx, [email protected][2], [email protected][1], byrow = TRUE)[rows,cols]
idx = as.vector(m)
if (any(is.na(idx)))
stop("NAs not permitted in index")
if (length(idx) == 0) {
x@data = x@data[,k,drop=FALSE]
x@data[] = NA
return(x)
}
pts = SpatialPoints(coordinates(x)[idx,,drop=FALSE],
rebuild_CRS(slot(x, "proj4string")))
if (length(idx) == 1)
SpatialPointsDataFrame(pts, x@data[idx, k, drop = FALSE])
else {
res = SpatialPixelsDataFrame(SpatialPixels(pts), x@data[idx, k, drop = FALSE])
as(res, "SpatialGridDataFrame")
}
}
setMethod("[", "SpatialGridDataFrame", subs.SpatialGridDataFrame)
cbind.SpatialGridDataFrame = function(...) {
stop.ifnot.equal = function(a, b) {
res = all.equal(getGridTopology(a), getGridTopology(b))
if (!is.logical(res) || !res)
stop("topology is not equal")
}
grds = list(...)
ngrds = length(grds)
if (ngrds < 1)
stop("no arguments supplied")
if (ngrds == 1)
return(grds[[1]])
sapply(grds[2:ngrds], function(x) stop.ifnot.equal(x, grds[[1]]))
gr = grds[[1]]
gr@data = do.call(cbind, lapply(grds, function(x) x@data))
proj4string(gr) = rebuild_CRS(slot(grds[[1]], "proj4string"))
gr
}
print.SpatialPixelsDataFrame = function(x, ...) {
cat("Object of class SpatialPixelsDataFrame\n")
print(as(x, "SpatialPixels"))
if (length(x) > 0) {
cat("\n")
cat("Data summary:\n")
if (ncol(x@data) > 0)
print(summary(x@data))
}
invisible(x)
}
setMethod("show", "SpatialPixelsDataFrame",
function(object) print.SpatialPixelsDataFrame(object))
print.SpatialGridDataFrame = function(x, ...) {
cat("Object of class SpatialGridDataFrame\n")
print(as(x, "SpatialGrid"))
if (length(x) > 0) {
cat("\n")
cat("Data summary:\n")
if (ncol(x@data) > 1)
sobj = summary(x@data)
else sobj = summary(x@data[[1]])
print(sobj)
}
invisible(x)
}
setMethod("show", "SpatialGridDataFrame",
function(object) print.SpatialGridDataFrame(object))
names.SpatialPixelsDataFrame = function(x) names(x@data)
names.SpatialGridDataFrame = function(x) names(x@data)
checkNames = function(x) {
if (!identical(x, make.names(x)))
warning("attempt to set invalid names: this may lead to problems later on. See ?make.names")
}
"names<-.SpatialPixelsDataFrame" = function(x,value) { checkNames(value); names(x@data) = value; x }
"names<-.SpatialGridDataFrame" = function(x,value) { checkNames(value); names(x@data) = value; x }
dim.SpatialPixelsDataFrame = function(x) dim(x@data)
dim.SpatialGridDataFrame = function(x) dim(x@data)
setMethod("split", "SpatialPixelsDataFrame", split.data.frame)
setMethod("geometry", "SpatialGridDataFrame",
function(obj) as(obj, "SpatialGrid"))
setMethod("geometry", "SpatialPixelsDataFrame",
function(obj) as(obj, "SpatialPixels"))
setAs("SpatialGridDataFrame", "SpatialPolygonsDataFrame",
function(from) {
fullgrid(from) = FALSE
as(from, "SpatialPolygonsDataFrame")
}
)
length.SpatialPixelsDataFrame = function(x) { nrow(x@coords) }
length.SpatialGridDataFrame = function(x) { .NumberOfCells(x@grid) }
image.scale <- function(z, zlim, col = heat.colors(12), breaks, axis.pos=1, add.axis = TRUE,
at = NULL, shrink = 0, ...) {
stopifnot(!is.factor(z))
if (!missing(breaks) && length(breaks) != (length(col) + 1))
stop("must have one more break than colour")
if (missing(zlim))
zlim <- range(z, na.rm=TRUE)
if (missing(breaks))
breaks <- seq(zlim[1], zlim[2], length.out = length(col) + 1)
Shrink = function(r, s) {
w = diff(r)
c(r[1] - 0.5 * s * w, r[2] + 0.5 * s * w)
}
if (axis.pos %in% c(1,3)) {
ylim <- c(0, 1)
xlim <- Shrink(range(breaks), shrink)
}
if (axis.pos %in% c(2,4)) {
ylim <- Shrink(range(breaks), shrink)
xlim <- c(0, 1)
}
poly <- vector(mode="list", length(col))
for (i in seq(poly))
poly[[i]] <- c(breaks[i], breaks[i+1], breaks[i+1], breaks[i])
plot(1,1,t="n", ylim = ylim, xlim = xlim, axes = FALSE,
xlab = "", ylab = "", xaxs = "i", yaxs = "i", ...)
for(i in seq(poly)) {
if (axis.pos %in% c(1,3))
polygon(poly[[i]], c(0,0,1,1), col=col[i], border=NA)
if (axis.pos %in% c(2,4))
polygon(c(0,0,1,1), poly[[i]], col=col[i], border=NA)
}
if (shrink > 0) {
if (is.null(at))
at = pretty(breaks)
b = c(breaks[1], breaks[length(breaks)])
if (axis.pos %in% c(1,3))
lines(y = c(0,1,1,0,0), x = c(b[1],b[1],b[2],b[2],b[1]))
if (axis.pos %in% c(2,4))
lines(x = c(0,1,1,0,0), y = c(b[1],b[1],b[2],b[2],b[1]))
} else
box()
if (add.axis)
axis(axis.pos, at)
}
image.scale.factor <- function(z, col = heat.colors(nlevels(z)), axis.pos = 1, scale.frac = 0.3,
scale.n = 15, ...) {
stopifnot(is.factor(z))
stopifnot(axis.pos %in% c(1,4))
frc = scale.frac
stre = scale.n
plot(1, 1, t="n", ylim = c(0,1), xlim = c(0,1), axes = FALSE,
xlab = "", ylab = "", xaxs = "i", yaxs = "i", ...)
n = nlevels(z)
if (n != length(col))
stop("
lb = (1:n - 0.5)/max(n, stre)
poly <- vector(mode="list", length(col))
breaks = (0:n) / max(n, stre)
if (n < stre) {
breaks = breaks + (stre - n)/(2 * stre)
lb = lb + (stre - n)/(2 * stre)
}
for (i in seq(poly))
poly[[i]] <- c(breaks[i], breaks[i+1], breaks[i+1], breaks[i])
for(i in seq(poly)) {
if (axis.pos %in% c(1,3))
polygon(poly[[i]], c(1,1,1-frc,1-frc), col=col[i], border=NA)
if (axis.pos %in% c(2,4))
polygon(c(0,0,frc,frc), poly[[i]], col=col[i], border=NA)
}
b = c(breaks[1], breaks[length(breaks)])
if (axis.pos %in% c(1,3)) {
lines(y = c(1,1-frc,1-frc,1,1), x = c(b[1],b[1],b[2],b[2],b[1]))
text(y = (1-frc)/1.05, x = lb, levels(z), pos = axis.pos)
}
if (axis.pos %in% c(2,4)) {
lines(x = c(0,frc,frc,0,0), y = c(b[1],b[1],b[2],b[2],b[1]))
text(x = 1.05 * frc, y = lb, levels(z), pos = axis.pos)
}
}
plot.SpatialGridDataFrame = function(x, ..., attr = 1, col, breaks,
zlim = range(as.numeric(x[[attr]])[is.finite(x[[attr]])]),
axes = FALSE, xaxs = "i", yaxs = xaxs, at = NULL,
border = NA, axis.pos = 4, add.axis = TRUE, what = "both", scale.size = lcm(2.8),
scale.shrink = 0, scale.frac = 0.3, scale.n = 15) {
if (missing(col)) {
if (is.factor(x[[1]]))
col = RColorBrewer::brewer.pal(nlevels(x[[1]]), "Set2")
else
col = bpy.colors(100)
}
image.args = list(x = x, col = col, zlim = zlim, axes = axes, xaxs = xaxs, yaxs = yaxs, ...)
if (all(c("red", "green", "blue") %in% names(image.args)))
what = "image"
else
image.args$x = x[1]
if (!missing(breaks))
image.args$breaks = breaks
si = scale.size
if (what == "both")
switch (axis.pos,
layout(matrix(c(2,1), nrow=2, ncol=1), widths=1, heights=c(1,si)),
layout(matrix(c(1,2), nrow=1, ncol=2), widths=c(si,1), heights=1),
layout(matrix(c(1,2), nrow=2, ncol=1), widths=1, heights=c(si,1)),
layout(matrix(c(2,1), nrow=1, ncol=2), widths=c(1,si), heights=1)
)
if (what %in% c("both", "scale")) {
mar = c(1,1,1,1)
if (! is.factor(x[[1]]))
mar[axis.pos] = 3
if (axes && axis.pos %in% c(2,4))
mar[1] = 3
if (axes && axis.pos %in% c(1,3))
mar[2] = 3
par(mar = mar)
if (is.factor(x[[1]]))
image.scale.factor(x[[1]], col = col, axis.pos = axis.pos, scale.frac = scale.frac,
scale.n = scale.n)
else
image.scale(x[[1]], zlim = zlim, col = col, breaks = breaks, axis.pos = axis.pos,
add.axis = add.axis, at = at, shrink = scale.shrink)
}
if (what %in% c("both", "image")) {
if (is.factor(x[[1]]))
image.args$x[[1]] = as.numeric(x[[1]])
mar=c(1,1,1,1)
if (axes)
mar[1:2] = 3
par(mar = mar)
do.call(image, image.args)
if (!is.na(border))
plot(geometry(x), col = border, add = TRUE)
}
}
setMethod("plot", signature(x = "SpatialGridDataFrame", y = "missing"),
function(x,y,...) plot.SpatialGridDataFrame(x,...))
setMethod("plot", signature(x = "SpatialPixelsDataFrame", y = "missing"),
function(x,y,...) plot.SpatialGridDataFrame(x,...)) |
predict.aidsEst <- function( object, newdata = NULL,
observedShares = FALSE, ... ) {
if( is.null( newdata ) ) {
newdata <- eval( object$call$data )
}
if( object$method == "LA" ) {
if( observedShares ) {
priceIndex <- aidsPx( priceIndex = object$priceIndex,
priceNames = object$priceNames,
data = newdata,
shareNames = object$shareNames,
base = list( prices = object$basePrices, shares = object$baseShares ),
coef = coef( object ), shifterNames = object$shifterNames )
} else {
priceIndex <- object$priceIndex
}
} else if( object$method %in% c( "IL", "MK" ) ) {
priceIndex <- "TL"
} else {
stop( "unknown element 'method' of argument 'object'" )
}
result <- aidsCalc( priceNames = object$priceNames,
totExpName = object$totExpName,
coef = coef( object ),
data = newdata,
priceIndex = priceIndex,
basePrices = object$basePrices,
baseShares = object$baseShares )
return( result )
} |
VCOV.calc <-
function(object){
P<-length(object$Beta)
L<-length(object$gl)
N<-nrow(object$sdata)
hess<-99
if(prod(object$gl>0)==1){
try1<-try(solve(-object$Hessian),silent=TRUE)
if(!is.character(try1) & prod(is.finite(try1))==1){
vcov.bg<-try1[1:P,1:P]
hess<-0
}else{
try2<-try(qr.solve(-object$Hessian),silent=TRUE)
if(!is.character(try2) & prod(is.finite(try2))==1){
vcov.bg<-try2[1:P,1:P]
hess<-1
}
}
}
if(hess==99){
v<--object$Hessian
A = v[1:P, 1:P]
B = v[1:P, (P + 1):(P + L)]
C = v[(P + 1):(P + L), 1:P]
D = v[(P + 1):(P + L), (P + 1):(P + L)]
vcov.bg = try(ginv(A - B %*% ginv(D) %*% C),silent=TRUE)
if(!is.character(vcov.bg) & prod(is.finite(vcov.bg))==1) hess<-2
}
if(hess==99){
x0<-c(object$Beta,object$gl)
Hessian<-try(hessian(f=loglik,x0=x0,sdata=object$sdata,Xp=object$Xp,r=object$r,bl.Li=object$bl.Li,bl.Ri=object$bl.Ri),silent=TRUE)
VCOV<-diag(solve(-Hessian))
numer.bg<-try(solve(-Hessian),silent=TRUE)
if(!is.character(numer.bg)){vcov.bg=diag(numer.bg)[1:P]; hess<-3}
}
return(list(vcov.bg=vcov.bg,hess=hess))
} |
NULL
sdf_register.spatial_rdd <- function(x, name = NULL) {
as.spark.dataframe(x, name = name)
}
as.spark.dataframe <- function(x, non_spatial_cols = NULL, name = NULL) {
sc <- spark_connection(x$.jobj)
sdf <- invoke_static(
sc,
"org.apache.sedona.sql.utils.Adapter",
"toDf",
x$.jobj,
as.list(non_spatial_cols),
spark_session(sc)
)
sdf_register(sdf, name)
} |
context("DGEobj - tests for annotate.R functions")
test_that('annotate.R: annotateDGEobj()', {
ann.file <- tempfile("annotations_test", fileext = ".txt")
writeLines(c("key1='value 1'", "key2=value 2"), con = ann.file)
ann_DGEobj <- annotateDGEobj(t_obj, ann.file)
expect_equal(attr(ann_DGEobj, 'key1'), "'value 1'")
expect_equal(attr(ann_DGEobj, 'key2'), 'value 2')
expect_null(attr(ann_DGEobj, 'key3'))
ann_DGEobj <- annotateDGEobj(t_obj, ann.file, keys = list("key2"))
expect_null(attr(ann_DGEobj, 'key1'))
expect_equal(attr(ann_DGEobj, 'key2'), 'value 2')
ann.list <- list("key1" = "'value 1'", "key2" = "value 2")
ann_DGEobj <- annotateDGEobj(t_obj, ann.list)
expect_equal(attr(ann_DGEobj, 'key1'), "'value 1'")
expect_equal(attr(ann_DGEobj, 'key2'), 'value 2')
expect_null(attr(ann_DGEobj, 'key3'))
ann_DGEobj <- annotateDGEobj(t_obj, ann.list, keys = list("key2"))
expect_null(attr(ann_DGEobj, 'key1'))
expect_equal(attr(ann_DGEobj, 'key2'), 'value 2')
})
test_that('annotate.R: incorrect usage', {
expect_error(annotateDGEobj(t_obj),
regexp = "argument \"annotations\" is missing, with no default")
expect_error(annotateDGEobj(t_obj, NULL),
regexp = "When annotations is NULL, no attribute gets added to the dgeObj.")
expect_error(annotateDGEobj(t_obj, "nonexistantfile.txt"),
regexp = "The file specified does not exist.")
}) |
context("Test 15: check BL=0 case for affcd is same as for aff")
test_that("check 1, setting streamEstSigma", {
numChecks <- 5
showChecks <- F
etaval <- 0.01
alphaval <- 0.01
BLval <- 0
aff1 <- initAFFMean(eta=etaval)
affcd1 <- initAFFMeanCD(eta=etaval, alpha=alphaval, BL=BLval)
affcd1$streamEstMean <- 0
affcd1$streamEstSigma <- 1
seednum <- 3
regimeLength <- 100
numChanges <- 3
delta <- 3
sigma <- 1
numChanges <- 3
N <- (regimeLength) * (numChanges + 1)
stepChanges <- rep(c(0:numChanges), each=regimeLength) * delta * sigma
set.seed(seednum)
stream <- rnorm(N, mean=0, sd=sigma) + stepChanges
lambda <- rep(0, length(stream))
lambdaCD <- rep(0, length(stream))
lambdaDeriv <- rep(0, length(stream))
lambdaCDDeriv <- rep(0, length(stream))
affmean <- rep(0, length(stream))
affmeanCD <- rep(0, length(stream))
t <- seq_along(stream)
for (i in t ){
obs <- stream[i]
aff1$update(obs)
affcd1$update(obs)
lambda[i] <- aff1$lambda
lambdaCD[i] <- affcd1$lambda
affmean[i] <- aff1$xbar
affmeanCD[i] <- affcd1$affxbar
lambdaDeriv[i] <- aff1$Lderiv
lambdaCDDeriv[i] <- affcd1$Lderiv
}
endCheck <- length(stream)
startCheck <- endCheck - numChecks + 1
for ( j in seq(from=startCheck, to=endCheck, by=1) ){
expect_equal(lambda[j], lambdaCD[j])
expect_equal(lambdaDeriv[j], lambdaCDDeriv[j])
expect_equal(affmean[j], affmeanCD[j])
if (showChecks){
cat("\n\n Test1 \n")
cat(j, ": ", lambda[j], ", ", lambdaCD[j], ", ",
lambda[j]==lambdaCD[j], "\n")
cat(j, ": ", lambdaDeriv[j], ", ", lambdaCDDeriv[j], ", ",
lambdaDeriv[j]==lambdaCDDeriv[j], "\n")
cat(j, ": ", affmean[j], ", ", affmeanCD[j], ", ",
affmean[j]==affmeanCD[j], "\n")
}
}
})
test_that("check 2, NOT setting streamEstSigma", {
numChecks <- 5
showChecks <- F
etaval <- 0.01
alphaval <- 0.01
BLval <- 0
aff1 <- initAFFMean(eta=etaval)
affcd1 <- initAFFMeanCD(eta=etaval, alpha=alphaval, BL=BLval)
affcd1$streamEstMean <- 0
seednum <- 3
regimeLength <- 100
numChanges <- 3
delta <- 3
sigma <- 1
numChanges <- 3
N <- (regimeLength) * (numChanges + 1)
stepChanges <- rep(c(0:numChanges), each=regimeLength) * delta * sigma
set.seed(seednum)
stream <- rnorm(N, mean=0, sd=sigma) + stepChanges
lambda <- rep(0, length(stream))
lambdaCD <- rep(0, length(stream))
lambdaDeriv <- rep(0, length(stream))
lambdaCDDeriv <- rep(0, length(stream))
affmean <- rep(0, length(stream))
affmeanCD <- rep(0, length(stream))
t <- seq_along(stream)
for (i in t ){
obs <- stream[i]
aff1$update(obs)
affcd1$update(obs)
lambda[i] <- aff1$lambda
lambdaCD[i] <- affcd1$lambda
affmean[i] <- aff1$xbar
affmeanCD[i] <- affcd1$affxbar
lambdaDeriv[i] <- aff1$Lderiv
lambdaCDDeriv[i] <- affcd1$Lderiv
}
endCheck <- length(stream)
startCheck <- endCheck - numChecks + 1
for ( j in seq(from=startCheck, to=endCheck, by=1) ){
expect_equal(lambda[j], lambdaCD[j])
expect_equal(lambdaDeriv[j], lambdaCDDeriv[j])
expect_equal(affmean[j], affmeanCD[j])
if (showChecks){
cat("\n\n Test2 \n")
cat(j, ": ", lambda[j], ", ", lambdaCD[j], ", ",
lambda[j]==lambdaCD[j], "\n")
cat(j, ": ", lambdaDeriv[j], ", ", lambdaCDDeriv[j], ", ",
lambdaDeriv[j]==lambdaCDDeriv[j], "\n")
cat(j, ": ", affmean[j], ", ", affmeanCD[j], ", ",
affmean[j]==affmeanCD[j], "\n")
}
}
}) |
causality <-
function(x, cause = NULL, vcov.=NULL, boot=FALSE, boot.runs=100){
if(!(class(x)=="varest")){
stop("\nPlease provide an object of class 'varest', generated by 'var()'.\n")
}
K <- x$K
p <- x$p
obs <- x$obs
type <- x$type
obj.name <- deparse(substitute(x))
y <- x$y
y.names <- colnames(x$y)
if(is.null(cause)){
cause <- y.names[1]
warning("\nArgument 'cause' has not been specified;\nusing first variable in 'x$y' (", cause, ") as cause variable.\n")
} else {
if(!all(cause%in%y.names)) stop("Argument cause does not match variables names.\n")
}
y1.names <- subset(y.names, subset = y.names %in% cause)
y2.names <- subset(y.names, subset = !(y.names %in% cause))
Z <- x$datamat[, -c(1 : K)]
xMlm<-toMlm(x)
PI <- coef(xMlm)
PI.vec <- as.vector(PI)
R2<-matrix(0, ncol=ncol(PI), nrow=nrow(PI))
g<-which(gsub("\\.l\\d+", "", rownames(PI))%in%cause)
j<-which(colnames(PI)%in%cause)
R2[g,-j]<-1
if (!is.null(x$restrictions)) {
xr <- t(x$restrictions)
xr <- abs(xr - 1)
rownames(xr)[rownames(xr) == "const"] <- "(Intercept)"
xr <- xr[rownames(PI), colnames(PI)]
xr <- xr + R2
xr[xr == 2] <- 1
R2 <- xr
}
w<-which(as.vector(R2)!=0)
N <- length(w)
R<-matrix(0, ncol=ncol(PI)*nrow(PI), nrow=N)
for(i in 1:N) R[i,w[i]]<-1
if (is.null(vcov.)) {
sigma.pi <- vcov(xMlm)
} else if (is.function(vcov.)) {
sigma.pi <- vcov.(xMlm)
} else {
sigma.pi <- vcov.
}
df1 <- p * length(y1.names) * length(y2.names)
df2 <- K * obs - length(PI)
STATISTIC <- t(R %*% PI.vec) %*% solve(R %*% sigma.pi %*% t(R)) %*% R %*% PI.vec / N
if(boot){
co.names<-Bcoef(x)
k<-which(gsub("\\.l\\d+", "", colnames(co.names))%in%cause)
l<-which(rownames(co.names)%in%cause)
R2inv<-matrix(1, ncol=nrow(PI), nrow=ncol(PI))
R2inv[-l,k]<-0
if (!is.null(x$restrictions)) {
xr <- x$restrictions
xr <- xr[rownames(co.names), colnames(co.names)]
R2inv <- xr * R2inv
}
xres<-restrict(x, method = "man", resmat = R2inv)
pred<-sapply(xres$varresult,predict)
res<-residuals(xres)
if(is.null(vcov.)){
if (is.null(x$restrictions)) {
Zmlm<-model.matrix(xMlm)
cross<-crossprod(Zmlm)
inside<-solve(R %*% sigma.pi %*% t(R))
boot.fun<-function(x=1){
Ynew<-pred+res*rnorm(n=obs, mean=0, sd=x)
PI.boot<-solve(cross, crossprod(Zmlm,Ynew))
PI.boot.vec<-as.vector(PI.boot)
t(R %*% PI.boot.vec) %*% inside %*% (R %*% PI.boot.vec) / N
}
} else {
xtmp <- x
boot.fun <- function(x = 1) {
xtmp$datamat[,1:K] <- pred + res * rnorm(n = obs, mean = 0, sd = x)
xMlm.boot <- toMlm(xtmp)
sigma.pi.boot <- vcov(xMlm.boot)
PI.boot.vec <- as.vector(coef(xMlm.boot))
t(R %*% PI.boot.vec) %*% solve(R %*% sigma.pi.boot %*% t(R)) %*% R %*% PI.boot.vec / N
}
}
} else {
xtmp <- x
boot.fun<-function(x=1){
xtmp$datamat[,1:K]<-pred+res*rnorm(n=obs, sd=x, mean=0)
xMlm.boot <- toMlm(xtmp)
if (is.function(vcov.)) {
sigma.pi.boot <- vcov.(xMlm.boot)
} else {
sigma.pi.boot <- vcov.
warning("vcov. should be function, not an object, when used with boot=TRUE")
}
PI.boot.vec <- as.vector(coef(xMlm.boot))
t(R %*% PI.boot.vec) %*% solve(R %*% sigma.pi.boot %*% t(R)) %*% R %*% PI.boot.vec / N
}
}
res.rep<-replicate(boot.runs, boot.fun(x=1))
pval<-mean(res.rep>as.numeric(STATISTIC))
}
names(STATISTIC) <- "F-Test"
if(!boot){
PARAMETER1 <- df1
PARAMETER2 <- df2
names(PARAMETER1) <- "df1"
names(PARAMETER2) <- "df2"
PVAL <- 1 - pf(STATISTIC, PARAMETER1, PARAMETER2)
PARAM<-c(PARAMETER1, PARAMETER2)
} else {
PARAMETER1 <- boot.runs
names(PARAMETER1) <- "boot.runs"
PVAL <- pval
PARAM<-PARAMETER1
}
METHOD <- paste("Granger causality H0:", paste(y1.names, collapse=" "), "do not Granger-cause", paste(y2.names, collapse=" "))
result1 <- list(statistic = STATISTIC, parameter = PARAM, p.value = PVAL, method = METHOD, data.name = paste("VAR object", obj.name))
class(result1) <- "htest"
sigma.u <- crossprod(resid(x)) / (obs - ncol(Z))
colnames(sigma.u) <- y.names
rownames(sigma.u) <- y.names
select <- sigma.u[rownames(sigma.u) %in% y2.names, colnames(sigma.u) %in% y1.names ]
sig.vech <- sigma.u[lower.tri(sigma.u, diag = TRUE)]
index <- which(sig.vech %in% select)
N <- length(index)
Cmat <- matrix(0, nrow = N, ncol = length(sig.vech))
for(i in 1 : N){
Cmat[i, index[i]] <- 1
}
Dmat <- .duplicate(K)
Dinv <- MASS::ginv(Dmat)
lambda.w <- obs %*% t(sig.vech) %*% t(Cmat) %*% solve(2 * Cmat %*% Dinv %*% kronecker(sigma.u, sigma.u) %*% t(Dinv) %*% t(Cmat)) %*% Cmat %*% sig.vech
STATISTIC <- lambda.w
names(STATISTIC) <- "Chi-squared"
PARAMETER <- N
names(PARAMETER) <- "df"
PVAL <- 1 - pchisq(STATISTIC, PARAMETER)
METHOD <- paste("H0: No instantaneous causality between:", paste(y1.names, collapse=" "), "and", paste(y2.names, collapse=" "))
result2 <- list(statistic = STATISTIC, parameter = PARAMETER, p.value = PVAL, method = METHOD, data.name = paste("VAR object", obj.name))
class(result2) <- "htest"
result2
return(list(Granger = result1, Instant = result2))
} |
delintercept <- function (mm)
{
saveattr <- attributes(mm)
intercept <- which(saveattr$assign == 0)
if (!length(intercept))
return(mm)
mm <- mm[, -intercept, drop = FALSE]
saveattr$dim <- dim(mm)
saveattr$dimnames <- dimnames(mm)
saveattr$assign <- saveattr$assign[-intercept]
attributes(mm) <- saveattr
mm
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.