code
stringlengths 1
13.8M
|
---|
mvmeta.vc <-
function(Xlist, ylist, Slist, nalist, k, m, p, nall, control, ...) {
Psi <- diag(0,k)
niter <- 0
converged <- FALSE
reltol <- control$reltol
while(!converged && niter<control$maxiter) {
old.Psi <- Psi
gls <- glsfit(Xlist,ylist,Slist,nalist,Psi,onlycoef=FALSE)
tXWXtot <- sumlist(lapply(gls$invtUXlist,crossprod))
invtXWXtot <- chol2inv(chol(tXWXtot))
reslist <- mapply(function(y,X) y-X%*%gls$coef,ylist,Xlist,SIMPLIFY=FALSE)
if(control$vc.adj) {
reslist <- mapply(function(res,X,invU,na) {
IH <- diag(1,sum(!na)) - X%*%invtXWXtot%*%crossprod(X,tcrossprod(invU))
eig <- eigen(IH)
invsqrtIH <- with(eig,vectors%*%(diag(1/sqrt(values),length(values)))%*%
solve(vectors))
return(invsqrtIH%*%res)
},reslist,Xlist,gls$invUlist,nalist,SIMPLIFY=FALSE)
}
Mlist <- mapply(function(res,na) {
M <- matrix(0,k,k)
M[!na,!na] <- tcrossprod(res)
return(M)},reslist,nalist,SIMPLIFY=FALSE)
S0list <- mapply(function(S,na) {
S0 <- matrix(0,k,k)
S0[!na,!na] <- S
return(S0)},Slist,nalist,SIMPLIFY=FALSE)
ind <- m-sumlist(nalist)
Nmat <- matrix(pmin(rep(ind,k),rep(ind,each=k)),k,k)
df.corr <- ifelse(control$vc.adj,0,p)
Psi <- sumlist(Mlist)/(Nmat-df.corr) - sumlist(S0list)/Nmat
eig <- eigen(Psi)
negeigen <- sum(eig$values<0)
Psi <- eig$vectors %*% diag(pmax(eig$values,control$set.negeigen),k) %*%
t(eig$vectors)
niter <- niter+1
value <- abs(Psi-old.Psi)
converged <- all(value<reltol*abs(Psi+reltol))
if(control$showiter) {
cat("iter ",niter,": value ",max(value),"\n",sep="")
if(converged) cat("converged\n")
}
}
qrinvtUX <- qr(gls$invtUX)
R <- qr.R(qrinvtUX)
Qty <- qr.qty(qrinvtUX,gls$invtUy)
vcov <- tcrossprod(backsolve(R,diag(1,ncol(gls$invtUX))))
res <- NULL
fitted <- lapply(Xlist,"%*%",gls$coef)
rank <- qrinvtUX$rank
list(coefficients=gls$coef,vcov=vcov,Psi=Psi,residuals=res,
fitted.values=fitted,df.residual=nall-rank-length(par),rank=rank,logLik=NA,
converged=converged,niter=niter,negeigen=negeigen,control=control)
}
|
isPositiveIntegerOrNaOrNanOrInfScalar <- function(argument, default = NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = FALSE, n = 1, zeroAllowed = TRUE, negativeAllowed = FALSE, positiveAllowed = TRUE, nonIntegerAllowed = FALSE, naAllowed = TRUE, nanAllowed = TRUE, infAllowed = TRUE, message = message, argumentName = argumentName)
}
|
knitr::opts_chunk$set(echo = TRUE)
library(SparseDC)
set.seed(10)
data(data_biase)
head(data_biase[,1:5])
gene_names_biase <- row.names(data_biase)
summary(as.factor(cell_type_biase))
summary(as.factor(condition_biase))
data_A <- data_biase[ , which(condition_biase == "A")]
data_B <- data_biase[ , which(condition_biase == "B")]
dim(data_A)
dim(data_B)
head(data_A[ ,1:5])
head(data_B[ ,1:5])
pre_data <- pre_proc_data(data_A, data_B, norm = FALSE, log = TRUE, center = TRUE)
pdata_A <- pre_data[[1]]
pdata_B <- pre_data[[2]]
head(pdata_A[,1:5])
head(pdata_B[,1:5])
summary(rowSums(cbind(pdata_A,pdata_B)))
lambda1_value <- lambda1_calculator(pdata_A, pdata_B, ncluster = 3)
lambda1_value
lambda2_value <- lambda2_calculator(pdata_A, pdata_B, ncluster =3)
lambda2_value
sdc_res <- sparsedc_cluster(pdata_A, pdata_B, ncluster = 3,
lambda1 = lambda1_value, lambda2 = lambda2_value)
clusters_1 <- sdc_res$clusters1
clusters_2 <- sdc_res$clusters2
centers_1 <- sdc_res$centers1
centers_2 <- sdc_res$centers2
summary(as.factor(clusters_1))
summary(as.factor(clusters_2))
table(cell_type_biase[which(condition_biase == "A")], clusters_1)
table(cell_type_biase[which(condition_biase == "B")], clusters_2)
table(c(cell_type_biase),c(clusters_1,clusters_2))
zygote_top_10_index <- which(centers_1[,1] >= tail(sort(centers_1[,1]),10)[1])
zygote_top_10 <- gene_names_biase[zygote_top_10_index]
zygote_top_10
zyg_t10_res <- cbind(zygote_top_10, centers_1[zygote_top_10_index])
zyg_t10_res
diff_gene_index_2cell <- which(centers_1[,2] != centers_2[,2])
diff_gene_index_2cell
|
ef_fun <- function(ef,
type = "logistic",
x = 1:length(ef),
x0 = mean(ef),
k = 1/4,
L = max(ef)) {
if(type == "logistic"){
FD <- function(x, x0, L, k) {
L/(1 + exp(1)^(-k*(x - x0)) )
}
a <- vein::EmissionFactors(FD(x, x0 = x0, k = k, L = L))
return(a)
}
}
|
tbl_vars.arrow_dplyr_query <- function(x) names(x$selected_columns)
select.arrow_dplyr_query <- function(.data, ...) {
check_select_helpers(enexprs(...))
column_select(as_adq(.data), !!!enquos(...))
}
select.Dataset <- select.ArrowTabular <- select.arrow_dplyr_query
rename.arrow_dplyr_query <- function(.data, ...) {
check_select_helpers(enexprs(...))
column_select(as_adq(.data), !!!enquos(...), .FUN = vars_rename)
}
rename.Dataset <- rename.ArrowTabular <- rename.arrow_dplyr_query
column_select <- function(.data, ..., .FUN = vars_select) {
out <- .FUN(names(.data), !!!enquos(...))
.data$selected_columns <- set_names(.data$selected_columns[out], names(out))
renamed <- out[names(out) != out]
if (length(renamed)) {
gbv <- .data$group_by_vars
renamed_groups <- gbv %in% renamed
gbv[renamed_groups] <- names(renamed)[match(gbv[renamed_groups], renamed)]
.data$group_by_vars <- gbv
}
.data
}
relocate.arrow_dplyr_query <- function(.data, ..., .before = NULL, .after = NULL) {
.data <- as_adq(.data)
map(.data$selected_columns, ~ (.$schema <- .data$.data$schema))
mask <- new_environment(.cache$functions, parent = caller_env())
to_move <- eval_select(substitute(c(...)), .data$selected_columns, mask)
.before <- enquo(.before)
.after <- enquo(.after)
has_before <- !quo_is_null(.before)
has_after <- !quo_is_null(.after)
if (has_before && has_after) {
abort("Must supply only one of `.before` and `.after`.")
} else if (has_before) {
where <- min(unname(eval_select(quo_get_expr(.before), .data$selected_columns, mask)))
if (!where %in% to_move) {
to_move <- c(to_move, where)
}
} else if (has_after) {
where <- max(unname(eval_select(quo_get_expr(.after), .data$selected_columns, mask)))
if (!where %in% to_move) {
to_move <- c(where, to_move)
}
} else {
where <- 1L
if (!where %in% to_move) {
to_move <- c(to_move, where)
}
}
lhs <- setdiff(seq2(1, where - 1), to_move)
rhs <- setdiff(seq2(where + 1, length(.data$selected_columns)), to_move)
pos <- vec_unique(c(lhs, to_move, rhs))
new_names <- names(pos)
.data$selected_columns <- .data$selected_columns[pos]
if (!is.null(new_names)) {
names(.data$selected_columns)[new_names != ""] <- new_names[new_names != ""]
}
.data
}
relocate.Dataset <- relocate.ArrowTabular <- relocate.arrow_dplyr_query
check_select_helpers <- function(exprs) {
exprs <- lapply(exprs, function(x) if (is_quosure(x)) quo_get_expr(x) else x)
unsup_select_helpers <- "where"
funs_in_exprs <- unlist(lapply(exprs, all_funs))
unsup_funs <- funs_in_exprs[funs_in_exprs %in% unsup_select_helpers]
if (length(unsup_funs)) {
stop(
"Unsupported selection ",
ngettext(length(unsup_funs), "helper: ", "helpers: "),
oxford_paste(paste0(unsup_funs, "()"), quote = FALSE),
call. = FALSE
)
}
}
|
treeSims<-function (node.height,perms=100, tip.label = NULL, br = "coalescent", ...)
{
node.height<-sort(node.height)
n <- length(node.height)+1
nbr <- 2 * n - 2
edge <- matrix(NA, nbr, 2)
x <- node.height
res<-list()
for (j in 1:perms){
edge.length <- numeric(nbr)
h <- numeric(2 * n - 1)
pool <- 1:n
nextnode <- 2L * n - 1L
for (i in 1:(n - 1)) {
y <- sample(pool, size = 2)
ind <- (i - 1) * 2 + 1:2
edge[ind, 2] <- y
edge[ind, 1] <- nextnode
edge.length[ind] <- node.height[i] - h[y]
h[nextnode] <- node.height[i]
pool <- c(pool[!pool %in% y], nextnode)
nextnode <- nextnode - 1L
}
phy <- list(edge = edge, edge.length = edge.length)
if (is.null(tip.label))
tip.label <- paste("t", 1:n, sep = "")
phy$tip.label <- sample(tip.label)
phy$Nnode <- n - 1L
class(phy) <- "phylo"
phy <- reorder(phy)
phy$edge[phy$edge[, 2] <= n, 2] <- 1:n
res[[j]]<-phy
}
return(res)
}
|
test_that("cnSpec plot data is formated as expected", {
x <- data.frame(chromosome=c('chr1', 'chr1'), start=c(1000, 5000), end=c(5000, 10000), segmean=c(0, 4), sample=c('samp1', 'samp2'))
y <- data.frame(chromosome=c('chr1', 'chr1'), start=c(0), end=c(10000))
out <- cnSpec(x, y, out="data")
expect_a <- data.frame(chromosome=as.factor(rep(1, 2)),
start=c(1000, 5000),
end=c(5000, 10000),
sample=as.factor(c('samp1', 'samp2')),
cn=c(0, 4))
expect_b <- data.frame(chromosome=as.factor(rep(1, 4)),
start=rep(c(0, 10000), 2),
end=rep(c(0, 10000), 2),
sample=c('samp1', 'samp1', 'samp2', 'samp2'))
expect_equivalent(out[[1]], expect_a)
expect_equivalent(out[[2]], expect_b)
})
|
"quantilize.ecd" <- function(object, show.warning=FALSE)
{
if (! ecd.has_quantile(object)) {
quantile(object) <- ecdq(object)
if (show.warning) {
warning("I am quantilizing ecd for you. This is slow. Consider ecd(with.quantile=T).")
}
}
object
}
setGeneric("quantilize", function(object, show.warning=FALSE) standardGeneric("quantilize"))
setMethod("quantilize", signature("ecd"), quantilize.ecd)
|
df <- eval(parse(text = 'structure(list(yi = c(1.01, 0.82, 0.59, 0.44, 0.84, 0.73, 1.12,
0.04, 0.24, 0.32, 1.04, 1.31, 0.59, 0.66, 0.62, 0.47, 1.08, 0.98,
0.26, 0.39, 0.6, 0.94, 0.11), vi = c(0.2704, 0.2116, 0.0529,
0.0324, 0.0841, 0.0841, 0.1296, 0.1369, 0.0225, 0.16, 0.1024,
0.3249, 0.0841, 0.0361, 0.0961, 0.0729, 0.1024, 0.1024, 0.0324,
0.0324, 0.0961, 0.2809, 0.0729), year = c(1992L, 2000L, 2000L,
2004L, 2005L, 2008L, 2008L, 2010L, 1992L, 1998L, 2006L, 2008L,
1992L, 2002L, 1995L, 1998L, 1998L, 2001L, 2002L, 2003L, 2004L,
2008L, 2008L), score = c(6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L,
7L, 7L, 7L, 18L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 12L),
fumonths = c(19L, 18L, 24L, 21L, 24L, 6L, 18L, 26L, 3L, 12L,
12L, 9L, 12L, 21L, 12L, 18L, 22L, 18L, 21L, 21L, 30L, 6L,
13L), retention = c(83, 100, 90.1649966666667, 57, 100, 87,
89, 86, 79, 100, 92, 100, 96, 100, 93.3, 94, 100, 98, 95,
95, 100, 100, 100), outcomes = c(2L, 4L, 35L, 16L, 3L, 26L,
4L, 11L, 2L, 1L, 7L, 1L, 16L, 10L, 4L, 5L, 10L, 13L, 7L,
12L, 4L, 6L, 53L), duration = c(18L, 12L, 12L, 21L, 24L,
12L, 18L, 26L, 2L, 12L, 5L, 9L, 21L, 3L, 12L, 12L, 22L, 18L,
21L, 21L, 24L, 6L, 12L), meetings = c(30, 5, 4, 15, 4, 12,
3, 4.5, 2, 3, 5, 18, 15, 3, 1, 10, 4, 33, 15, 15, 9, 18,
9), hours = c(1, 1, 1.5, 1, 1, 1.5, 6, 6, 0.25, 1, 1, 6,
1, 1, 15, 0.75, 3, 1.75, 1, 1, 1, 4, 0.75)), row.names = c(NA,
-23L), class = "data.frame")
'))
res <- tryCatch({
suppressWarnings(brma(yi ~. , df, iter = 10))
}, error = function(e){NULL})
test_that("pema runs", {
expect_true(!is.null(res))
})
|
library(tinytest)
.runThisTest <- Sys.getenv("RunRblpapiUnitTests") == "yes"
if (!.runThisTest) exit_file("Skipping this file")
library(Rblpapi)
res <- bds("DAX Index", "INDX_MEMBERS", simplify=FALSE)
expect_true(inherits(res, "list"), info = "checking return type")
expect_true(inherits(res[[1]], "data.frame"), info = "checking return type of first element")
expect_error(bds(c("DAX Index", "SPX Index"), "INDX_MEMBERS"), info = "more than one security")
expect_error(bds(c("DAX Index", "SPX Index"), c("INDX_MEMBERS", "IVOL_SURFACE")), info = "more than one security and more than one field")
expect_error(bds("DAX Index", c("INDX_MEMBERS", "IVOL_SURFACE")), info = "more than one field")
res <- bds("DAX Index", "INDX_MEMBERS")
expect_true(inherits(res, "data.frame"), info = "checking return type under simplify")
|
getGenomeSet <-
function(db = "refseq",
organisms,
reference = FALSE,
release = NULL,
clean_retrieval = TRUE,
gunzip = TRUE,
update = FALSE,
path = "set_genomes",
assembly_type = "toplevel") {
message(
"Starting genome retrieval of the following genomes: ",
paste0(organisms, collapse = ", "),
" ..."
)
if (!file.exists(path)) {
message("Generating folder ", path, " ...")
dir.create(path, recursive = TRUE)
}
if (!(assembly_type %in% c("toplevel", "primary_assembly")))
stop("Please select one the available assembly types: \ntoplevel, primary_assembly")
if (!file.exists(file.path(path, "documentation")))
dir.create(file.path(path, "documentation"))
clean_names <- clean_species_names_helper(list.files(path), gunzip = gunzip)
message("\n")
if (length(clean_names) > 0) {
for (j in seq_len(length(clean_names))) {
if (file.exists(file.path(path, clean_names[j]))) {
if (!update) {
message("The file ", clean_names[j], " seems to exist already in ", path, ".",
"The existing file will be retained. Please specify 'update = TRUE' in case you wish to re-load the file.")
}
if (update) {
message("The file ", clean_names[j], " seems to exist already in ", path, ".",
"You specified 'update = TRUE', thus the file ", clean_names[j], " will be downloaded again.")
unlink(file.path(path, clean_names[j]), force = TRUE)
}
}
}
}
if (!update && (length(organisms) > 1)) {
organisms_short <- tidy_name2(organisms)
clean_names_short <- unlist(sapply(clean_names, function(x) unlist(stringr::str_split(x, "[.]"))))
organisms_short_setdiff <- as.character(as.vector(dplyr::setdiff(organisms_short, clean_names_short)))
if (length(organisms) > 0) {
organisms <- organisms[which(organisms_short %in% organisms_short_setdiff)]
}
}
if (length(organisms) > 0) {
paths <- vector("character", length(organisms))
message("\n")
for (i in seq_len(length(organisms))) {
paths[i] <- getGenome(db = db,
organism = organisms[i],
reference = reference,
release = release,
path = path,
assembly_type = assembly_type)
message("\n")
}
meta_files <- list.files(path)
meta_files <- meta_files[stringr::str_detect(meta_files, "doc_")]
file.rename(from = file.path(path, meta_files), to = file.path(path, "documentation", meta_files))
doc_tsv_files <- file.path(path,"documentation", meta_files[stringr::str_detect(meta_files, "[.]tsv")])
summary_log <- dplyr::bind_rows(lapply(doc_tsv_files, function(data) {
suppressMessages(readr::read_tsv(data))
}))
readr::write_excel_csv(summary_log, file.path(path, "documentation", paste0(basename(path), "_summary.csv")))
message("A summary file (which can be used as supplementary information file in publications) containig retrieval information for all species has been stored at '",file.path(path, "documentation", paste0(basename(path), "_summary.csv")),"'.")
if (clean_retrieval) {
message("\n")
message("Cleaning file names for more convenient downstream processing ...")
}
if (clean_retrieval && gunzip)
clean.retrieval(paths, gunzip = TRUE)
if (clean_retrieval && !gunzip)
clean.retrieval(paths, gunzip = FALSE)
new_files <- list.files(path)
new_files <- new_files[-which(stringr::str_detect(new_files, "documentation"))]
return(file.path(path, new_files))
} else {
files <- file.path(path, list.files(path))
files <- files[-which(stringr::str_detect(files, "documentation"))]
return(files)
}
}
|
use
singleton(
tags$head(
tags$script(src = "
)
)
}
session$sendCustomMessage("
}
|
make_ExG <- function(color_image) {
df_field <- as.data.frame(color_image, wide="c")
df_field <- df_field %>%
mutate(r_small = c.1/(c.1 + c.2 + c.3)) %>%
mutate(g_small = c.2/(c.1 + c.2 + c.3)) %>%
mutate(b_small = c.3/(c.1 + c.2 + c.3))
df_field <- df_field %>%
mutate(ExG = 2*g_small - r_small - b_small)
df_bw <- df_field %>%
dplyr::select(c("x","y","ExG"))
df_bw <- melt(df_bw, id = c("x","y"))
names(df_bw)[3] <- "cc"
df_bw <- na.omit(df_bw)
df_bw$cc <- as.integer(df_bw$cc)
df_bw <- Image(df_bw$value, dim = c(max(df_bw$x),max(df_bw$y)), colormode = 'Grayscale')
return(df_bw)
}
|
ConceptSet <- R6::R6Class(
classname = "ConceptSet",
public = list(
initialize = function(extents, intents,
objects, attributes,
I = NULL) {
private$objects <- objects
private$attributes <- attributes
private$pr_extents <- extents
private$pr_intents <- intents
private$I <- I
},
size = function() {
if (self$is_empty()) {
return(0)
}
return(ncol(private$pr_extents))
},
is_empty = function() {
return(is.null(private$pr_extents))
},
extents = function() {
return(private$pr_extents)
},
intents = function() {
return(private$pr_intents)
},
print = function() {
if (self$is_empty()) {
cat("An empty set of concepts.\n")
} else {
n <- ncol(private$pr_extents)
cat("A set of", n, "concepts:\n")
str <- sapply(seq(n), function(i) {
vA <- Matrix::Matrix(private$pr_extents[, i], sparse = TRUE)
vB <- Matrix::Matrix(private$pr_intents[, i], sparse = TRUE)
paste0(i, ": ",
.concept_to_string(vA, vB,
objects = private$objects,
attributes = private$attributes))
})
cat(str, sep = "\n")
}
},
to_latex = function(print = TRUE,
ncols = 1,
numbered = TRUE,
align = TRUE) {
if (!self$is_empty()) {
output <- concepts_to_latex(private$pr_extents,
private$pr_intents,
private$objects,
private$attributes,
ncols = ncols,
align = align,
numbered = numbered)
if (print) {
cat(output)
}
return(invisible(output))
}
},
to_list = function() {
if (self$is_empty()) {
return(list())
}
elements <- .matrix_to_concepts(
M_ext = private$pr_extents,
M_int = private$pr_intents,
objects = private$objects,
attributes = private$attributes)
class(elements) <- c("list")
return(elements)
},
`[` = function(indices) {
if (!self$is_empty()) {
if (is.logical(indices)) {
indices <- which(indices)
}
indices <- indices[indices <= ncol(private$pr_extents)]
return(ConceptSet$new(
extents = Matrix::Matrix(private$pr_extents[, indices],
sparse = TRUE),
intents = Matrix::Matrix(private$pr_intents[, indices],
sparse = TRUE),
objects = private$objects,
attributes = private$attributes,
I = private$I))
}
return(ConceptSet$new(extents = NULL,
intents = NULL,
objects = private$objects,
attributes = private$attributes,
I = private$I))
},
sub = function(index) {
if (!self$is_empty()) {
index <- index[index <= ncol(private$pr_extents)]
if (length(index) > 0) {
return(self[index]$to_list()[[1]])
}
}
return(NULL)
},
support = function() {
if (!is.null(private$concept_support)) {
return(private$concept_support)
}
my_I <- private$I
my_I@x <- as.numeric(my_I@x)
subsets <- .subset(private$pr_intents, my_I)
private$concept_support <- Matrix::rowMeans(subsets)
return(private$concept_support)
}
),
private = list(
pr_extents = NULL,
pr_intents = NULL,
objects = NULL,
attributes = NULL,
I = NULL,
concept_support = NULL
)
)
|
estat_getStatsData <- function(appId, statsDataId,
startPosition = NULL,
limit = NULL,
lang = c("J", "E"),
.fetch_all = TRUE,
...) {
lang <- match.arg(lang)
total_number <- estat_getStatsDataCount(appId, statsDataId, lang = lang, ...)
ranges <- calc_ranges(startPosition, limit, total_number, .fetch_all)
result <- list()
for (i in seq_len(nrow(ranges))) {
cur_limit <- ranges$limits[i]
cur_start <- ranges$starts[i]
message(sprintf(
"Fetching record %.0f-%.0f... (total: %.0f records)\n",
cur_start, cur_start + cur_limit - 1, total_number
))
j <- estat_api("rest/3.0/app/getSimpleStatsData",
appId = appId,
statsDataId = statsDataId,
startPosition = format(cur_start, scientific = FALSE),
limit = format(cur_limit, scientific = FALSE),
lang = lang,
metaGetFlg = "N",
sectionHeaderFlg = "2",
...
)
result[[i]] <- j
}
dplyr::bind_rows(result)
}
estat_getStatsDataCount <- function(appId, statsDataId, ...) {
j <- estat_api("rest/3.0/app/json/getStatsData",
appId = appId,
statsDataId = statsDataId,
metaGetFlg = "N",
cntGetFlg = "Y",
...
)
as.numeric(j$GET_STATS_DATA$STATISTICAL_DATA$RESULT_INF$TOTAL_NUMBER)
}
calc_ranges <- function(startPosition,
limit,
record_count,
.fetch_all,
.max_records_at_once = 100000) {
ranges <- list()
if (is.null(startPosition)) {
startPosition <- 1
}
if (is.null(limit)) {
endPosition <- record_count
} else {
endPosition <- min(startPosition + limit - 1, record_count)
}
if (.fetch_all) {
ranges$starts <- seq(from = startPosition, to = endPosition, by = .max_records_at_once)
ranges$limits <- rep(.max_records_at_once, length(ranges$starts))
fraction <- (endPosition - startPosition + 1) %% .max_records_at_once
if (fraction != 0) {
ranges$limits[length(ranges$limits)] <- fraction
}
} else {
ranges$starts <- startPosition
ranges$limits <- min(startPosition + .max_records_at_once - 1, endPosition)
}
tibble::tibble(!!!ranges)
}
|
tenFoldCV.glm <- function(dat.glm, mod, conf_level = 0.95) {
N <- nrow(dat.glm)
dat.glm <- dat.glm[sample(1:N, size = N, replace = FALSE) , ]
MatRes <- matrix(nrow = N, ncol = 3)
colnames(MatRes) <- c("True_sex", "Proba_10CV", "Predict_sex_10CV")
MatRes <- data.frame(MatRes)
MatRes[ , 1] <- as.character(dat.glm$Sex)
for (k in 1:10) {
pioch <- (1:N <= k*N/10) & (1:N > (k-1)*N/10)
app <- dat.glm[!pioch, ]
val <- dat.glm[pioch, ]
modTemp <- glm(mod$call$formula, family = binomial, data = app)
MatRes[pioch, 2] <- predict(modTemp, newdata = val, type = "response")
}
MatRes[ , 3] <- finalSE(MatRes[ , 2], conf_level)
indet_rate <- nrow(MatRes[MatRes$Predict_sex_10CV == "I", ]) / nrow(MatRes)
if (indet_rate < 1) {
success_rate <- nrow(MatRes[(MatRes$Predict_sex_10CV=="F" & MatRes$True_sex=="F") | (MatRes$Predict_sex_10CV=="M" & MatRes$True_sex=="M"), ]) / nrow(MatRes[MatRes$Predict_sex_10CV!="I", ])
} else {
success_rate <- NA
}
return(list(ClassifResults = MatRes, IndetRate = indet_rate, SuccessRate = success_rate))
}
|
CompareSubTrees.k <-
function(trees,focal,maxk,mod.id=c(1,0,0,0),min.val=0.01){ res<-list()
Ks<-1:maxk
for (i in 1:maxk){
cat("\n",i,"of k =",maxk)
res[[i]]<-compareSubTrees(trees,focal=focal,k=Ks[i],mod.id=mod.id,min.val=min.val)
}
cat("\n")
return(res)
}
|
"tradeModel" <- function(x,
signal.threshold=c(0,0),
leverage=1,
return.model=TRUE,
plot.model=FALSE,
trade.dates=NULL,
exclude.training=TRUE,
ret.type=c('weeks','months','quarters','years'),...)
{
trade.offset = 0;
quantmod <- getModelData(x);
if(class(quantmod) != "quantmod") stop("model must be of class quantmod");
if(!is.null(trade.dates) && length(trade.dates) < 2) stop("trade.dates must be of length 2");
model.data <- modelData(quantmod,trade.dates,exclude.training=exclude.training);
fitted.zoo <- predictModel([email protected],model.data,...)
if(class(fitted.zoo) != "zoo") {
fitted.zoo <- zoo(as.vector(fitted.zoo),index(model.data));
}
signal.zoo <- ifelse(fitted.zoo < signal.threshold[1] |
fitted.zoo > signal.threshold[2],
ifelse(fitted.zoo > 0,1,-1), 0);
tmp.index <- index(signal.zoo)[-(1+trade.offset)];
market.zoo <- model.data[-(nrow(model.data)+trade.offset),1]
signal.zoo <- signal.zoo[-c(length(index(signal.zoo))-trade.offset,length(index(signal.zoo)))];
signal.zoo = merge(market.zoo,signal.zoo)
index(signal.zoo) <- tmp.index;
quantmodResults <- list(model=quantmod, signal=signal.zoo)
model.returns <- modelReturn(quantmodResults,trade.dates=trade.dates,leverage=leverage,ret.type=ret.type);
quantmodResults$return <- model.returns;
quantmodResults$model <- stripModelData(quantmodResults$model);
return(structure(quantmodResults, class="quantmodResults"));
}
print.quantmodResults <- function(x, ...) {
cat("\n Model: ",[email protected],"\n")
cat("\n C.A.G.R.: ",sprintf("%04.2f%%",x$return@CAGR*100),"\tH.P.R.: ",
sprintf("%04.2f%%",x$return@HPR*100),"\n");
to.date.ret <- sprintf("%04.2f%%",x$return@returnsBy[NROW(x$return@returnsBy),-1]*100)
to.date.ret <- as.data.frame(t(to.date.ret),row.names=" ")
colnames(to.date.ret) <- colnames(x$return@returnsBy[,-1])
cat("\n Returns by period summary:\n\n")
print(as.data.frame(lapply(as.data.frame(x$return@returnsBy[,-1]),
function(x) sprintf("%04.2f%%",(rev(as.numeric(summary(x))[1:6]*100)))),
row.names=c(' Max.',' 3rd Qu.',' Mean',' Median',' 2rd Qu.',' Min.')))
cat("\n Period to date returns:\n\n")
print(to.date.ret)
}
|
if (suppressWarnings(
require("testthat") &&
require("ggeffects") &&
require("lme4") &&
require("sjlabelled") &&
require("sjmisc")
)) {
data(efc)
efc$neg_c_7d <- dicho(efc$neg_c_7)
fit <- glm(neg_c_7d ~ c12hour + e42dep + c161sex + c172code, data = efc, family = binomial(link = "logit"))
m <- glm(
cbind(incidence, size - incidence) ~ period,
family = binomial,
data = lme4::cbpp
)
test_that("ggpredict, glm", {
expect_s3_class(ggpredict(fit, "c12hour"), "data.frame")
expect_s3_class(ggpredict(fit, c("c12hour", "c161sex")), "data.frame")
expect_s3_class(ggpredict(fit, c("c12hour", "c161sex", "c172code")), "data.frame")
})
test_that("ggeffect, glm", {
expect_s3_class(ggeffect(fit, "c12hour"), "data.frame")
expect_s3_class(ggeffect(fit, c("c12hour", "c161sex")), "data.frame")
expect_s3_class(ggeffect(fit, c("c12hour", "c161sex", "c172code")), "data.frame")
})
test_that("ggemmeans, glm", {
expect_s3_class(ggemmeans(fit, "c12hour"), "data.frame")
expect_s3_class(ggemmeans(fit, c("c12hour", "c161sex")), "data.frame")
expect_s3_class(ggemmeans(fit, c("c12hour", "c161sex", "c172code")), "data.frame")
})
p1 <- ggpredict(m, "period")
p2 <- ggeffect(m, "period")
p3 <- ggemmeans(m, "period")
test_that("ggeffects, glm", {
expect_equal(p1$predicted[1], 0.2194245, tolerance = 1e-3)
expect_equal(p2$predicted[1], 0.2194245, tolerance = 1e-3)
expect_equal(p3$predicted[1], 0.2194245, tolerance = 1e-3)
})
test_that("ggpredict, glm, robust", {
expect_s3_class(ggpredict(fit, "c12hour", vcov.fun = "vcovHC", vcov.type = "HC1"), "data.frame")
expect_s3_class(ggpredict(fit, c("c12hour", "c161sex"), vcov.fun = "vcovHC", vcov.type = "HC1"), "data.frame")
expect_s3_class(ggpredict(fit, c("c12hour", "c161sex", "c172code"), vcov.fun = "vcovHC", vcov.type = "HC1"), "data.frame")
})
test_that("ggeffects, glm, robust", {
expect_s3_class(ggpredict(m, "period", vcov.fun = "vcovHC", vcov.type = "HC1"), "data.frame")
})
data(cbpp)
cbpp$trials <- cbpp$size - cbpp$incidence
m1 <- glmer(cbind(incidence, trials) ~ period + (1 | herd), data = cbpp, family = binomial)
m2 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd), data = cbpp, family = binomial)
m3 <- glm(cbind(incidence, trials) ~ period, data = cbpp, family = binomial)
m4 <- glm(cbind(incidence, size - incidence) ~ period, data = cbpp, family = binomial)
test_that("ggeffects, glm-matrix-columns", {
expect_s3_class(ggpredict(m1, "period"), "data.frame")
expect_s3_class(ggpredict(m2, "period"), "data.frame")
expect_s3_class(ggpredict(m3, "period"), "data.frame")
expect_s3_class(ggpredict(m4, "period"), "data.frame")
expect_s3_class(ggemmeans(m1, "period"), "data.frame")
expect_s3_class(ggemmeans(m2, "period"), "data.frame")
expect_s3_class(ggemmeans(m3, "period"), "data.frame")
expect_s3_class(ggemmeans(m4, "period"), "data.frame")
})
}
|
get_image_rtf <- function(file_path, width, height, units) {
if (!units %in% c("inches", "cm")) {
stop("Invalid units.")
}
if (units == "inches") {
conv <- 1440
} else {
conv <- 566.9291
}
ret <- paste0("{\\pict\\pngblip\\picwgoal",round(width*conv),"\\pichgoal",round(height*conv)," \n")
ret <- paste0(ret, get_image_bytes(file_path), "\n}")
return(ret)
}
get_image_bytes <- function(file_path) {
if (!file.exists(file_path))
stop(paste("Image file not found:", file_path))
max.bytes<-50000000
dat<-readBin(file_path, what="raw", size=1,
signed=TRUE, endian="little", n=max.bytes);
sdat <- split(dat, ceiling(seq_along(dat)/40))
lns <- sapply(sdat, paste, collapse = "")
ret <- paste0(lns, "\n", collapse = "")
return(ret)
}
get_image_html <- function(file_path, report_path, plt, units) {
dr <- file.path(dirname(report_path), "images")
if (!file.exists(dr)) {
dir.create(dr)
}
fl <- paste0( gsub(".html", "", basename(report_path), fixed = TRUE), "-",
stri_rand_strings(1, 4, pattern = "[A-Z0-9]"), ".jpg")
pth <- file.path(dr, fl)
res <- file.copy(file_path, pth)
if (all(res == TRUE)) {
file.remove(file_path)
}
u <- units
if (u == "inches")
u <- "in"
ph <- round(plt$height * .99, 3)
pw <- round(plt$width * .99, 3)
ret <- paste0("<img src=\"./images/", basename(pth), "\"",
" style=\"height:", ph, u, ";",
" width:", pw, u, ";\">")
return(ret)
}
|
build_kraken_tree <- function(report) {
if (nrow(report) == 0 || nrow(report) == 1) {
return(list(report))
}
sel_depth <- report[,'depth'] == report[1,'depth']
depth_partitions <- cumsum(sel_depth)
res <- lapply(unique(depth_partitions),
function(my_depth_partition) {
sel <- depth_partitions == my_depth_partition
if (sum(sel) == 1)
return(report[sel,,drop=F])
first_row <- which(sel)[1]
dres <- build_kraken_tree(report[which(sel)[-1],,drop=F])
attr(dres,"row") <- report[first_row,,drop=F]
dres
})
names(res) <- report$name[sel_depth]
res
}
collapse.taxRanks <- function(krakenlist,keep_taxRanks=LETTERS,filter_taxon=NULL) {
cols <- c("taxonReads","n_unique_kmers","n_kmers")
if (length(krakenlist) == 0 || is.data.frame(krakenlist)) {
return(krakenlist)
}
parent_row <- attr(krakenlist,"row")
all.child_rows <- c()
if (is.null(parent_row)) {
return(do.call(rbind,lapply(krakenlist,collapse.taxRanks,keep_taxRanks=keep_taxRanks,filter_taxon=filter_taxon)))
}
rm.cladeReads <- 0
for (kl in krakenlist) {
if (is.data.frame(kl)) {
child_rows <- kl
} else {
child_rows <- collapse.taxRanks(kl,keep_taxRanks,filter_taxon=filter_taxon)
if ('rm.cladeReads' %in% names(attributes(child_rows))) {
rm.cladeReads <- rm.cladeReads + attr(child_rows,'rm.cladeReads')
}
}
delete.taxon <- child_rows[1,'name'] %in% filter_taxon
if (delete.taxon) {
rm.cladeReads <- rm.cladeReads + child_rows[1,'cladeReads']
dmessage(sprintf("removed %7s cladeReads, including %s childs, for %s",child_rows[1,'"cladeReads"'],nrow(child_rows)-1,child_rows[1,'name']))
child_rows <- NULL
} else {
keep_last.child <- child_rows[1,'taxRank'] %in% keep_taxRanks
if (!keep_last.child) {
cols <- cols[cols %in% colnames(parent_row)]
parent_row[,cols] <- parent_row[,cols] + child_rows[1,cols]
child_rows <- child_rows[-1,,drop=FALSE]
if (nrow(child_rows) > 0)
child_rows[,'depth'] <- child_rows[,'depth'] - 1
}
}
all.child_rows <- rbind(all.child_rows,child_rows)
}
parent_row[,'cladeReads'] <- parent_row[,'cladeReads'] - rm.cladeReads
res <- rbind(parent_row,all.child_rows)
if (parent_row[,'cladeReads'] < 0)
stop("mistake made in removing cladeReads")
if (rm.cladeReads > 0)
attr(res,'rm.cladeReads') <- rm.cladeReads
return(res)
}
delete_taxRanks_below <- function(report,taxRank="S") {
del_taxRank <- 0
do_del <- FALSE
del_row <- 0
cols <- c("taxonReads","n_unique_kmers","n_kmers")
sub.sums <- c(0,0,0)
rows_to_delete <- c()
for (i in seq_len(nrow(report))) {
if (report[i,'taxRank'] %in% taxRank) {
del_depth <- report[i,'depth']
do_del <- TRUE
del_row <- i
sub.sums <- c(0,0,0)
} else {
if (do_del) {
if (report[i,'depth'] > del_taxRank) {
rows_to_delete <- c(rows_to_delete,i)
sub.sums <- sub.sums + report[i,cols]
} else {
report[del_row,cols] <- report[del_row,cols]+sub.sums
sub.sums <- c(0,0,0)
do_del <- FALSE
}
}
}
}
report[-rows_to_delete,]
}
read_report2 <- function(myfile,collapse=TRUE,keep_taxRanks=c("D","K","P","C","O","F","G","S"),min.depth=0,filter_taxon=NULL,
has_header=NULL,add_taxRank_columns=FALSE) {
first.line <- readLines(myfile,n=1)
isASCII <- function(txt) all(charToRaw(txt) <= as.raw(127))
if (!isASCII(first.line)) {
dmessage(myfile," is no valid report - not all characters are ASCII")
return(NULL)
}
if (is.null(has_header)) {
has_header <- grepl("^[a-zA-Z]",first.line)
}
if (has_header) {
report <- utils::read.table(myfile,sep="\t",header = T,
quote = "",stringsAsFactors=FALSE, comment.char="
colnames(report)[colnames(report)=="clade_perc"] <- "percentage"
colnames(report)[colnames(report)=="perc"] <- "percentage"
colnames(report)[colnames(report)=="n_reads_clade"] <- "cladeReads"
colnames(report)[colnames(report)=="n.clade"] <- "cladeReads"
colnames(report)[colnames(report)=="n_reads_taxo"] <- "taxonReads"
colnames(report)[colnames(report)=="n.stay"] <- "taxonReads"
colnames(report)[colnames(report)=="rank"] <- "taxRank"
colnames(report)[colnames(report)=="tax_rank"] <- "taxRank"
colnames(report)[colnames(report)=="taxonid"] <- "taxID"
colnames(report)[colnames(report)=="tax"] <- "taxID"
} else {
report <- utils::read.table(myfile,sep="\t",header = F,
col.names = c("percentage","cladeReads","taxonReads","taxRank","taxID","name"),
quote = "",stringsAsFactors=FALSE, comment.char="
}
report$depth <- nchar(gsub("\\S.*","",report$name))/2
report$name <- gsub("^ *","",report$name)
report$name <- paste(tolower(report$taxRank),report$name,sep="_")
kraken.tree <- build_kraken_tree(report)
report <- collapse.taxRanks(kraken.tree,keep_taxRanks=keep_taxRanks,filter_taxon=filter_taxon)
if (add_taxRank_columns) {
report[,keep_taxRanks] <- NA
}
report$taxLineage = report$name
rows_to_consider <- rep(FALSE,nrow(report))
for (i in seq_len(nrow(report))) {
if (i > 1 && report[i,"depth"] > min.depth) {
idx <- report$depth < report[i,"depth"] & rows_to_consider
if (!any(idx)) { next() }
current.taxRank <- report[i,'taxRank']
my_row <- max(which(idx))
report[i,'taxLineage'] <- paste(report[my_row,'taxLineage'],report[i,'taxLineage'],sep="|")
if (add_taxRank_columns) {
if (report[my_row,'taxRank'] %in% keep_taxRanks) {
taxRanks.cp <- keep_taxRanks[seq(from=1,to=which(keep_taxRanks == report[my_row,'taxRank']))]
report[i,taxRanks.cp] <- report[my_row,taxRanks.cp]
}
report[i,report[i,'taxRank']] <- report[i,'name']
}
}
rows_to_consider[i] <- TRUE
}
report <- report[report$depth >= min.depth,]
report$percentage <- round(report$cladeReads/sum(report$taxonReads),6) * 100
for (column in c("taxonReads", "cladeReads"))
if (all(floor(report[[column]]) == report[[column]]))
report[[column]] <- as.integer(report[[column]])
if ('n_unique_kmers' %in% colnames(report))
report$kmerpercentage <- round(report$n_unique_kmers/sum(report$n_unique_kmers,na.rm=T),6) * 100
rownames(report) <- NULL
report
}
filter_taxon <- function(report, filter_taxon, rm_clade = TRUE, do_message=FALSE) {
taxon_depth <- NULL
taxonReads <- 0
pos.taxons <- which(sub("._","",report$name) %in% filter_taxon)
if (length(pos.taxons) == 0) {
return(report)
}
row_seq <- seq_len(nrow(report))
rows_to_delete <- rep(FALSE,nrow(report))
taxon_depths <- report[pos.taxons,"depth"]
if (isTRUE(rm_clade)) {
taxonReads <- report[pos.taxons,"cladeReads"]
} else {
taxonReads <- report[pos.taxons,"taxonReads"]
report[pos.taxons,"taxonReads"] <- 0
}
for (i in seq_along(pos.taxons)) {
pos.taxon <- pos.taxons[i]
if (pos.taxon == 1) {
rows_to_delete[1] <- TRUE
next
}
taxon_depth <- taxon_depths[i]
taxonReads <- taxonReads[i]
if (rm_clade) {
tosum_below <- row_seq >= pos.taxon & report$depth <= taxon_depth
taxons_below <- cumsum(tosum_below) == 1
rows_to_delete[taxons_below] <- TRUE
}
rows_to_update <- c(pos.taxon)
taxons_above <- seq_len(nrow(report)) < pos.taxon & report$depth == taxon_depth
any_stays <- FALSE
prev_taxon_depth <- taxon_depth
taxons_above <- c()
for (i in seq(from=(pos.taxon-1),to=1)) {
curr_taxon_depth <- report[i,"depth"]
if (curr_taxon_depth < prev_taxon_depth) {
if (!any_stays) {
if (report[i,"cladeReads"] == taxonReads) {
rows_to_delete[i] <- TRUE
if (do_message)
dmessage("Deleting ",report[i,"name"])
} else {
any_stays <- TRUE
}
}
if (!rows_to_delete[i]) {
rows_to_update <- c(rows_to_update, i)
if (do_message)
dmessage("Updating ",report[i,"name"])
}
prev_taxon_depth <- curr_taxon_depth
} else {
any_stays <- TRUE
}
}
report[rows_to_update, "cladeReads"] <- report[rows_to_update, "cladeReads"] - taxonReads
}
report[!rows_to_delete,]
}
read_report <- function(myfile, has_header=NULL, check_file = FALSE) {
first.line <- tryCatch( readLines(myfile,n=1, warn=FALSE),
error = function(e) { warning("Error reading ",myfile); return() })
isASCII <- function(txt) {
if (length(txt) == 0)
return(FALSE)
raw <- charToRaw(txt)
all(raw <= as.raw(127) && (raw >= as.raw(32) | raw == as.raw(9)))
}
if (length(first.line) == 0) {
dmessage("Could not read ", myfile, ".")
return(NULL)
}
tryCatch({
if (nchar(first.line) == 0) {
dmessage("First line of ", myfile, " is empty")
return(NULL)
}
}, error = function(e) {
dmessage(e)
return(NULL)
})
if (!isTRUE(isASCII(first.line))) {
dmessage(myfile," is not a ASCII file")
return(NULL)
}
if (is.null(has_header)) {
has_header <- grepl("^[a-zA-Z
}
is_metaphlan3_fmt <- grepl("^
is_metaphlan_fmt <- grepl("Metaphlan2_Analysis$", first.line)
is_krakenu_fmt <- grepl("^.?%\treads\ttaxReads\tkmers", first.line)
is_kaiju_fmt <- grepl("^ *%\t *reads", first.line)
ntabs <- lengths(regmatches(first.line, gregexpr("\t", first.line)))
nrows <- ifelse(isTRUE(check_file), 5, -1)
if (!is_krakenu_fmt && is_kaiju_fmt) {
cont <- readLines(myfile)
cont <- cont[!grepl("^-", cont)]
cont <- sub(".*\t *","", cont)
cont <- sub("; ?$","", cont)
report <- utils::read.delim(textConnection(cont), stringsAsFactors = FALSE)
colnames(report) <- c("taxonReads", "taxLineage")
report$cladeReads <- report$taxonReads
report$taxLineage <- gsub("^","-_",report$taxLineage)
report$taxLineage <- gsub("; ","|-_",report$taxLineage)
report$taxLineage <- gsub("-_Viruses", "d_Viruses", report$taxLineage, fixed=T)
report$taxLineage <- gsub("-_cellular organisms|-_Bacteria", "-_cellular organisms|d_Bacteria", report$taxLineage, fixed=T)
report$taxLineage <- gsub("-_cellular organisms|-_Eukaryota", "-_cellular organisms|d_Eukaryota", report$taxLineage, fixed=T)
report$taxLineage <- gsub("-_cellular organisms|-_Archaea", "-_cellular organisms|d_Archaea", report$taxLineage, fixed=T)
report$taxLineage[1:(length(report$taxLineage)-1)] <- paste0("-_root|", report$taxLineage[1:(length(report$taxLineage)-1)])
report$taxLineage[report$taxLineage=="-_unclassified"] <- "u_unclassified"
new_counts <- integer(length = 0)
for (j in seq_len(nrow(report))) {
count <- report$cladeReads[j]
tl <- report$taxLineage[j]
tl2 <- sub("\\|[^|]*$","", tl)
while (tl2 != tl) {
if (tl2 %in% names(new_counts)) {
new_counts[tl2] <- new_counts[tl2] + count
} else {
new_counts[tl2] <- count
}
tl <- tl2
tl2 <- sub("\\|[^|]*$","", tl)
}
}
report <- rbind(report,
data.frame(taxonReads=0,taxLineage=names(new_counts),cladeReads=as.integer(new_counts)))
tl_order <- order(report$taxLineage)
tl_order <- c(tl_order[length(tl_order)],tl_order[-length(tl_order)])
report <- report[tl_order, c("taxLineage", "taxonReads", "cladeReads")]
} else if (is_metaphlan3_fmt) {
report <- tryCatch({
utils::read.table(myfile,sep="\t",header = F,
quote = "",stringsAsFactors=FALSE,
comment.char = "
col.names = c("taxLineage", "taxID", "cladeReads", "additional_species"),
check.names=FALSE)
}, error = function(x) NULL, warning = function(x) NULL)
if (is.null(report)) { return(NULL); }
report$taxID <- sub(".*\\|", "", report$taxID)
} else if (has_header) {
report <- tryCatch({
utils::read.table(myfile,sep="\t",header = T,
quote = "",stringsAsFactors=FALSE,
comment.char = ifelse(is_metaphlan_fmt, "", "
check.names=FALSE)
}, error = function(x) NULL, warning = function(x) NULL)
if (is.null(report)) { return(NULL); }
colnames(report)[colnames(report) %in% c("
colnames(report)[colnames(report) %in% c("reads","numReadsClade","n_reads_clade","n.clade","n-clade")] <- "cladeReads"
colnames(report)[colnames(report) %in% c("taxReads","numReadsTaxon","n_reads_taxo","n.stay","n-stay")] <- "taxonReads"
colnames(report)[colnames(report) %in% c("rank","tax_taxRank","level")] <- "taxRank"
colnames(report)[colnames(report) %in% c("tax","taxonid")] <- "taxID"
colnames(report)[colnames(report) %in% c("indentedName","taxName")] <- "name"
colnames(report)[colnames(report) %in% c("dup")] <- "kmerDuplicity"
colnames(report)[colnames(report) %in% c("cov")] <- "kmerCoverage"
} else {
report <- NULL
if (ntabs == 5) {
col_names <- c("percentage","cladeReads","taxonReads","taxRank","taxID","name")
} else if (ntabs == 7) {
col_names <- c("percentage","cladeReads","taxonReads", "n_unique_kmers","n_kmers", "taxRank","taxID","name")
}
report <- tryCatch({
utils::read.table(myfile,sep="\t",header = F,
col.names = col_names,
quote = "",stringsAsFactors=FALSE,
nrows = nrows)
}, error=function(x) NULL, warning=function(x) NULL)
if (is.null(report)) {
dmessage(paste("Warning: File",myfile,"does not have the required format"))
return(NULL);
}
}
if (ncol(report) < 2) {
dmessage(paste("Warning: File",myfile,"does not have the required format"))
return(NULL)
}
if (is_metaphlan_fmt || is_metaphlan3_fmt) {
colnames(report)[1] <- "taxLineage"
colnames(report)[colnames(report) == "Metaphlan2_Analysis"] <- "cladeReads"
report <- report[order(report$taxLineage), ]
report$taxLineage <- gsub("_"," ",report$taxLineage)
report$taxLineage <- gsub(" ","_",report$taxLineage)
report$taxLineage <- paste0("-_root|", report$taxLineage)
root_lines <- data.frame(taxLineage=c("u_unclassified","-_root"),"cladeReads"=c(0,100), stringsAsFactors = F)
if ("taxID" %in% colnames(report)) {
root_lines <- cbind(root_lines, "taxID" = c(0, 1))
report <- report[, c("taxLineage", "cladeReads", "taxID")]
}
report <- rbind(root_lines, report)
}
if (all(c("name","taxRank") %in% colnames(report)) && !"taxLineage" %in% colnames(report)) {
report$depth <- nchar(gsub("\\S.*","",report$name))/2
if (!all(report$depth == floor(report$depth))) {
warning("Depth doesn't work out!")
return(NULL)
}
report$name <- gsub("^ *","",report$name)
table(report$taxRank)
allowed_taxRanks <- c("U", "S", "G", "F", "C", "D", "O", "K", "P")
report$taxRank[report$taxRank=="class"] <- "C"
report$taxRank[report$taxRank=="family"] <- "F"
report$taxRank[report$taxRank=="genus"] <- "G"
report$taxRank[report$taxRank=="superkingdom"] <- "D"
report$taxRank[report$taxRank=="kingdom"] <- "K"
report$taxRank[report$taxRank=="order"] <- "O"
report$taxRank[report$taxRank=="phylum"] <- "P"
report$taxRank[report$taxRank=="species"] <- "S"
report$taxRank[report$name=="unclassified"] <- "U"
report$taxRank[!report$taxRank %in% allowed_taxRanks] <- "-"
report$name <- paste(tolower(report$taxRank),report$name,sep="_")
rownames(report) <- NULL
report$taxLineage <- report$name
n <- nrow(report)
depths <- report$depth
taxLineages <- report$name
taxLineages_p <- as.list(seq_along(report$name))
depth_row_tmp <- c(1:25)
for (current_row in seq(from=1, to=nrow(report))) {
dcr <- depths[current_row]
depth_row_tmp[dcr+1] <- current_row
if (dcr >= 1) {
prev_pos <- depth_row_tmp[[dcr]]
taxLineages_p[[current_row]] <- c(taxLineages_p[[prev_pos]], current_row)
}
}
report$taxLineage <- sapply(taxLineages_p, function(x) paste0(taxLineages[x], collapse="|"))
} else if ("taxLineage" %in% colnames(report)) {
taxLineages <- strsplit(report$taxLineage, "|", fixed=TRUE)
if (!"name" %in% colnames(report))
report$name <- sapply(taxLineages, function(x) x[length(x)])
if (!"depth" %in% colnames(report)) {
report$depth <- sapply(taxLineages, length) - 1
}
if (!"taxRank" %in% colnames(report))
report$taxRank <- toupper(substr(report$name, 0, 1))
}
if (!all(c("name","taxRank") %in% colnames(report)) ||
nrow(report) < 2 ||
!((report[1,"name"] == "u_unclassified" && report[2,"name"] == "-_root") || report[1,"name"] == "-_root")) {
dmessage(paste("Warning: File",myfile,"does not have the required format"))
str(report)
return(NULL)
}
if (!"taxonReads" %in% colnames(report)) {
parent <- sub("^\\(.*\\)\\|.*$", "\\1", report$taxLineage)
taxLineages <- strsplit(report$taxLineage, "|", fixed=TRUE)
report$taxonReads <- report$cladeReads - sapply(report$name, function(x) sum(report$cladeReads[parent == x]))
report$taxonReads[report$taxonReads <= 0.00001] <- 0
}
report$percentage <- signif(report$cladeReads/sum(report$taxonReads),6) * 100
if ('n_unique_kmers' %in% colnames(report))
report$kmerpercentage <- round(report$n_unique_kmers/sum(report$n_unique_kmers,na.rm=T),6) * 100
if ("taxID" %in% colnames(report)) {
std_colnames <- c("percentage","cladeReads","taxonReads","taxRank", "taxID","name")
} else {
std_colnames <- c("percentage","cladeReads","taxonReads","taxRank","name")
}
stopifnot(all(std_colnames %in% colnames(report)))
report[, c(std_colnames, setdiff(colnames(report), std_colnames))]
}
|
context("canvasXpress segregation for violin plot")
skip_if_offline(host = "www.canvasxpress.org")
test_that("violinplot with grouping and segregation", {
tryCatch({
y <- read.table("https://www.canvasxpress.org/data/cX-toothgrowth-dat.txt", header = TRUE, sep = "\t", quote = "", row.names = 1, fill = TRUE, check.names = FALSE, stringsAsFactors = FALSE)
x <- read.table("https://www.canvasxpress.org/data/cX-toothgrowth-smp.txt", header = TRUE, sep = "\t", quote = "", row.names = 1, fill = TRUE, check.names = FALSE, stringsAsFactors = FALSE)
z <- data.frame(Gene = c("Gene1"), stringsAsFactors = FALSE)
},
error = function(e) {
skip('Unable to read data files')
})
rownames(z) <- rownames(y)
result <- canvasXpress(data = y,
smpAnnot = x,
varAnnot = z,
graphType = "Boxplot",
graphOrientation = "vertical",
colorBy = "supp",
title = "Violinplot with segregation and grouping should work",
showViolinBoxplot = TRUE,
groupingFactors = list("supp"),
segregateVariablesBy = list("Gene"),
afterRender = list(list("switchNumericToString", list("supp", TRUE))))
check_ui_test(result)
})
|
equals2 <- function(v1, v2) {
same <- (v1 == v2) | (is.na(v1) & is.na(v2))
same[is.na(same)] <- FALSE
return(same)
}
|
setClass(
Class = "S2.corcircle",
contains = "ADEg.S2"
)
setMethod(
f = "initialize",
signature = "S2.corcircle",
definition = function(.Object, data = list(dfxy = NULL, xax = 1, yax = 2, labels = NULL, frame = 0, storeData = TRUE), ...) {
.Object <- callNextMethod(.Object, data = data, ...)
.Object@data$labels <- data$labels
return(.Object)
})
setMethod(
f = "prepare",
signature = "S2.corcircle",
definition = function(object) {
name_obj <- deparse(substitute(object))
oldparamadeg <- adegpar()
on.exit(adegpar(oldparamadeg))
adegtot <- adegpar([email protected])
getgrid <- function(nbgrid = 10) {
cgrid <- signif(2 / nbgrid, 2)
h0 <- c(rev(seq(0, -1, by = -cgrid)), seq(0 + cgrid, 1, by = cgrid))
cgrid <- diff(h0)[1]
coord <- rep(0, length(h0))
for(i in 1:length(h0))
coord[i] <- sqrt(1 - h0[i] * h0[i])
return(list(x0 = c(h0, -coord), x1 = c(h0, coord), y0 = c(-coord, h0), y1 = c(coord, h0), d = cgrid))
}
if(adegtot$pgrid$draw || adegtot$paxes$draw)
[email protected]$backgrid <- getgrid(adegtot$pgrid$nint)
if(is.null([email protected]$ppoints$cex))
adegtot$ppoints$cex <- 0
[email protected] <- adegtot
callNextMethod()
[email protected]$plabels$optim <- FALSE
assign(name_obj, object, envir = parent.frame())
})
setMethod(
f = "panel",
signature = "S2.corcircle",
definition = function(object, x, y) {
panel.arrows(x0 = 0, y0 = 0, y1 = y, x1 = x, angle = [email protected]$parrows$angle,
length = [email protected]$parrows$length, ends = [email protected]$parrows$end,
lwd = [email protected]$plines$lwd, col = [email protected]$plines$col, lty = [email protected]$plines$lty)
plabels <- [email protected]$plabels
pos <- .textpos(x, y, origin = c(0, 0))
if(object@data$storeData)
labels <- object@data$labels
else
labels <- eval(object@data$labels, envir = sys.frame(object@data$frame))
test <- .textsize(labels, plabels)
w <- test$w
h <- test$h
adeg.panel.label(x = x + pos[1, ] * w / 2, y = y + pos[2, ] * h / 2, labels = labels, plabels = plabels)
})
s.corcircle <- function(dfxy, xax = 1, yax = 2, labels = row.names(as.data.frame(dfxy)), fullcircle = TRUE,
facets = NULL, plot = TRUE, storeData = TRUE, add = FALSE, pos = -1, ...) {
thecall <- .expand.call(match.call())
df <- try(as.data.frame(eval(thecall$dfxy, envir = sys.frame(sys.nframe() + pos))), silent = TRUE)
if((class(df) == "try-error") | is.null(thecall$dfxy))
stop("non convenient selection for dfxy (can not be converted to dataframe)")
sortparameters <- sortparamADEg(...)
if(!is.null(facets)) {
if((length(xax) == 1 & length(yax) == 1))
object <- multi.facets.S2(thecall, sortparameters$adepar)
else
stop("Facets are not allowed with multiple xax/yax")
}
else if((length(xax) > 1 | length(yax) > 1)) {
object <- multi.ax.S2(thecall)
}
else {
if(length(sortparameters$rest))
warning(c("Unused parameters: ", paste(unique(names(sortparameters$rest)), " ", sep = "")), call. = FALSE)
g.args <- c(sortparameters$g.args, list(fullcircle = fullcircle))
if(storeData)
tmp_data <- list(dfxy = dfxy, xax = xax, yax = yax, labels = labels, frame = sys.nframe() + pos, storeData = storeData)
else
tmp_data <- list(dfxy = thecall$dfxy, xax = xax, yax = yax, labels = thecall$labels, frame = sys.nframe() + pos, storeData = storeData)
object <- new(Class = "S2.corcircle", data = tmp_data, adeg.par = sortparameters$adepar, trellis.par = sortparameters$trellis, g.args = g.args, Call = as.call(thecall))
prepare(object)
setlatticecall(object)
if(add)
object <- add.ADEg(object)
}
if(! add & plot)
print(object)
invisible(object)
}
|
robyn_plots <- function(InputCollect, OutputCollect, export = TRUE) {
check_class("robyn_outputs", OutputCollect)
pareto_fronts <- OutputCollect$pareto_fronts
hyper_fixed <- OutputCollect$hyper_fixed
temp_all <- OutputCollect$allPareto
all_plots <- list()
if (!hyper_fixed) {
if (!is.null(InputCollect$prophet_vars) && length(InputCollect$prophet_vars) > 0
|| !is.null(InputCollect$factor_vars) && length(InputCollect$factor_vars) > 0)
{
dt_plotProphet <- InputCollect$dt_mod[, c("ds", "dep_var", InputCollect$prophet_vars, InputCollect$factor_vars), with = FALSE]
dt_plotProphet <- suppressWarnings(melt.data.table(dt_plotProphet, id.vars = "ds"))
all_plots[["pProphet"]] <- pProphet <- ggplot(
dt_plotProphet, aes(x = ds, y = value)) +
geom_line(color = "steelblue") +
facet_wrap(~variable, scales = "free", ncol = 1) +
labs(title = "Prophet decomposition") +
xlab(NULL) + ylab(NULL)
if (export) ggsave(
paste0(OutputCollect$plot_folder, "prophet_decomp.png"),
plot = pProphet,
dpi = 600, width = 12, height = 3 * length(levels(dt_plotProphet$variable))
)
}
if (any(InputCollect$exposure_selector)) {
all_plots[["pSpendExposure"]] <- pSpendExposure <- wrap_plots(
InputCollect$plotNLSCollect,
ncol = ifelse(length(InputCollect$plotNLSCollect) <= 3, length(InputCollect$plotNLSCollect), 3)
) +
plot_annotation(
title = "Spend-exposure fitting with Michaelis-Menten model",
theme = theme(plot.title = element_text(hjust = 0.5))
)
if (export) ggsave(
paste0(OutputCollect$plot_folder, "spend_exposure_fitting.png"),
plot = pSpendExposure, dpi = 600, width = 12,
height = ceiling(length(InputCollect$plotNLSCollect) / 3) * 7
)
} else {
}
if (length(temp_all) > 0) {
resultHypParam <- copy(temp_all$resultHypParam)
hpnames_updated <- c(names(OutputCollect$OutputModels$hyper_updated), "robynPareto")
hpnames_updated <- str_replace(hpnames_updated, "lambda", "lambda_hp")
resultHypParam.melted <- melt.data.table(resultHypParam[, hpnames_updated, with = FALSE],
id.vars = c("robynPareto"))
resultHypParam.melted <- resultHypParam.melted[variable == "lambda_hp", variable := "lambda"]
all_plots[["pSamp"]] <- ggplot(
resultHypParam.melted, aes(x = value, y = variable, color = variable, fill = variable)) +
geom_violin(alpha = .5, size = 0) +
geom_point(size = 0.2) +
theme(legend.position = "none") +
labs(
title = "Hyperparameter optimisation sampling",
subtitle = paste0("Sample distribution", ", iterations = ", OutputCollect$iterations, " * ", OutputCollect$trials, " trial"),
x = "Hyperparameter space",
y = NULL
)
if (export) ggsave(
paste0(OutputCollect$plot_folder, "hypersampling.png"),
plot = all_plots$pSamp, dpi = 600, width = 12, height = 7
)
}
if (length(temp_all) > 0) {
pareto_fronts_vec <- 1:pareto_fronts
resultHypParam <- copy(temp_all$resultHypParam)
if (!is.null(InputCollect$calibration_input)) {
resultHypParam[, iterations := ifelse(is.na(robynPareto), NA, iterations)]
}
calibrated <- !is.null(InputCollect$calibration_input)
pParFront <- ggplot(resultHypParam, aes(
x = .data$nrmse, y = .data$decomp.rssd, colour = .data$iterations)) +
scale_colour_gradient(low = "skyblue", high = "navyblue") +
labs(
title = ifelse(!calibrated, "Multi-objective evolutionary performance",
"Multi-objective evolutionary performance with calibration"
),
subtitle = sprintf(
"2D Pareto fronts with %s, for %s trial%s with %s iterations each",
OutputCollect$nevergrad_algo, OutputCollect$trials,
ifelse(pareto_fronts > 1, "s", ""), OutputCollect$iterations
),
x = "NRMSE",
y = "DECOMP.RSSD",
colour = "Iterations",
size = "MAPE",
alpha = NULL
)
if (calibrated) {
pParFront <- pParFront +
geom_point(data = resultHypParam, aes(size = .data$mape, alpha = 1 - .data$mape))
} else {
pParFront <- pParFront + geom_point()
}
for (pfs in 1:max(pareto_fronts_vec)) {
if (pfs == 2) {
pf_color <- "coral3"
} else if (pfs == 3) {
pf_color <- "coral2"
} else {
pf_color <- "coral"
}
pParFront <- pParFront + geom_line(
data = resultHypParam[robynPareto == pfs],
aes(x = .data$nrmse, y = .data$decomp.rssd), colour = pf_color)
}
all_plots[["pParFront"]] <- pParFront
if (export) ggsave(
paste0(OutputCollect$plot_folder, "pareto_front.png"),
plot = pParFront,
dpi = 600, width = 12, height = 7
)
}
if (length(temp_all) > 0) {
xDecompAgg <- copy(temp_all$xDecompAgg)
dt_ridges <- xDecompAgg[rn %in% InputCollect$paid_media_spends
, .(variables = rn
, roi_total
, iteration = (iterNG-1)*OutputCollect$cores+iterPar
, trial)][order(iteration, variables)]
bin_limits <- c(1,20)
qt_len <- ifelse(OutputCollect$iterations <=100, 1,
ifelse(OutputCollect$iterations > 2000, 20, ceiling(OutputCollect$iterations/100)))
set_qt <- floor(quantile(1:OutputCollect$iterations, seq(0, 1, length.out = qt_len+1)))
set_bin <- set_qt[-1]
dt_ridges[, iter_bin := cut(dt_ridges$iteration, breaks = set_qt, labels = set_bin)]
dt_ridges <- dt_ridges[!is.na(iter_bin)]
dt_ridges[, iter_bin := factor(iter_bin, levels = sort(set_bin, decreasing = TRUE))]
dt_ridges[, trial := as.factor(trial)]
all_plots[["pRidges"]] <- pRidges <- ggplot(
dt_ridges, aes(x = roi_total, y = iter_bin, fill = as.integer(iter_bin), linetype = trial)) +
scale_fill_distiller(palette = "GnBu") +
geom_density_ridges(scale = 4, col = "white", quantile_lines = TRUE, quantiles = 2, alpha = 0.7) +
facet_wrap(~ variables, scales = "free") +
guides(fill = "none")+
theme(panel.background = element_blank()) +
labs(x = "Total ROAS", y = "Iteration Bucket"
,title = "ROAS distribution over iteration"
,fill = "iter bucket")
if (export) suppressMessages(ggsave(
paste0(OutputCollect$plot_folder, "roas_convergence.png"),
plot = pRidges, dpi = 600, width = 12,
height = ceiling(InputCollect$mediaVarCount / 3) * 6
))
}
}
return(invisible(all_plots))
}
robyn_onepagers <- function(InputCollect, OutputCollect, selected = NULL, quiet = FALSE, export = TRUE) {
check_class("robyn_outputs", OutputCollect)
pareto_fronts <- OutputCollect$pareto_fronts
hyper_fixed <- OutputCollect$hyper_fixed
resultHypParam <- copy(OutputCollect$resultHypParam)
xDecompAgg <- copy(OutputCollect$xDecompAgg)
if (!is.null(selected)) {
if ("clusters" %in% selected) selected <- OutputCollect$clusters$models$solID
resultHypParam <- resultHypParam[solID %in% selected]
xDecompAgg <- xDecompAgg[solID %in% selected]
if (!quiet) message(">> Exporting only cluster results one-pagers (", nrow(resultHypParam), ")...")
}
if (check_parallel_plot()) registerDoParallel(OutputCollect$cores) else registerDoSEQ()
if (!hyper_fixed) {
pareto_fronts_vec <- 1:pareto_fronts
count_mod_out <- resultHypParam[robynPareto %in% pareto_fronts_vec, .N]
} else {
pareto_fronts_vec <- 1
count_mod_out <- nrow(resultHypParam)
}
all_fronts <- unique(xDecompAgg$robynPareto)
all_fronts <- sort(all_fronts[!is.na(all_fronts)])
if (!all(pareto_fronts_vec %in% all_fronts)) pareto_fronts_vec <- all_fronts
if (check_parallel_plot()) {
if (!quiet) message(paste(">> Plotting", count_mod_out, "selected models on", OutputCollect$cores, "cores..."))
} else {
if (!quiet) message(paste(">> Plotting", count_mod_out, "selected models on 1 core (MacOS fallback)..."))
}
if (!quiet & count_mod_out > 0) pbplot <- txtProgressBar(min = 0, max = count_mod_out, style = 3)
temp <- OutputCollect$allPareto$plotDataCollect
all_plots <- list()
cnt <- 0
for (pf in pareto_fronts_vec) {
plotMediaShare <- xDecompAgg[robynPareto == pf & rn %in% InputCollect$paid_media_spends]
uniqueSol <- plotMediaShare[, unique(solID)]
parallelResult <- foreach(sid = uniqueSol) %dorng% {
plotMediaShareLoop <- plotMediaShare[solID == sid]
rsq_train_plot <- plotMediaShareLoop[, round(unique(rsq_train), 4)]
nrmse_plot <- plotMediaShareLoop[, round(unique(nrmse), 4)]
decomp_rssd_plot <- plotMediaShareLoop[, round(unique(decomp.rssd), 4)]
mape_lift_plot <- ifelse(!is.null(InputCollect$calibration_input), plotMediaShareLoop[, round(unique(mape), 4)], NA)
plotMediaShareLoopBar <- temp[[sid]]$plot1data$plotMediaShareLoopBar
plotMediaShareLoopLine <- temp[[sid]]$plot1data$plotMediaShareLoopLine
ySecScale <- temp[[sid]]$plot1data$ySecScale
p1 <- ggplot(plotMediaShareLoopBar, aes(x = .data$rn, y = .data$value, fill = .data$variable)) +
geom_bar(stat = "identity", width = 0.5, position = "dodge") +
geom_text(aes(label = paste0(round(.data$value * 100, 2), "%")),
color = "darkblue", position = position_dodge(width = 0.5), fontface = "bold") +
geom_line(data = plotMediaShareLoopLine, aes(
x = .data$rn, y = .data$value / ySecScale, group = 1, color = .data$variable),
inherit.aes = FALSE) +
geom_point(data = plotMediaShareLoopLine, aes(
x = .data$rn, y = .data$value / ySecScale, group = 1, color = .data$variable),
inherit.aes = FALSE, size = 4) +
geom_text(
data = plotMediaShareLoopLine, aes(
label = round(.data$value, 2), x = .data$rn, y = .data$value / ySecScale, group = 1, color = .data$variable),
fontface = "bold", inherit.aes = FALSE, hjust = -1, size = 6
) +
scale_y_continuous(sec.axis = sec_axis(~ . * ySecScale)) +
coord_flip() +
theme(legend.title = element_blank(), legend.position = c(0.9, 0.2), axis.text.x = element_blank()) +
scale_fill_brewer(palette = "Paired") +
labs(
title = paste0("Share of Spend VS Share of Effect with total ", ifelse(InputCollect$dep_var_type == "conversion", "CPA", "ROI")),
subtitle = paste0(
"rsq_train: ", rsq_train_plot,
", nrmse = ", nrmse_plot,
", decomp.rssd = ", decomp_rssd_plot,
ifelse(!is.na(mape_lift_plot), paste0(", mape.lift = ", mape_lift_plot), "")
),
y = NULL, x = NULL
)
plotWaterfallLoop <- temp[[sid]]$plot2data$plotWaterfallLoop
p2 <- suppressWarnings(
ggplot(plotWaterfallLoop, aes(x = id, fill = sign)) +
geom_rect(aes(x = rn, xmin = id - 0.45, xmax = id + 0.45,
ymin = end, ymax = start), stat = "identity") +
scale_x_discrete("", breaks = levels(plotWaterfallLoop$rn), labels = plotWaterfallLoop$rn) +
theme(axis.text.x = element_text(angle = 65, vjust = 0.6), legend.position = c(0.1, 0.1)) +
geom_text(mapping = aes(
label = paste0(format_unit(xDecompAgg), "\n", round(xDecompPerc * 100, 2), "%"),
y = rowSums(cbind(plotWaterfallLoop$end, plotWaterfallLoop$xDecompPerc / 2))
), fontface = "bold") +
coord_flip() +
labs(
title = "Response decomposition waterfall by predictor",
subtitle = paste0(
"rsq_train: ", rsq_train_plot,
", nrmse = ", nrmse_plot,
", decomp.rssd = ", decomp_rssd_plot,
ifelse(!is.na(mape_lift_plot), paste0(", mape.lift = ", mape_lift_plot), "")
),
x = NULL, y = NULL
))
if (InputCollect$adstock == "geometric") {
dt_geometric <- temp[[sid]]$plot3data$dt_geometric
p3 <- ggplot(dt_geometric, aes(x = .data$channels, y = .data$thetas, fill = "coral")) +
geom_bar(stat = "identity", width = 0.5) +
theme(legend.position = "none") +
coord_flip() +
geom_text(aes(label = paste0(round(thetas * 100, 1), "%")),
position = position_dodge(width = 0.5), fontface = "bold") +
ylim(0, 1) +
labs(
title = "Geometric adstock - fixed decay rate over time",
subtitle = paste0(
"rsq_train: ", rsq_train_plot,
", nrmse = ", nrmse_plot,
", decomp.rssd = ", decomp_rssd_plot,
ifelse(!is.na(mape_lift_plot), paste0(", mape.lift = ", mape_lift_plot), "")
),
y = NULL, x = NULL
)
}
if (InputCollect$adstock %in% c("weibull_cdf", "weibull_pdf")) {
weibullCollect <- temp[[sid]]$plot3data$weibullCollect
wb_type <- temp[[sid]]$plot3data$wb_type
p3 <- ggplot(weibullCollect, aes(x = .data$x, y = .data$decay_accumulated)) +
geom_line(aes(color = .data$channel)) +
facet_wrap(~.data$channel) +
geom_hline(yintercept = 0.5, linetype = "dashed", color = "gray") +
geom_text(aes(x = max(.data$x), y = 0.5, vjust = -0.5, hjust = 1, label = "Halflife"), colour = "gray") +
theme(legend.position = "none") +
labs(title = paste0("Weibull adstock ", wb_type," - flexible decay rate over time"),
subtitle = paste0(
"rsq_train: ", rsq_train_plot,
", nrmse = ", nrmse_plot,
", decomp.rssd = ", decomp_rssd_plot,
ifelse(!is.na(mape_lift_plot), paste0(", mape.lift = ", mape_lift_plot), "")
),
x = "Time unit", y = NULL)
}
dt_scurvePlot <- temp[[sid]]$plot4data$dt_scurvePlot
dt_scurvePlotMean <- temp[[sid]]$plot4data$dt_scurvePlotMean
if (!"channel" %in% colnames(dt_scurvePlotMean)) dt_scurvePlotMean$channel <- dt_scurvePlotMean$rn
p4 <- ggplot(dt_scurvePlot[dt_scurvePlot$channel %in% InputCollect$paid_media_spends,],
aes(x = .data$spend, y = .data$response, color = .data$channel)) +
geom_line() +
geom_point(data = dt_scurvePlotMean, aes(
x = .data$mean_spend, y = .data$mean_response, color = .data$channel)) +
geom_text(data = dt_scurvePlotMean, aes(
x = .data$mean_spend, y = .data$mean_response, color = .data$channel,
label = formatNum(.data$mean_spend, 2, abbr = TRUE)),
show.legend = FALSE, hjust = -0.2) +
theme(legend.position = c(0.9, 0.2)) +
labs(
title = "Response curve and mean spend by channel",
subtitle = paste0(
"rsq_train: ", rsq_train_plot,
", nrmse = ", nrmse_plot,
", decomp.rssd = ", decomp_rssd_plot,
ifelse(!is.na(mape_lift_plot), paste0(", mape.lift = ", mape_lift_plot), "")
),
x = "Spend", y = "Response"
) + lares::scale_x_abbr() + lares::scale_y_abbr()
xDecompVecPlotMelted <- temp[[sid]]$plot5data$xDecompVecPlotMelted
p5 <- ggplot(xDecompVecPlotMelted, aes(x = .data$ds, y = .data$value, color = .data$variable)) +
geom_line() +
theme(legend.position = c(0.9, 0.9)) +
labs(
title = "Actual vs. predicted response",
subtitle = paste0(
"rsq_train: ", rsq_train_plot,
", nrmse = ", nrmse_plot,
", decomp.rssd = ", decomp_rssd_plot,
ifelse(!is.na(mape_lift_plot), paste0(", mape.lift = ", mape_lift_plot), "")
),
x = "Date", y = "Response"
)
xDecompVecPlot <- temp[[sid]]$plot6data$xDecompVecPlot
p6 <- qplot(x = .data$predicted, y = .data$actual - .data$predicted, data = xDecompVecPlot) +
geom_hline(yintercept = 0) +
geom_smooth(se = TRUE, method = "loess", formula = "y ~ x") +
xlab("Fitted") + ylab("Residual") + ggtitle("Fitted vs. Residual")
onepagerTitle <- paste0("Model one-pager, on pareto front ", pf, ", ID: ", sid)
pg <- wrap_plots(p2, p5, p1, p4, p3, p6, ncol = 2) +
plot_annotation(title = onepagerTitle, theme = theme(plot.title = element_text(hjust = 0.5)))
all_plots[[sid]] <- pg
if (export) {
ggsave(
filename = paste0(OutputCollect$plot_folder, "/", sid, ".png"),
plot = pg,
dpi = 600, width = 18, height = 18
)
}
if (check_parallel_plot() & !quiet & count_mod_out > 0) {
cnt <- cnt + 1
setTxtProgressBar(pbplot, cnt)
}
}
if (!quiet & count_mod_out > 0) {
cnt <- cnt + length(uniqueSol)
setTxtProgressBar(pbplot, cnt)
}
}
if (!quiet & count_mod_out > 0) close(pbplot)
if (check_parallel_plot()) stopImplicitCluster()
return(invisible(all_plots))
}
allocation_plots <- function(InputCollect, OutputCollect, dt_optimOut, select_model, scenario, export = TRUE, quiet = FALSE) {
plotDT_resp <- dt_optimOut[, c("channels", "initResponseUnit", "optmResponseUnit")][order(rank(channels))]
plotDT_resp[, channels := as.factor(channels)]
chn_levels <- plotDT_resp[, as.character(channels)]
plotDT_resp[, channels := factor(channels, levels = chn_levels)]
setnames(plotDT_resp, names(plotDT_resp), new = c("channel", "initial response / time unit", "optimised response / time unit"))
plotDT_resp <- suppressWarnings(melt.data.table(plotDT_resp, id.vars = "channel", value.name = "response"))
p12 <- ggplot(plotDT_resp, aes(x = .data$channel, y = .data$response, fill = .data$variable)) +
geom_bar(stat = "identity", width = 0.5, position = "dodge") +
coord_flip() +
scale_fill_brewer(palette = "Paired") +
geom_text(aes(label = round(.data$response, 0), hjust = 1, size = 2.0),
position = position_dodge(width = 0.5), fontface = "bold", show.legend = FALSE
) +
theme(
legend.title = element_blank(), legend.position = c(0.8, 0.2),
axis.text.x = element_blank(), legend.background = element_rect(
colour = "grey", fill = "transparent"
)
) +
labs(
title = "Initial vs. optimised mean response",
subtitle = paste0(
"Total spend increases ", dt_optimOut[
, round(mean(optmSpendUnitTotalDelta) * 100, 1)
], "%",
"\nTotal response increases ", dt_optimOut[
, round(mean(optmResponseUnitTotalLift) * 100, 1)
], "% with optimised spend allocation"
),
y = NULL, x = "Channels"
)
plotDT_share <- dt_optimOut[, c("channels", "initSpendShare", "optmSpendShareUnit")][order(rank(channels))]
plotDT_share[, channels := as.factor(channels)]
chn_levels <- plotDT_share[, as.character(channels)]
plotDT_share[, channels := factor(channels, levels = chn_levels)]
setnames(plotDT_share, names(plotDT_share), new = c("channel", "initial avg.spend share", "optimised avg.spend share"))
plotDT_share <- suppressWarnings(melt.data.table(plotDT_share, id.vars = "channel", value.name = "spend_share"))
p13 <- ggplot(plotDT_share, aes(x = .data$channel, y = .data$spend_share, fill = .data$variable)) +
geom_bar(stat = "identity", width = 0.5, position = "dodge") +
coord_flip() +
scale_fill_brewer(palette = "Paired") +
geom_text(aes(label = paste0(round(.data$spend_share * 100, 2), "%"), hjust = 1, size = 2.0),
position = position_dodge(width = 0.5), fontface = "bold", show.legend = FALSE
) +
theme(
legend.title = element_blank(), legend.position = c(0.8, 0.2),
axis.text.x = element_blank(), legend.background = element_rect(
colour = "grey", fill = "transparent"
)
) +
labs(
title = "Initial vs. optimised budget allocation",
subtitle = paste0(
"Total spend increases ", dt_optimOut[, round(mean(optmSpendUnitTotalDelta) * 100, 1)], "%",
"\nTotal response increases ", dt_optimOut[, round(mean(optmResponseUnitTotalLift) * 100, 1)], "% with optimised spend allocation"
),
y = NULL, x = "Channels"
)
plotDT_saturation <- melt.data.table(OutputCollect$mediaVecCollect[
solID == select_model & type == "saturatedSpendReversed"
], id.vars = "ds", measure.vars = InputCollect$paid_media_spends, value.name = "spend", variable.name = "channel")
plotDT_decomp <- melt.data.table(OutputCollect$mediaVecCollect[
solID == select_model & type == "decompMedia"
], id.vars = "ds", measure.vars = InputCollect$paid_media_spends, value.name = "response", variable.name = "channel")
plotDT_scurve <- cbind(plotDT_saturation, plotDT_decomp[, .(response)])
plotDT_scurve <- plotDT_scurve[spend >= 0]
plotDT_scurveMeanResponse <- OutputCollect$xDecompAgg[solID == select_model & rn %in% InputCollect$paid_media_spends]
dt_optimOutScurve <- rbind(dt_optimOut[, .(channels, initSpendUnit, initResponseUnit)][, type := "initial"],
dt_optimOut[, .(channels, optmSpendUnit, optmResponseUnit)][, type := "optimised"], use.names = FALSE)
setnames(dt_optimOutScurve, c("channels", "spend", "response", "type"))
p14 <- ggplot(data = plotDT_scurve, aes(x = .data$spend, y = .data$response, color = .data$channel)) +
geom_line() +
geom_point(data = dt_optimOutScurve, aes(
x = .data$spend, y = .data$response, color = .data$channels, shape = .data$type), size = 2) +
geom_text(data = dt_optimOutScurve, aes(
x = .data$spend, y = .data$response, color = .data$channels,
label = formatNum(.data$spend, 2, abbr = TRUE)),
show.legend = FALSE, hjust = -0.2) +
theme(legend.position = c(0.9, 0.4), legend.title = element_blank()) +
labs(
title = "Response curve and mean spend by channel",
subtitle = paste0(
"rsq_train: ", plotDT_scurveMeanResponse[, round(mean(rsq_train), 4)],
", nrmse = ", plotDT_scurveMeanResponse[, round(mean(nrmse), 4)],
", decomp.rssd = ", plotDT_scurveMeanResponse[, round(mean(decomp.rssd), 4)],
", mape.lift = ", plotDT_scurveMeanResponse[, round(mean(mape), 4)]
),
x = "Spend", y = "Response"
) + lares::scale_x_abbr() + lares::scale_y_abbr()
grobTitle <- paste0("Budget allocator optimum result for model ID ", select_model)
plots <- (p13 + p12) / p14 + plot_annotation(
title = grobTitle, theme = theme(plot.title = element_text(hjust = 0.5))
)
if (export) {
scenario <- ifelse(scenario == "max_historical_response", "hist", "respo")
filename <- paste0(OutputCollect$plot_folder, select_model, "_reallocated_", scenario, ".png")
if (!quiet) message("Exporting charts into file: ", filename)
ggsave(
filename = filename,
plot = plots,
dpi = 400, width = 18, height = 14, limitsize = FALSE
)
}
return(list(p12 = p12, p13 = p13, p14 = p14))
}
|
test_that("Benvo rejects inappropriate structures", {
expect_error(benvo(subject_data = data.frame(a=1,b=2),
sub_bef_data =list(FFR=data.frame(c=1,d=2)),by='a'),regexp = "common")
expect_error(benvo(subject_data = data.frame(a=1,b=2),
sub_bef_data = list()))
expect_error(benvo(subject_data = 7,
sub_bef_data =list(data.frame(c=1,b=2))))
})
test_that("Benvo accepts appropriate structures",{
expect_silent(benvo(subject_data = FFR_subjects,
sub_bef_data = list(FFR=FFR_distances),by='id'))
expect_message(benvo(subject_data = FFR_subjects,
sub_bef_data = list(FFR=FFR_distances)),regexp="id")
expect_message(benvo(subject_data = FFR_subjects,
sub_bef_data = list(FFR_distances),by = "id"),regexp = "generic names")
expect_silent(benvo(subject_data = FFR_subjects,
sub_bef_data = list(FFR=FFR_distances),by = "id"))
expect_silent(benvo(subject_data = HFS_subjects,
sub_bef_data = list(HFS=HFS_distances_times),by=c('id','measurement')))
expect_message(benvo(subject_data = HFS_subjects,
sub_bef_data = list(HFS=HFS_distances_times)),regexp = 'measurement')
expect_silent(benvo(subject_data = HFS_subjects,
sub_bef_data = list(HFS=HFS_distances_times),by=c("id","measurement")))
})
test_that("Benvo correctly identifies id",{
expect_equal(c("id","measurement"),attr(benvo(subject_data = HFS_subjects,
sub_bef_data = list(HFS=HFS_distances_times)),'id'))
expect_equal("cid",attr(benvo(subject_data = data.frame(cid = c("a","b"),
BMI = rnorm(2)),
sub_bef_data = list(data.frame(cid=c("a","a","b","b"),
Distance=rnorm(4)))),
"id"))
expect_warning(benvo(subject_data = data.frame(cid = factor(c("a","b")),
BMI = rnorm(2)),
sub_bef_data = list(data.frame(cid=factor(c("a","a","b","b")),
Distance=rnorm(4)))),"data column")
})
test_that("Benvo simple methods work",{
expect_output(print(FFbenvo),"tibble")
expect_output(summary(FFbenvo),"Observations")
expect_output(summary(longitudinal_HFS),
regexp = "Subjects:")
expect_invisible(summary(FFbenvo))
expect_invisible(summary(longitudinal_HFS))
})
test_that("benvo does not alter entered dfs",{
expect_equal(FFR_subjects,FFbenvo$subject_data)
expect_equal(FFR_distances,FFbenvo$sub_bef_data[[1]])
})
|
mogi1 <-
function(d=1, f=1, a=0.1, P=1e5, mu=4e+09, nu=0.25)
{
if(missing(d)) { d = 1}
if(missing(f)) {f=1}
if(missing(a)) {a=0.1}
if(missing(P)) {P=1e5}
if(missing(mu)) {mu=4e+09}
if(missing(nu)) { nu = 0.25 }
denom = (4*mu*(f^2 + d^2)^(1.5))
DELTAd = 3*a^3*P*d/denom
DELTAh = 3*a^3*P*f/denom
return(list(ur=DELTAd, uz=DELTAh))
}
|
library(testthat)
library(googleway)
test_check("googleway")
|
count_edges <- function(graph) {
fcn_name <- get_calling_fcn()
if (graph_object_valid(graph) == FALSE) {
emit_error(
fcn_name = fcn_name,
reasons = "The graph object is not valid")
}
if (is_graph_empty(graph)) {
return(0)
}
nrow(graph$edges_df)
}
|
glrtReg <-
function(data, type, groups){
regCoeffHA <- glmReg(data, type, groups)
regCoeffH0 <- glmReg(data, type, 0)
glrt <- 2 * (regCoeffHA$loglik - regCoeffH0$loglik)
return(glrt)
}
|
two_scatter <- function(fit,new.data=NULL,
code.0='Alive',
code.1='Dead',
code.highrisk='High',
code.lowrisk='Low',
cutoff.show=TRUE,
cutoff.value='median',
cutoff.x,
cutoff.y,
cutoff.label,
title.A.ylab='Risk Score',
title.B.ylab='Survival Time',
title.xlab='Rank',
title.A.legend='Risk Group',
title.B.legend='Status',
size.AB=1.5,
size.ylab.title=14,
size.xlab.title=14,
size.Atext=11,
size.Btext=11,
size.xtext=11,
size.xyticks=0.5,
size.xyline=0.5,
size.points=2,
size.dashline=1,
size.cutoff=5,
size.legendtitle=13,
size.legendtext=12,
color.A=c(low='blue',high='red'),
color.B=c(code.0='blue',code.1='red'),
vjust.A.ylab=1,
vjust.B.ylab=2,
family='sans',
expand.x=3) {
fit=to.cph(fit)
if (is.null(new.data)) data=model.data(fit) else data=new.data
event=model.y(fit)[2]
time=model.y(fit)[1]
riskscore = predict(fit,type = 'lp',newdata = data)
data2 = cbind(data, riskscore)
data3 = data2[order(data2$riskscore), ]
if (cutoff.value == 'roc') {
cutoff.point = cutoff::roc(score = data3$riskscore,
class = data3[,event])$cutoff
} else if (cutoff.value == 'cutoff') {
rs = cutoff::cox(
data = data3,
time = time,
y = event,
x = 'riskscore',
cut.numb = 1,
n.per = 0.1,
y.per = 0.1,
round = 20
)
to.numeric(rs$p.adjust)=1
cutoff.point = (rs$cut1[rs$p.adjust == min(rs$p.adjust)])
if (length(cutoff.point)>1) cutoff.point=cutoff.point[1]
} else if (cutoff.value == 'median') {
cutoff.point=median(x = data3$riskscore,na.rm = TRUE)
}else{
cutoff.point=cutoff.value
}
if (cutoff.point < min(riskscore) || cutoff.point>max(riskscore)){
stop('cutoff must between ',min(riskscore),' and ',max(riskscore))
}
prob=rms::Survival(fit)(times = median(data3[,time]),lp = riskscore)
correlaiton=cor(prob,riskscore,method = 'spearman')
if (correlaiton<0) {
`Risk Group` = ifelse(data3$riskscore > cutoff.point,code.highrisk,code.lowrisk)
} else{
`Risk Group` = ifelse(data3$riskscore < cutoff.point,code.highrisk,code.lowrisk)
}
data4 = cbind(data3, `Risk Group`)
cut.position=(1:nrow(data4))[data4$riskscore == cutoff.point]
if (length(cut.position)==0){
cut.position=which.min(abs(data4$riskscore - cutoff.point))
}else if (length(cut.position)>1){
cut.position=cut.position[length(cut.position)]
}
data4$riskscore=round(data4$riskscore,1)
data4[, time]=round(data4[, time],1)
color.A=c(color.A['low'],color.A['high'])
names(color.A)=c(code.lowrisk,code.highrisk)
fA = ggplot(data = data4,
aes_string(
x = 1:nrow(data4),
y = data4$riskscore,
color=factor(`Risk Group`)
)
) +
geom_point(size = size.points) +
scale_color_manual(name=title.A.legend,values = color.A) +
geom_vline(
xintercept = cut.position,
linetype = 'dotted',
size = size.dashline
) +
theme(
panel.grid = element_blank(),
panel.background = element_blank())+
theme(
axis.ticks.x = element_blank(),
axis.line.x = element_blank(),
axis.text.x = element_blank(),
axis.title.x = element_blank()
) +
theme(
axis.title.y = element_text(
size = size.ylab.title,vjust = vjust.A.ylab,angle = 90,family=family),
axis.text.y = element_text(size=size.Atext,family = family),
axis.line.y = element_line(size=size.xyline,colour = "black"),
axis.ticks.y = element_line(size = size.xyticks,colour = "black"))+
theme(legend.title = element_text(size = size.legendtitle,family = family),
legend.text = element_text(size=size.legendtext,family = family))+
coord_trans()+
ylab(title.A.ylab)+
scale_x_continuous(expand = c(0,expand.x))
fA
if (cutoff.show){
if (missing(cutoff.label)) cutoff.label=paste0('cutoff: ',round(cutoff.point,2))
if (missing(cutoff.x)) cutoff.x=cut.position+3
if (missing(cutoff.y)) cutoff.y=cutoff.point
fA=fA+ annotate("text",
x=cutoff.x,
y=cutoff.y,
label=cutoff.label,
family=family,
size=size.cutoff,
fontface="plain",
colour="black")
}
fA
color.B=c(color.B['code.0'],color.B['code.1'])
names(color.B)=c(code.0,code.1)
fB=ggplot(data = data4,
aes_string(
x = 1:nrow(data4),
y = data4[, time],
color=factor(ifelse(data4[,event]==1,code.1,code.0)))
) +
geom_point(size=size.points)+
scale_color_manual(name=title.B.legend,values = color.B) +
geom_vline(
xintercept = cut.position,
linetype = 'dotted',
size = size.dashline
) +
theme(
panel.grid = element_blank(),
panel.background = element_blank())+
theme(
axis.line.x = element_line(size=size.xyline,colour = "black"),
axis.ticks.x = element_line(size=size.xyline,colour = "black"),
axis.text.x = element_text(size=size.xtext,family = family),
axis.title.x = element_text(size = size.xlab.title,family=family)
) +
theme(
axis.title.y = element_text(
size = size.ylab.title,vjust = vjust.B.ylab,angle = 90,family=family),
axis.text.y = element_text(size=size.Btext,family = family),
axis.ticks.y = element_line(size = size.xyticks),
axis.line.y = element_line(size=size.xyline,colour = "black")
)+
theme(legend.title = element_text(size = size.legendtitle,family = family),
legend.text = element_text(size=size.legendtext,family = family))+
ylab(title.B.ylab)+xlab(title.xlab)+
coord_trans()+
scale_x_continuous(expand = c(0,expand.x))
fB
egg::ggarrange(
fA,
fB,
ncol = 1,
labels = c('A', 'B'),
label.args = list(gp = grid::gpar(font = 2, cex =size.AB,
family=family))
)
}
|
hgt <- function(x, size, active.entry = NULL, bcd.opt = list("max.iter" = 10, "eps" = 1e-3)) {
stopifnot(!anyNA(x))
stopifnot(!missing(size) | !is.null(active.entry))
p <- ncol(x)
if(!isSymmetric(x)) {
s <- var(x)
} else {
s <- x
}
max.iter <- bcd.opt[["max.iter"]]
eps <- bcd.opt[["eps"]]
stopifnot(round(max.iter, 0) == max.iter)
stopifnot(max.iter > 0)
stopifnot(eps > 0)
if(!is.null(active.entry)) {
if(ncol(active.entry) != 2) {
stop("Arguments active.entry is invalid!")
}
if(any(active.entry[, 1] == active.entry[, 2])) {
stop("Digonal entries should not be included in arguments active.entry!")
}
active_index <- as.vector(active.entry)
if(any(active_index > p) | any(active_index < 1)) {
stop("Arguments active.entry is invalid since subscript out of bounds!")
}
double_active_entry <- rbind(active.entry, active.entry[, 2:1])
if(any(duplicated(double_active_entry))) {
stop("Symmetric positions of off-diagonal entries should be considered once in arguments active.entry!")
}
act_set <- active.entry - 1
Omega <- bcd(s, act_set, iter_max = max.iter, eps = eps)
} else {
if (size > (p ^ 2 - p) / 2) {
stop("Arguments size is too large!")
}
if (size < 0) {
stop("Arguments size should be greater than zero!")
}
S_init <- cov2cor(s)
diag(S_init) <- 0
S_vec <- as.vector(abs(S_init))
lambda <- sort(S_vec, decreasing = TRUE)[2 * size + 1]
S_init[abs(S_init) <= lambda] <- 0
non_zero_index <- which(as.matrix(S_init) != 0, arr.ind = TRUE)
active.entry <- non_zero_index[which(non_zero_index[,1] < non_zero_index[,2]),]
act_set <- active.entry - 1
Omega <- bcd(s, act_set, iter_max = max.iter, eps = eps)
}
return(list(Omega = Omega, active.entry = active.entry))
}
sgt <- function(x, lambda, size = NULL) {
stopifnot(!missing(lambda) | !is.null(size))
stopifnot(!anyNA(x))
if(!isSymmetric(x)) {
s <- cov(x)
} else {
s <- x
}
p <- ncol(x)
if(!missing(lambda)) {
S_init <- s
diag(S_init) <- 0
} else {
if (size > (p ^ 2 - p) / 2) {
stop("Arguments size is too large!")
}
if (size < 0) {
stop("Arguments size should be greater than zero!")
}
S_init <- s
diag(S_init) <- 0
S_vec <- as.vector(abs(S_init))
lambda <- sort(S_vec, decreasing = TRUE)[2 * size + 1]
}
S_init[abs(S_init) <= lambda] <- 0
non_zero_index <- which(as.matrix(S_init) != 0, arr.ind = TRUE)
active.entry <- non_zero_index[which(non_zero_index[,1] < non_zero_index[,2]),]
act_set <- active.entry - 1
res <- soft_GT(s, lambda, act_set)
Omega <- res[["Omega"]]
is.acyclic <- res[["is.acyclic"]]
return(list(Omega = Omega, active.entry = active.entry, is.acyclic = is.acyclic))
}
|
transformPhylo.ML <- function (y, phy, model = NULL, modelCIs = TRUE, nodeIDs = NULL,
rateType = NULL, minCladeSize = 1, nSplits = 2, splitTime = NULL,
boundaryAge = 10, testAge = 1, restrictNode = NULL, lambdaEst = FALSE,
acdcScalar = FALSE, branchLabels = NULL, hiddenSpeciation = FALSE,
full.phy = NULL, useMean = FALSE, profilePlot = FALSE, lowerBound = NULL,
upperBound = NULL, covPIC = TRUE, n.cores = 1, tol = NULL,
meserr = NULL, controlList = c(fnscale = -1, maxit = 100,
factr = 1e-07, pgtol = 0, type = 2, lmm = 5), returnPhy = FALSE,
print.warnings = FALSE, mode.order = NULL, rate.var = FALSE,
testShiftTimes = NULL, saveAll = TRUE)
{
model <- tolower(model)
all.models <- c("bm", "kappa", "lambda", "delta", "ou", "acdc",
"psi", "multipsi", "trend", "free", "clade", "tm1", "tm2",
"timeslice", "modeslice")
if (any(is.na((match(model, all.models)))))
stop(paste(model, "not recognised - please provide one of",
paste0(all.models, collapse = ", ")))
bounds <- matrix(c(1e-08, 1, 1e-08, 1, 1e-08, 5, 1e-08, 20,
0, 1, 1e-08, 1000, 1e-10, 20), 7, 2, byrow = TRUE)
rownames(bounds) <- c("kappa", "lambda", "delta", "alpha",
"psi", "rate", "acdcrate")
lower.function.warning <- function() if (print.warnings)
warning("Confidence limits fall outside parameter bounds - consider changing lowerBound")
upper.function.warning <- function() if (print.warnings)
warning("Confidence limits fall outside parameter bounds - consider changing upperBound")
aic.fun <- function(likelihood, k) return(-2 * likelihood +
2 * k)
aicc.fun <- function(likelihood, k, n) return(-2 * likelihood +
2 * k + ((2 * k * (k + 1))/(n - k - 1)))
if (acdcScalar && !is.null(nodeIDs))
upperBound <- -1e-06
x <- NULL
switch(model, bm = {
phy <- transformPhylo(phy = phy, model = "bm", meserr = meserr,
y = y)
out <- likTraitPhylo(y, phy, covPIC = covPIC)
out$logLikelihood <- out[[2]]
out$brownianVariance <- out[[1]]
out$root.state <- apply(y, 2, function(col.y) as.numeric(ace(col.y,
phy, method = "pic")[[1]][1]))
out$AIC <- aic.fun(out$logLikelihood, 2)
out$AICc <- aicc.fun(out$logLikelihood, 2, Ntip(phy))
if (returnPhy) out$bmPhy <- phy
class(out) <- "bm.ML"
}, lambda = {
if (is.null(lowerBound)) {
lowerBound <- bounds["lambda", 1]
}
if (is.null(upperBound)) {
upperBound <- bounds["lambda", 2]
}
lambda <- runif(1, lowerBound, upperBound)
var.funlambda <- function(lambda) {
return(transformPhylo.ll(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr, covPIC = covPIC)[[2]])
}
vo <- optim(lambda, var.funlambda, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
if (modelCIs == TRUE) {
lambda.fun <- function(param) {
ll <- transformPhylo.ll(y, phy, model = "lambda",
lambda = param, meserr = meserr, covPIC = covPIC)$logLikelihood
return(ll - vo$value + 1.92)
}
if (lambda.fun(lowerBound) < 0) {
LCI <- uniroot(lambda.fun, interval = c(lowerBound,
vo$par))$root
} else {
LCI <- lowerBound
lower.function.warning()
}
if (lambda.fun(upperBound) < 0) {
UCI <- uniroot(lambda.fun, interval = c(vo$par,
upperBound))$root
} else {
UCI <- upperBound
upper.function.warning()
}
out <- list()
out$MaximumLikelihood <- vo$value
out$Lambda <- matrix(c(vo$par, LCI, UCI), 1, 3, byrow = TRUE)
colnames(out$Lambda) <- c("MLLambda", "LowerCI",
"UpperCI")
} else {
out <- list()
out$MaximumLikelihood <- vo$value
out$Lambda <- matrix(vo$par, 1, 1, byrow = TRUE)
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0))
lambdaCurve <- Vectorize(lambda.fun)
curve(lambdaCurve(x), from = lowerBound[1], to = upperBound[1],
xlab = expression(paste("Pagel's ", lambda)),
ylab = "log-likelihood", las = 1, main = "profile plot",
lwd = 2)
if (modelCIs) {
abline(v = c(LCI, vo$par[1], UCI), lty = c(3,
2, 3), lwd = 2, col = "
}
}
lambdaPhy <- transformPhylo(y = y, phy = phy, model = "lambda",
lambda = vo$par[1], meserr = meserr)
out$brownianVariance <- likTraitPhylo(y = y, phy = lambdaPhy,
covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(ace(col.y,
phy = lambdaPhy, method = "pic")[[1]][1]))
out$AIC <- aic.fun(out$MaximumLikelihood, 3)
out$AICc <- aicc.fun(out$MaximumLikelihood, 3, Ntip(lambdaPhy))
if (returnPhy) out$lambdaPhy <- lambdaPhy
class(out) <- "lambda.ML"
}, kappa = {
if (is.null(nodeIDs)) {
nodeIDs <- Ntip(phy) + 1
} else {
nodeIDs <- nodeIDs
}
if (is.null(lowerBound)) {
lowerBound <- bounds["kappa", 1]
if (lambdaEst) lowerBound[2] <- bounds["lambda",
1]
}
if (is.null(upperBound)) {
upperBound <- bounds["kappa", 2]
if (lambdaEst) upperBound[2] <- bounds["lambda",
2]
}
kappa <- runif(1, lowerBound[1], upperBound[1])
if (lambdaEst) kappa[2] <- runif(1, lowerBound[2], upperBound[2])
var.funkappa <- function(param) {
if (length(param) != 2) {
lambda <- 1
} else {
lambda <- param[2]
}
kappa <- param[1]
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
return(transformPhylo.ll(y = y, phy = lambdaPhy,
kappa = kappa, nodeIDs = nodeIDs, model = "kappa",
meserr = meserr, covPIC = covPIC)[[2]])
}
vo <- optim(kappa, var.funkappa, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
if (lambdaEst) {
lambda <- vo$par[2]
} else {
lambda <- 1
}
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
if (modelCIs == TRUE) {
kappa.fun <- function(param, chiSq = TRUE) {
ll <- transformPhylo.ll(y = y, phy = lambdaPhy,
kappa = param, model = "kappa", meserr = meserr,
covPIC = covPIC)$logLikelihood
if (chiSq) return(ll - vo$value + 1.92) else return(ll)
}
if (kappa.fun(lowerBound[1]) < 0) {
LCI <- uniroot(kappa.fun, interval = c(lowerBound[1],
vo$par[1]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
if (kappa.fun(upperBound[1]) < 0) {
UCI <- uniroot(kappa.fun, interval = c(vo$par[1],
upperBound[1]))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0))
kappaCurve <- Vectorize(kappa.fun)
curve(kappaCurve(x, FALSE), from = lowerBound[1],
to = upperBound[1], xlab = expression(kappa),
ylab = "log-likelihood", las = 1, main = "profile plot",
lwd = 2)
if (modelCIs) {
abline(v = c(LCI, vo$par[1], UCI), lty = c(3,
2, 3), lwd = 1, col = "
}
}
out <- list()
out$MaximumLikelihood <- vo$value[1]
if (modelCIs) {
out$Kappa <- matrix(NA, 1, 3, byrow = TRUE)
out$Kappa[1, ] <- c(vo$par[1], LCI, UCI)
colnames(out$Kappa) <- c("MLKappa", "LowerCI", "UpperCI")
} else {
out$Kappa <- matrix(NA, 1, 1, byrow = TRUE)
out$Kappa[1, ] <- c(vo$par[1])
colnames(out$Kappa) <- c("MLKappa")
}
kappaPhy <- transformPhylo(y = y, phy = lambdaPhy, model = "kappa",
kappa = vo$par[1], meserr = meserr)
out$brownianVariance <- likTraitPhylo(y = y, phy = kappaPhy,
covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(ace(col.y,
kappaPhy, method = "pic")[[1]][1]))
param <- 3
if (lambdaEst) {
out$lambda <- vo$par[2]
param <- 4
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$kappaPhy <- kappaPhy
class(out) <- "kappa.ML"
}, delta = {
if (is.null(nodeIDs)) {
nodeIDs <- Ntip(phy) + 1
} else {
nodeIDs <- nodeIDs
}
if (is.null(lowerBound)) {
lowerBound <- bounds["delta", 1]
if (lambdaEst) lowerBound[2] <- bounds["lambda",
1]
}
if (is.null(upperBound)) {
upperBound <- bounds["delta", 2]
if (lambdaEst) upperBound[2] <- bounds["lambda",
2]
}
delta <- runif(1, lowerBound[1], upperBound[1])
if (lambdaEst) delta[2] <- runif(1, lowerBound[2], upperBound[2])
var.fundelta <- function(param) {
if (length(param) != 2) {
lambda <- 1
} else {
lambda <- param[2]
}
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
return(transformPhylo.ll(y = y, phy = lambdaPhy,
delta = param[1], nodeIDs = nodeIDs, model = "delta",
meserr = meserr, covPIC = covPIC)[[2]])
}
vo <- optim(delta, var.fundelta, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
if (lambdaEst) {
lambda <- vo$par[2]
} else {
lambda <- 1
}
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
if (modelCIs == TRUE) {
delta.fun <- function(param, chiSq = TRUE) {
ll <- transformPhylo.ll(y = y, phy = lambdaPhy,
delta = param, model = "delta", nodeIDs = nodeIDs,
meserr = meserr, covPIC = covPIC)$logLikelihood
if (chiSq) return(ll - vo$value + 1.92) else return(ll)
}
if (delta.fun(lowerBound[1]) < 0) {
LCI <- uniroot(delta.fun, interval = c(lowerBound[1],
vo$par[1]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
if (delta.fun(upperBound[1]) < 0) {
UCI <- uniroot(delta.fun, interval = c(vo$par[1],
upperBound[1]))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0))
deltaCurve <- Vectorize(delta.fun)
curve(deltaCurve(x, FALSE), from = lowerBound[1],
to = upperBound[1], xlab = expression(delta),
ylab = "log-likelihood", las = 1, main = "profile plot",
lwd = 2)
if (modelCIs) {
abline(v = c(LCI, vo$par[1], UCI), lty = c(3,
2, 3), lwd = 2, col = "
}
}
out <- list()
out$MaximumLikelihood <- vo$value[1]
if (modelCIs) {
out$Delta <- matrix(c(vo$par[1], LCI, UCI), 1, 3,
byrow = TRUE)
colnames(out$Delta) <- c("MLDelta", "LowerCI", "UpperCI")
} else {
out$Delta <- matrix(vo$par[1], 1, 1, byrow = TRUE)
colnames(out$Delta) <- c("MLDelta")
}
deltaPhy <- transformPhylo(y = y, phy = lambdaPhy, model = "delta",
delta = vo$par[1], meserr = meserr)
out$brownianVariance <- likTraitPhylo(phy = deltaPhy,
y = y, covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = deltaPhy, method = "pic")[[1]][1])))
param <- 3
if (lambdaEst) {
out$lambda <- vo$par[2]
names(out)[4] <- "Lambda"
param <- 4
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) {
out$deltaPhy <- deltaPhy
}
class(out) <- "delta.ML"
}, ou = {
if (is.null(nodeIDs)) nodeIDs <- Ntip(phy) + 1 else nodeIDs <- nodeIDs
if (is.null(lowerBound)) {
lowerBound <- bounds["alpha", 1]
if (lambdaEst) lowerBound[2] <- bounds["lambda",
1]
}
if (is.null(upperBound)) {
upperBound <- bounds["alpha", 2]
if (lambdaEst) upperBound[2] <- bounds["lambda",
2]
}
alpha <- 0.01
if (lambdaEst) alpha[2] <- runif(1, lowerBound[2], upperBound[2])
n.par <- length(lowerBound)
if (!is.ultrametric(phy)) {
if (ncol(y) > 1) stop("non-ultrametric phy and OU model only applicable for single traits, sorry")
print("non-ultrametric phy and OU model - using variance-covariance matrix, not tree-transformation")
cophenetic.dist <- cophenetic.phylo(phy)
vcv.matrix <- vcv(phy)
alpha[1] <- log(alpha[1])
lowerBound[1] <- log(lowerBound[1])
upperBound[1] <- log(upperBound[1])
if (lambdaEst) stop("non-ultrametric phy and OU model not applicable with lambda model, sorry")
anc.loc <- 3
bm.loc <- 2
alpha[c(bm.loc, anc.loc)] <- log(c(0.1, 0.1))
lowerBound[c(bm.loc, anc.loc)] <- log(c(1e-08, NA))
upperBound[c(bm.loc, anc.loc)] <- c(log(10), NA)
}
if (is.ultrametric(phy)) {
var.funOU <- function(param) {
if (length(param) != 2) {
lambda <- 1
} else {
lambda <- param[2]
}
alpha.int <- param[1]
lambdaPhy <- transformPhylo(y = y, phy = phy,
lambda = lambda, model = "lambda")
return(transformPhylo.ll(y = y, phy = lambdaPhy,
alpha = alpha.int, nodeIDs = nodeIDs, model = "OU",
meserr = meserr, covPIC = covPIC)[[2]])
}
vo <- optim(as.numeric(alpha), var.funOU, method = "L-BFGS-B",
lower = as.numeric(lowerBound), upper = as.numeric(upperBound),
control = controlList)
} else {
var.funOU <- function(param) {
vcv.phy <- vcv(phy)
co.phy <- cophenetic(phy)
return(transformPhylo.ll(y = y, phy = phy, model = "OU",
alpha = exp(param[1]), meserr = meserr, mu = exp(param[anc.loc]),
sigma.sq = exp(param[bm.loc]), covPIC = covPIC,
vcv.matrix = vcv.phy, cophenetic.dist = co.phy))
}
start <- 200
count <- 0
no.solution <- TRUE
while (no.solution) {
vo <- try(optim(as.numeric(alpha), var.funOU,
method = "L-BFGS-B", lower = as.numeric(lowerBound),
upper = as.numeric(upperBound), control = controlList),
silent = TRUE)
if (is(vo)[1] != "try-error") {
no.solution <- FALSE
} else {
start <- start - count
upperBound[c(bm.loc, anc.loc)] <- c(log(start),
log(start))
count <- count + 10
}
}
}
if (lambdaEst) {
lambda <- vo$par[2]
} else {
lambda <- 1
}
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda")
if (!is.ultrametric(phy)) {
ou.tr <- function(alpha) {
vcv.matrix <- transformPhylo(y = y, phy = phy,
alpha = alpha, nodeIDs = nodeIDs, model = "OU",
meserr = meserr)
mu <- mu.mean(vcv.matrix, y)[1, 1]
sigma.sq <- sig.sq(mu, vcv.matrix, y)[1, 1]
reml.lik <- mvtnorm::dmvnorm(y[, 1], mean = rep(mu,
ncol(vcv.matrix)), sigma = vcv.matrix * sigma.sq,
log = TRUE)
return(list(reml.lik = reml.lik, reml.sigma.sq = sigma.sq,
reml.mu = mu))
}
reml.out <- ou.tr(alpha = exp(vo$par[1]))
vo$value[1] <- reml.out[[1]]
}
if (modelCIs == TRUE) {
if (is.ultrametric(phy)) {
ou.fun <- function(param, chiSq = TRUE) {
ll <- transformPhylo.ll(y, lambdaPhy, model = "OU",
alpha = param, nodeIDs = nodeIDs, meserr = meserr,
covPIC = covPIC)$logLikelihood
if (chiSq) {
return(ll - vo$value + 1.92)
} else {
return(ll)
}
}
} else {
ou.fun <- function(param, chiSq = TRUE) {
ll <- ou.tr(alpha = exp(param))[[1]]
if (chiSq) {
return(ll - reml.out[[1]] + 1.92)
} else {
return(ll)
}
}
}
lower.attempt <- try(uniroot(ou.fun, interval = c(lowerBound[1],
vo$par[1]))$root, silent = TRUE)
if (is.numeric(lower.attempt)) {
LCI <- uniroot(ou.fun, interval = c(lowerBound[1],
vo$par[1]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
upper.attempt <- try(uniroot(ou.fun, interval = c(vo$par[1],
upperBound[1]))$root, silent = TRUE)
if (is.numeric(upper.attempt)) {
UCI <- uniroot(ou.fun, interval = c(vo$par[1],
upperBound[1]))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
}
if (!is.ultrametric(phy)) {
vo$par[1] <- exp(vo$par[1])
if (modelCIs == TRUE) {
UCI <- exp(UCI[1])
LCI <- exp(LCI[1])
}
lowerBound[1] <- exp(lowerBound[1])
upperBound[1] <- exp(upperBound[1])
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0))
if (is.ultrametric(phy)) {
ouCurve <- Vectorize(ou.fun)
curve(ouCurve(x, FALSE), from = lowerBound[1],
to = upperBound[1], xlab = expression(alpha),
ylab = "log-likelihood", las = 1, main = "profile plot",
lwd = 2)
if (modelCIs) abline(v = c(LCI, vo$par[1], UCI),
lty = c(3, 2, 3), lwd = 2, col = "
} else {
ou.fun.profile <- function(param) {
ll <- ou.tr(param)[[1]]
return(ll)
}
ouCurve <- Vectorize(ou.fun.profile)
curve(ouCurve(x), from = lowerBound[1], to = upperBound[1],
xlab = expression(alpha), ylab = "log-likelihood",
las = 1, main = "profile plot", lwd = 2)
if (modelCIs) abline(v = c(LCI[1], vo$par[1],
UCI[1]), lty = c(3, 2, 3), lwd = 2, col = "
}
}
out <- list()
out$MaximumLikelihood <- vo$value[1]
if (modelCIs) {
out$Alpha <- matrix(c(vo$par[1], LCI, UCI), 1, 3,
byrow = TRUE)
colnames(out$Alpha) <- c("MLAlpha", "LowerCI", "UpperCI")
} else {
out$Alpha <- matrix(vo$par[1], 1, 1, byrow = TRUE)
colnames(out$Alpha) <- c("MLAlpha")
}
if (is.ultrametric(phy)) {
ouPhy <- transformPhylo(y = y, phy = lambdaPhy, model = "OU",
alpha = vo$par[1], meserr = meserr)
out$brownianVariance <- likTraitPhylo(y = y, phy = ouPhy,
covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = ouPhy, method = "pic")[[1]][1])))
} else {
out$brownianVariance <- reml.out$reml.sigma.sq
out$root.state <- reml.out$reml.mu
}
names(out) <- c("MaximumLikelihood", "Alpha", "brownianVariance",
"root.state")
param <- 3
if (lambdaEst) {
out$lambda <- vo$par[2]
param <- 4
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$ouPhy <- ouPhy
class(out) <- "ou.ML"
}, acdc = {
if (is.null(nodeIDs)) {
nodeIDs <- Ntip(phy) + 1
} else {
nodeIDs <- nodeIDs
}
rootBranchingTime <- nodeTimes(phy)[1, 1]
if (is.null(lowerBound)) {
lowerBound <- log(bounds["acdcrate", 1])/rootBranchingTime
}
if (is.null(upperBound)) {
upperBound <- log(bounds["acdcrate", 2])/rootBranchingTime
}
if (acdcScalar) {
if (is.na(lowerBound[2])) {
lowerBound[2] <- 1
}
if (is.na(upperBound[2])) {
upperBound[2] <- 5
}
}
if (lambdaEst) {
lowerBound <- c(lowerBound, bounds["lambda", 1])
upperBound <- c(upperBound, bounds["lambda", 2])
}
acdcRate <- runif(1, lowerBound[1], upperBound[1])
if (acdcScalar && lambdaEst) {
acdcRate[2] <- runif(1, lowerBound[2], upperBound[2])
acdcRate[3] <- runif(1, lowerBound[3], upperBound[3])
}
if (!acdcScalar && lambdaEst || acdcScalar && !lambdaEst) {
acdcRate[2] <- runif(1, lowerBound[2], upperBound[2])
}
if (acdcScalar) {
var.funACDC <- function(param) {
if (lambdaEst) lambda <- tail(param, 1) else lambda <- 1
acdc.est <- param[1]
scalarRate <- param[2]
lambdaPhy <- transformPhylo(y = y, phy = phy,
lambda = lambda, model = "lambda", meserr = meserr)
return(transformPhylo.ll(lambdaPhy, acdcRate = acdc.est,
nodeIDs = nodeIDs, model = "ACDC", y = y, cladeRates = scalarRate,
meserr = meserr, covPIC = covPIC)[[2]])
}
} else {
var.funACDC <- function(param) {
if (lambdaEst) lambda <- param[2] else lambda <- 1
acdc.est <- param[1]
lambdaPhy <- transformPhylo(y = y, phy = phy,
lambda = lambda, model = "lambda", meserr = meserr)
return(transformPhylo.ll(lambdaPhy, acdcRate = acdc.est,
nodeIDs = nodeIDs, model = "ACDC", y = y, cladeRates = 1,
meserr = meserr, covPIC = covPIC)[[2]])
}
}
vo <- optim(acdcRate, var.funACDC, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
if (lambdaEst) lambda <- tail(vo$par, 1) else lambda <- 1
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
if (acdcScalar) cladeRateEst <- vo$par[2] else cladeRateEst <- 1
if (modelCIs) {
ACDC.fun <- function(param, chiSq = TRUE) {
ll <- transformPhylo.ll(y, lambdaPhy, acdcRate = param,
nodeIDs = nodeIDs, model = "ACDC", cladeRates = cladeRateEst,
meserr = meserr, covPIC = covPIC)$logLikelihood
if (chiSq) return(ll - vo$value + 1.92) else return(ll)
}
if (ACDC.fun(lowerBound[1]) < 0) {
LCI <- uniroot(ACDC.fun, interval = c(lowerBound[1],
vo$par[1]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
if (ACDC.fun(upperBound[1]) < 0) {
UCI <- uniroot(ACDC.fun, interval = c(vo$par[1],
upperBound[1]))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0))
acdcCurve <- Vectorize(ACDC.fun)
curve(acdcCurve(x, FALSE), from = lowerBound[1],
to = upperBound[1], xlab = "ACDC rate", ylab = "log-likelihood",
las = 1, main = "profile plot", lwd = 2)
if (modelCIs) {
abline(v = c(LCI, vo$par[1], UCI), lty = c(3,
2, 3), lwd = 2, col = "
}
}
out <- list()
out$MaximumLikelihood <- vo$value[1]
if (modelCIs) {
out$ACDC <- matrix(c(vo$par[1], LCI, UCI), 1, 3,
byrow = TRUE)
colnames(out$ACDC) <- c("MLacdc", "LowerCI", "UpperCI")
} else {
out$ACDC <- matrix(vo$par[1], 1, 1, byrow = TRUE)
colnames(out$ACDC) <- c("MLacdc")
}
if (acdcScalar) out$scalar <- scaleClade <- vo$par[2] else scaleClade <- 1
acdcPhy <- transformPhylo(y = y, phy = lambdaPhy, model = "ACDC",
acdcRate = vo$par[1], nodeIDs = nodeIDs, cladeRates = scaleClade,
meserr = meserr)
out$brownianVariance <- likTraitPhylo(phy = acdcPhy,
y = y, covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = acdcPhy, method = "pic")[[1]][1])))
param <- length(vo$par) + 2
if (lambdaEst) {
out$lambda <- tail(vo$par, 1)
param <- param + 1
}
n <- Ntip(phy)
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$acdcPhy <- acdcPhy
class(out) <- "acdc.ML"
}, psi = {
if (is.null(lowerBound)) {
lowerBound <- bounds["psi", 1]
if (lambdaEst) {
lowerBound[2] <- bounds["lambda", 1]
}
}
if (is.null(upperBound)) {
upperBound <- bounds["psi", 2]
if (lambdaEst) {
upperBound[2] <- bounds["lambda", 2]
}
}
psi <- runif(1, lowerBound[1], upperBound[1])
if (lambdaEst) psi[1] <- runif(1, lowerBound[2], upperBound[2])
if (hiddenSpeciation) {
if (is.null(full.phy)) stop("please provide a full phylogeny")
full.data.match <- match(full.phy$tip.label, rownames(y))
tips.no.data <- full.phy$tip.label[which(is.na(full.data.match))]
phy <- dropTipPartial(full.phy, tips.no.data)
}
if (is.ultrametric(phy)) {
phy.bd <- birthdeath(phy)
} else {
phy.bd <- birthdeath_motmot(phy)
}
mu_over_lambda <- phy.bd[[4]][1]
lambda_minus_mu <- phy.bd[[4]][2]
lambda.sp <- as.numeric(lambda_minus_mu/(1 - mu_over_lambda))
mu.ext <- as.numeric(lambda_minus_mu/(1/mu_over_lambda -
1))
if (mu.ext > 0) {
phy <- sampleHiddenSp(phy, lambda.sp = lambda.sp,
mu.ext = mu.ext, useMean = useMean)
} else {
phy$hidden.speciation <- NULL
}
var.funpsi <- function(param) {
if (length(param) != 2) lambda <- 1 else lambda <- param[2]
psi <- param[1]
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
return(transformPhylo.ll(y = y, phy = lambdaPhy,
psi = psi, model = "psi", meserr = meserr, covPIC = covPIC,
lambda.sp = lambda.sp)[[2]])
}
vo <- optim(psi, var.funpsi, method = "L-BFGS-B", lower = lowerBound,
upper = upperBound, control = controlList)
if (lambdaEst) lambda <- vo$par[2] else lambda <- 1
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
if (modelCIs == TRUE) {
psi.fun <- function(param, chiSq = TRUE) {
ll <- transformPhylo.ll(y, lambdaPhy, model = "psi",
psi = param, meserr = meserr, covPIC = covPIC,
lambda.sp = lambda.sp)$logLikelihood
if (chiSq) return(ll - vo$value + 1.92) else return(ll)
}
if (psi.fun(lowerBound[1]) < 0) {
LCI <- uniroot(psi.fun, interval = c(lowerBound[1],
vo$par[1]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
if (psi.fun(upperBound[1]) < 0) {
UCI <- uniroot(psi.fun, interval = c(vo$par[1],
upperBound[1]))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0))
psiCurve <- Vectorize(psi.fun)
curve(psiCurve(x, FALSE), from = lowerBound[1], to = upperBound[1],
xlab = expression(psi), ylab = "log-likelihood",
las = 1, main = "profile plot", lwd = 2)
if (modelCIs) {
abline(v = c(LCI, vo$par[1], UCI), lty = c(3,
2, 3), lwd = 2, col = "
}
}
out <- list()
out$MaximumLikelihood <- vo$value[1]
if (modelCIs) {
out$psi <- matrix(c(vo$par[1], LCI, UCI), 1, 3, byrow = TRUE)
colnames(out$psi) <- c("MLpsi", "LowerCI", "UpperCI")
} else {
out$psi <- matrix(vo$par[1], 1, 1, byrow = TRUE)
colnames(out$psi) <- c("MLpsi")
}
psiPhy <- transformPhylo(y = y, phy = lambdaPhy, model = "psi",
psi = vo$par[1], meserr = meserr, lambda.sp = lambda.sp)
out$brownianVariance <- likTraitPhylo(y = y, phy = psiPhy,
covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = psiPhy, method = "pic")[[1]][1])))
param <- 3
if (lambdaEst) {
out$lambda <- vo$par[2]
param <- 4
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$psiPhy <- psiPhy
class(out) <- "psi.ML"
}, multipsi = {
if (is.null(branchLabels)) stop("for 'multipsi' model must provide branchLabels giving state for each branch")
states <- levels(factor(branchLabels))
if (is.null(lowerBound)) {
lowerBound <- bounds[rep("psi", length(states)),
1]
if (lambdaEst) lowerBound[length(states) + 1] <- bounds["lambda",
1]
}
if (is.null(upperBound)) {
upperBound <- bounds[rep("psi", length(states)),
2]
if (lambdaEst) upperBound[length(states) + 1] <- bounds["lambda",
2]
}
ran.start <- runif(1, lowerBound[1], upperBound[1])
start <- rep(ran.start, length(states))
if (lambdaEst) start <- c(start, runif(1, lowerBound[2],
upperBound[2]))
if (hiddenSpeciation) {
if (is.null(full.phy)) stop("please provide a full phylogeny")
full.data.match <- match(full.phy$tip.label, rownames(y))
tips.no.data <- full.phy$tip.label[which(is.na(full.data.match))]
phy <- dropTipPartial(full.phy, tips.no.data)
}
if (is.ultrametric(phy)) {
phy.bd <- birthdeath(phy)
} else {
phy.bd <- birthdeath_motmot(phy)
}
mu_over_lambda <- phy.bd[[4]][1]
lambda_minus_mu <- phy.bd[[4]][2]
lambda.sp <- as.numeric(lambda_minus_mu/(1 - mu_over_lambda))
mu.ext <- as.numeric(lambda_minus_mu/(1/mu_over_lambda -
1))
if (mu.ext > 0) {
phy <- sampleHiddenSp(phy, lambda.sp = lambda.sp,
mu.ext = mu.ext, useMean = useMean)
} else {
phy$hidden.speciation <- NULL
}
var.funmultipsi <- function(param) {
all.param <- length(param)
if (lambdaEst) {
lambda <- param[all.param]
psi <- param[-all.param]
} else {
psi <- param
lambda <- 1
}
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
return(transformPhylo.ll(y = y, phy = lambdaPhy,
branchLabels = branchLabels, psi = psi, model = "multipsi",
meserr = meserr, covPIC = covPIC, lambda.sp = lambda.sp)[[2]])
}
vo <- optim(start, var.funmultipsi, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
if (lambdaEst) lambda <- tail(vo$par, 1) else lambda <- 1
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
out <- list()
out$MaximumLikelihood <- vo$value[1]
out$psi <- matrix(NA, length(states), 3, byrow = TRUE,
dimnames = list(states, c("MLpsi", "LowerCI", "UpperCI")))
out$psi[, 1] <- vo$par[1:length(states)]
if (modelCIs == TRUE) {
psi.fun <- function(param, chiSq = TRUE) {
psi <- as.numeric(vo$par)
psi[i] <- param
ll <- transformPhylo.ll(y, lambdaPhy, model = "multipsi",
branchLabels = branchLabels, psi = psi, meserr = meserr,
covPIC = covPIC, lambda.sp = lambda.sp)$logLikelihood
if (chiSq) return(ll - vo$value + 1.92) else return(ll)
}
for (i in 1:length(states)) {
if (psi.fun(lowerBound[i]) < 0) {
LCI <- uniroot(psi.fun, interval = c(lowerBound[i],
vo$par[i]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
if (psi.fun(upperBound[i]) < 0) {
UCI <- uniroot(psi.fun, interval = c(vo$par[i],
upperBound[i]))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
out$psi[i, 2:3] <- c(LCI, UCI)
}
}
if (profilePlot) {
par(mar = c(5, 5, 5, 5), oma = c(0, 0, 0, 0), mfrow = c(length(states),
length(states)))
for (i in 1:length(states)) {
psiCurve <- Vectorize(psi.fun)
curve(psiCurve(x, FALSE), from = lowerBound[1],
to = upperBound[1], xlab = expression(psi),
ylab = "log-likelihood", las = 1, main = paste0("profile plot psi ",
i), lwd = 2)
if (modelCIs) {
abline(v = c(out$psi[i, 2], out$psi[i, 1],
out$psi[i, 3]), lty = c(3, 2, 3), lwd = 2,
col = "
}
}
}
multipsiPhy <- transformPhylo(y = y, phy = lambdaPhy,
model = "multipsi", psi = vo$par[1:length(states)],
meserr = meserr, lambda.sp = lambda.sp, branchLabels = branchLabels)
out$brownianVariance <- likTraitPhylo(y = y, phy = multipsiPhy,
covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = multipsiPhy, method = "pic")[[1]][1])))
param <- length(states) + 2
if (lambdaEst) {
out$lambda <- vo$par[length(states) + 1]
param <- param + 1
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$psiPhy <- multipsiPhy
class(out) <- "multipsi.ML"
}, trend = {
if (is.ultrametric(phy)) stop("trend model only makes sense with non-ultrametric trees")
if (ncol(y) > 1) stop("only when trait at a one time, please run each trait individually")
bm.model.var <- transformPhylo.ML(y, phy, model = "bm",
meserr = meserr)$brownianVariance[1, 1]
phy <- reorder(phy)
tip.age.from.root <- c(nodeTimes(phy)[1, 1] - nodeTimes(phy)[which(phy$edge[,
2] <= Ntip(phy)), 2])
yy <- data.frame(y, tip.age.from.root)
if (lambdaEst == FALSE) {
estimates <- pic.pgls(y ~ tip.age.from.root, phy,
y = yy, lambda = 1, return.intercept.stat = TRUE,
meserr = meserr)
} else {
estimates <- pic.pgls(y ~ tip.age.from.root, phy,
y = yy, lambda = "ML", return.intercept.stat = TRUE,
meserr = meserr)
}
slope.model <- estimates$model.summary$coef[1]
intercept.model <- estimates$intercept[1]
y2 <- matrix((tip.age.from.root * slope.model) + intercept.model)
cont <- pic.motmot(y2, phy)
contr <- c(cont[[1]][, 1], 0)
rawVariances <- c(cont$contr[, 2], cont$V)
brCov <- 1/(Ntip(phy) + 1) * (sum(contr^2/rawVariances))
brCov <- bm.model.var - brCov
likelihood.trend <- likTraitPhylo(y, phy, brCov = brCov)[[2]]
if (lambdaEst) lambda <- estimates$lambda else lambda <- 1
lambdaPhy <- transformPhylo(y = y, phy = phy, lambda = lambda,
model = "lambda", meserr = meserr)
output.slope <- estimates$model.summary$coef[1:2]
output.intercept <- estimates$intercept[1:2]
out <- list()
out$MaximumLikelihood <- likelihood.trend
if (modelCIs) {
out$Trend <- matrix(output.slope[1:2], 1, 2, byrow = TRUE)
colnames(out$Trend) <- c("MLSlope", "StdError")
out$root.state <- matrix(output.intercept[1:2], 1,
2, byrow = TRUE)
colnames(out$root.state) <- c("ancestral.state",
"StdError")
} else {
out$Trend <- matrix(output.slope[1], 1, 1, byrow = TRUE)
colnames(out$Trend) <- c("MLSlope")
out$root.state <- matrix(output.intercept[1], 1,
1, byrow = TRUE)
colnames(out$root.state) <- c("ancestral.state")
}
out$brownianVariance <- matrix(brCov)
param <- 3
if (lambdaEst) {
out$lambda <- estimates$lambda
names(out)[4] <- "Lambda"
param <- 4
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) {
out$TrendPhy <- lambdaPhy
}
class(out) <- "trend.ML"
}, free = {
if (is.null(lowerBound)) {
lowerBound <- bounds["rate", 1]
}
if (is.null(upperBound)) {
upperBound <- bounds["rate", 2]
}
branchRates <- rep(1, length(phy$edge.length))
var.funfree <- function(branchRates) {
return(transformPhylo.ll(y, phy, branchRates = branchRates,
model = "free", meserr = meserr, covPIC = covPIC)[[2]])
}
vo <- optim(branchRates, var.funfree, method = "L-BFGS-B",
lower = 0, control = c(fnscale = -1, maxit = 10,
factr = 1e+14))
phy2 <- phy
phy2$edge.length <- phy$edge.length * vo$par
out <- vector(mode = "list", length = 3)
output.par <- likTraitPhylo(y = y, phy = phy2, covPIC = covPIC)
out$MaximumLikelihood <- output.par$logLikelihood
out$brownianVariance <- output.par$brownianVariance
out$Rates <- vo$par
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = phy2, method = "pic")[[1]][1])))
if (vo$convergence == 0) {
out$Convergence <- "Successful"
} else {
out$Convergence <- "Failed"
}
param <- length(branchRates) + 2
if (lambdaEst) {
out$lambda <- vo$par[length(branchRates) + 1]
param <- param + 1
}
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$freePhy <- phy2
class(out) <- "free.ML"
}, clade = {
if (is.null(lowerBound)) {
lowerBound <- bounds["rate", 1]
}
if (is.null(upperBound)) {
upperBound <- bounds["rate", 2]
}
if (is.null(rateType)) {
rateType <- rep("clade", length(nodeIDs))
} else {
rateType <- rateType
}
cladeRates <- rep(1, length(nodeIDs))
var.funclade <- function(param) {
return(transformPhylo.ll(y, phy, nodeIDs = nodeIDs,
cladeRates = param, model = "clade", rateType = rateType)[[2]])
}
vo <- optim(cladeRates, var.funclade, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
phyCladeFull <- transformPhylo(phy, model = "clade",
nodeIDs = nodeIDs, rateType = rateType, cladeRates = vo$par,
y = y, meserr = meserr)
out <- list()
if (modelCIs == TRUE) {
free.fun <- function(param) {
ll <- transformPhylo.ll(y, phyClade, model = "clade",
nodeIDs = SingleNode, rateType = whichRateType,
cladeRates = param, meserr = meserr, covPIC = covPIC)$logLikelihood
return(ll - vo$value + 1.92)
}
out$Rates <- matrix(vo$value, length(nodeIDs), 4,
byrow = TRUE)
colnames(out$Rates) <- c("node", "MLRate", "LowerCI",
"UpperCI")
for (i in 1:length(nodeIDs)) {
SingleNode <- nodeIDs[i]
whichRateType <- rateType[i]
phyClade <- transformPhylo(phyCladeFull, model = "clade",
nodeIDs = SingleNode, rateType = whichRateType,
cladeRates = 1/vo$par[i], y = y, meserr = meserr)
if (free.fun(lowerBound) < 0) {
LCI <- uniroot(free.fun, interval = c(lowerBound,
vo$par[i]))$root
} else {
LCI <- lowerBound[1]
lower.function.warning()
}
if (free.fun(upperBound) < 0) {
UCI <- uniroot(free.fun, interval = c(vo$par[i],
upperBound))$root
} else {
UCI <- upperBound[1]
upper.function.warning()
}
out$Rates[i, ] <- c(nodeIDs[i], vo$par[i], LCI,
UCI)
}
} else {
out$Rates <- matrix(NA, length(nodeIDs), 2, byrow = TRUE)
colnames(out$Rates) <- c("node", "MLRate")
out$Rates[, 1] <- nodeIDs
out$Rates[, 2] <- vo$par
}
out$MaximumLikelihood <- vo$value
out$brownianVariance <- likTraitPhylo(y = y, phy = phyCladeFull,
covPIC = covPIC)$brownianVariance
out$root.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = phyCladeFull, method = "pic")[[1]][1])))
param <- 2 + length(vo$par)
out$AIC <- aic.fun(out$MaximumLikelihood, param)
out$AICc <- aicc.fun(out$MaximumLikelihood, param, Ntip(phy))
if (returnPhy) out$freePhy <- phyCladeFull
class(out) <- "clade.ML"
}, tm1 = {
if (is.null(lowerBound)) {
lowerBound <- bounds["rate", 1]
}
if (is.null(upperBound)) {
upperBound <- bounds["rate", 2]
}
nodes <- unique(sort(phy$edge[, 2]))
nodeDepth <- node.depth(phy)
nodesByRichness <- cbind(richness = nodeDepth[nodes],
node = nodes)
searchNode <- nodesByRichness[nodesByRichness[, 1] >=
minCladeSize, 2]
if (is.null(restrictNode) == FALSE) {
ngroups <- length(restrictNode)
cm <- caper::clade.matrix(phy)
colnames(cm$clade.matrix) <- cm$tip.label
cmMat <- cm$clade.matrix
skipNodes <- numeric()
for (i in 1:ngroups) {
matDrop <- cmMat[, restrictNode[[i]]]
nodeDrop <- rowSums(matDrop) < length(restrictNode[[i]]) &
rowSums(matDrop) >= 1
skipNodes <- c(skipNodes, as.numeric(rownames(matDrop)[nodeDrop]))
}
skipNodes <- unique(c(skipNodes, phy$edge[phy$edge.length <
tol, 2]))
searchNode <- setdiff(searchNode, skipNodes)
} else {
skipNodes <- unique(phy$edge[phy$edge.length < tol,
2])
searchNode <- setdiff(searchNode, skipNodes)
}
n <- length(y)
BERateOut <- matrix(NA, nrow = nSplits + 1, ncol = (6 +
nSplits))
fullModelOut <- vector(mode = "list", length = nSplits)
MLsingle <- transformPhylo.ll(y = y, phy = phy, model = "bm",
meserr = meserr, covPIC = covPIC)[[2]]
AICsingle <- aic.fun(MLsingle, 2)
AICcsingle <- aicc.fun(MLsingle, 2, n)
colnames(BERateOut) <- 1:dim(BERateOut)[2]
colnames(BERateOut)[1:6] <- c("node", "shiftPos", "lnL",
"n.params", "AIC", "AICc")
colnames(BERateOut)[-c(1:6)] <- paste0("rate.", 1:nSplits)
rownames(BERateOut) <- c("BM ", paste0("shift.", 1:nSplits))
BERateOut[1, 1:6] <- c(0, 1, MLsingle, 2, AICsingle,
AICcsingle)
BERateOut <- data.frame(BERateOut)
cat("\n", "BM model")
cat("\n")
print(BERateOut[1, 1:6])
for (k in 1:nSplits) {
cladeMembers <- matrix(NA, ncol = k, nrow = length(phy$edge[,
1]))
if (k == 1) {
searchNode <- searchNode
} else {
searchNode <- searchNode[!(searchNode %in% bestNodes)]
}
for (i in searchNode) {
if (k == 1) {
currentNodeIDs <- i
} else {
currentNodeIDs <- c(bestNodes, i)
}
cladeRates <- rep(1, length(currentNodeIDs))
var.funclade.tm1 <- function(cladeRates) {
return(transformPhylo.ll(y, phy, nodeIDs = currentNodeIDs,
rateType = rep("clade", length(currentNodeIDs)),
cladeRates = cladeRates, model = "clade",
meserr = meserr, covPIC = covPIC)[[2]])
}
currentCladeModel <- optim(cladeRates, var.funclade.tm1,
method = "L-BFGS-B", lower = lowerBound, upper = upperBound,
control = controlList)
fullModelOut[[k]] <- rbind(fullModelOut[[k]],
c(node = as.integer(i), shiftPos = 1, ML = currentCladeModel$value,
currentCladeModel$par))
currentModel <- currentCladeModel
shiftPos <- 1
param <- (k * 2) + 1
currentModel <- list(currentModel, i, cladeMembers)
currentML <- currentModel[[1]]$value
AIC <- aic.fun(currentModel[[1]]$value, param)
AICc <- aicc.fun(currentModel[[1]]$value, param,
n)
if (i == min(searchNode)) {
BERateOut[k + 1, 1:(6 + k)] <- c(currentModel[[2]],
shiftPos, currentModel[[1]]$value, param,
AIC, AICc, rev(currentModel[[1]]$par))
} else {
if (currentML > BERateOut[k + 1, 3]) {
BERateOut[k + 1, 1:(6 + k)] <- c(currentModel[[2]],
shiftPos, currentModel[[1]]$value, param,
AIC, AICc, rev(currentModel[[1]]$par))
}
}
}
if (k == 1) bestNodes <- BERateOut[k + 1, 1] else bestNodes <- c(bestNodes,
BERateOut[k + 1, 1])
if (sum(BERateOut[, "shiftPos"] == 1, na.rm = T) >
0) BERateOut[which(BERateOut[, "shiftPos"] ==
1), "shiftPos"] <- "clade"
cat("\n", "Shift", k)
cat("\n")
print(BERateOut[k + 1, c(1:(6 + k))])
}
out <- list(as.data.frame(BERateOut), fullModelOut, y,
phy)
class(out) <- "traitMedusa"
}, tm2 = {
if (is.null(lowerBound)) lowerBound <- bounds["rate",
1]
if (is.null(upperBound)) upperBound <- bounds["rate",
2]
nodes <- unique(sort(phy$edge[, 2]))
nodeDepth <- node.depth(phy)
nodesByRichness <- cbind(richness = nodeDepth[nodes],
node = nodes)
searchNode <- nodesByRichness[nodesByRichness[, 1] >=
minCladeSize, 2]
searchNodeType <- c(searchNode, searchNode[searchNode >
Ntip(phy)])
searchType <- c(rep("clade", length(searchNode)), rep("branch",
sum(searchNode > Ntip(phy))))
searchNodeTypeAll <- data.frame(searchType, searchNodeType,
stringsAsFactors = FALSE)
if (is.null(restrictNode) == FALSE) {
ngroups <- length(restrictNode)
cm <- caper::clade.matrix(phy)
colnames(cm$clade.matrix) <- cm$tip.label
cmMat <- cm$clade.matrix
skipNodes <- numeric()
for (i in 1:ngroups) {
matDrop <- cmMat[, restrictNode[[i]]]
nodeDrop <- rowSums(matDrop) < length(restrictNode[[i]]) &
rowSums(matDrop) >= 1
skipNodes <- c(skipNodes, as.numeric(rownames(matDrop)[nodeDrop]))
}
skipNodes <- unique(c(skipNodes, phy$edge[phy$edge.length <
tol, 2]))
searchNode <- setdiff(searchNode, skipNodes)
} else {
skipNodes <- unique(phy$edge[phy$edge.length < tol,
2])
searchNode <- setdiff(searchNode, skipNodes)
}
tm2.fun <- function(whichSearchNode) which(searchNodeTypeAll[,
2] == whichSearchNode)
searchNodeTypeAll <- searchNodeTypeAll[sort(unlist(sapply(searchNode,
tm2.fun))), ]
n <- length(y)
BERateOut <- matrix(NA, nrow = nSplits + 1, ncol = (6 +
(nSplits)))
fullModelOut <- vector(mode = "list", length = nSplits)
bestModel <- matrix(NA, ncol = 2, nrow = nSplits)
fullModelOut <- vector(mode = "list", length = nSplits)
MLsingle <- transformPhylo.ll(y = y, phy = phy, model = "bm",
meserr = meserr, covPIC = covPIC)[[2]]
AICsingle <- aic.fun(MLsingle, 2)
AICcsingle <- aicc.fun(MLsingle, 2, Ntip(phy))
BERateOut[1, 1:6] <- c(0, 1, MLsingle, 2, AICsingle,
AICcsingle)
colnames(BERateOut) <- 1:dim(BERateOut)[2]
colnames(BERateOut)[1:6] <- c("node", "shiftPos", "lnL",
"n.params", "AIC", "AICc")
colnames(BERateOut)[-c(1:6)] <- paste0("rate.", 1:nSplits)
rownames(BERateOut) <- c("BM ", paste0("shift.", 1:nSplits))
BERateOut[1, 1:6] <- c(0, 1, MLsingle, 2, AICsingle,
AICcsingle)
BERateOut <- data.frame(BERateOut)
cat("\n", "BM model")
cat("\n")
print(BERateOut[1, 1:6])
for (k in 1:nSplits) {
cladeMembers <- matrix(NA, ncol = k, nrow = length(phy$edge[,
1]))
bestModel[bestModel[, 2] == "1", 2] <- "clade"
bestModel[bestModel[, 2] == "2", 2] <- "branch"
if (k == 1) {
searchNodeTypeAll <- searchNodeTypeAll
} else {
dropNodeRow <- which(searchNodeTypeAll[, 1] ==
bestModel[k - 1, 2] & searchNodeTypeAll[, 2] ==
as.numeric(bestModel[k - 1, 1]))
rowDropLogical <- row(searchNodeTypeAll)[, 1] !=
dropNodeRow
searchNodeTypeAll <- searchNodeTypeAll[rowDropLogical,
]
}
if (k == 1) currentNodeIDs <- NULL else currentNodeIDs <- na.omit(as.numeric(bestModel[,
1]))
if (k == 1) currentRateType <- NULL else currentRateType <- na.omit(bestModel[,
2])
foo2 <- function(x_foo, k, currentNodeIDs = currentNodeIDs,
currentRateType = currentRateType) {
currentNodeIDs <- c(currentNodeIDs, x_foo[, 2])
currentRateType <- c(currentRateType, x_foo[,
1])
cladeRates <- rep(1, length(currentNodeIDs))
var.funclade.tm2 <- function(cladeRates) return(transformPhylo.ll(y,
phy, nodeIDs = currentNodeIDs, rateType = currentRateType,
cladeRates = cladeRates, model = "clade", meserr = meserr,
covPIC = covPIC)[[2]])
currentCladeModel <- optim(cladeRates, var.funclade.tm2,
method = "L-BFGS-B", lower = lowerBound, upper = upperBound,
control = controlList)
if (x_foo[, 1] == "clade") shiftPos <- 1
if (x_foo[, 1] == "branch") shiftPos <- 2
currentModel <- currentCladeModel
param <- k * 2 + 1
currentModel <- list(currentModel, x_foo[2],
cladeMembers)
currentML <- currentModel[[1]]$value
AIC <- aic.fun(currentModel[[1]]$value, param)
AICc <- aicc.fun(currentModel[[1]]$value, param,
n)
out <- c(currentModel[[2]][, 1], shiftPos, currentModel[[1]]$value,
param, AIC, AICc, currentModel[[1]]$par)
return(out)
}
searchNodeList <- vector(mode = "list", length = length(searchNodeTypeAll[,
1]))
for (i in 1:length(searchNodeTypeAll[, 1])) searchNodeList[[i]] <- searchNodeTypeAll[i,
]
all.output <- parallel::mclapply(searchNodeList,
FUN = foo2, k = k, currentNodeIDs = currentNodeIDs,
currentRateType = currentRateType, mc.cores = n.cores)
all.output <- matrix(unlist(all.output), nrow = length(searchNodeList),
byrow = TRUE)
best.out <- all.output[which.max(all.output[, 3]),
]
fullModelOut[[k]] <- all.output
BERateOut[k + 1, 1:(6 + k)] <- best.out
bestModel[k, ] <- unlist(BERateOut[k + 1, 1:2])
if (sum(BERateOut[, "shiftPos"] == 1, na.rm = T) >
0) BERateOut[which(BERateOut[, "shiftPos"] ==
1), "shiftPos"] <- "clade"
if (sum(BERateOut[, "shiftPos"] == 2, na.rm = T) >
0) BERateOut[which(BERateOut[, "shiftPos"] ==
2), "shiftPos"] <- "branch"
cat("\n", "Shift", k)
cat("\n")
print(BERateOut[k + 1, c(1:(6 + k))])
}
out <- list(as.data.frame(BERateOut), fullModelOut, y,
phy)
class(out) <- "traitMedusa"
}, modeslice = {
maxTime <- nodeTimes(phy)[1, 1]
input <- lowerBound <- upperBound <- c()
mode.order <- tolower(mode.order)
count <- 1
if (methods::is(splitTime)[1] == "NULL") stop("please provide a shift time(s)")
if (lambdaEst) stop("sorry Lambda estimation not applicable with modeslice model, sorry")
if ((length(splitTime) + 1) != length(mode.order)) stop("mismatch between number of nodes and shift times")
transformation <- c()
if (any(is.na(match(mode.order, c("bm", "ou", "kappa",
"acdc"))))) stop("mode.order must be a combination of 'bm', 'ou', 'kappa', and/or 'acdc'")
for (x in 1:length(mode.order)) {
if (mode.order[x] == "bm") {
if (rate.var) {
input[count] <- log(1)
lowerBound[count] <- log(bounds["rate", 1])
upperBound[count] <- log(bounds["rate", 2])
count <- count + 1
transformation <- c(transformation, "log")
}
}
if (mode.order[x] == "ou") {
input[count] <- log(0.1)
lowerBound[count] <- log(bounds["alpha", 1])
upperBound[count] <- log(bounds["alpha", 2])
count <- count + 1
transformation <- c(transformation, "log")
}
if (mode.order[x] == "kappa") {
input[count] <- 0.1
lowerBound[count] <- log(bounds["kappa", 1])
upperBound[count] <- log(bounds["kappa", 2])
count <- count + 1
transformation <- c(transformation, "log")
}
if (mode.order[x] == "acdc") {
if (acdcScalar) {
input[count] <- log(1)
lowerBound[count] <- log(1)
upperBound[count] <- log(bounds["rate", 2])
count <- count + 1
transformation <- c(transformation, "log")
}
lowerBound[count] <- -10/nodeTimes(phy)[1, 1]
upperBound[count] <- -1e-06
input[count] <- runif(1, lowerBound[count], upperBound[count])
count <- count + 1
transformation <- c(transformation, "none")
}
}
n <- Ntip(phy)
anc.loc <- length(lowerBound) + 1
lowerBound[anc.loc] <- upperBound[anc.loc] <- NA
input[anc.loc] <- log(0.1)
transformation <- c(transformation, "log")
bm.loc <- length(lowerBound) + 1
lowerBound[bm.loc] <- log(1e-08)
upperBound[bm.loc] <- NA
input[bm.loc] <- log(0.1)
transformation <- c(transformation, "log")
var.fun.modeslice <- function(param) {
input.in <- param[-c(anc.loc, bm.loc)]
transform <- transformation[-c(anc.loc, bm.loc)]
for (u in 1:length(transform)) if (transform[u] ==
"log") input.in[u] <- exp(input.in[u])
return(transformPhylo.ll(y = y, phy = phy, mode.order = mode.order,
mode.param = input.in, model = "modeslice", mu = exp(param[anc.loc]),
sigma.sq = exp(param[bm.loc]), splitTime = splitTime,
covPIC = covPIC, rate.var = rate.var, cladeRates = acdcScalar,
meserr = meserr))
}
vo <- optim(input, var.fun.modeslice, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
res.par <- vo$par
for (u in 1:length(transformation)) if (transformation[u] ==
"log") res.par[u] <- exp(res.par[u])
rm.param <- c(bm.loc, anc.loc)
tre.tr <- function(mode.param.input) {
transform <- transformation[-rm.param]
for (u in 1:length(transform)) if (transform[u] ==
"log") mode.param.input[u] <- exp(mode.param.input[u])
vcv.matrix <- transformPhylo(y = y, phy = phy, mode.order = mode.order,
mode.param = mode.param.input, model = "modeslice",
splitTime = splitTime, rate.var = rate.var, cladeRates = acdcScalar,
meserr = meserr)
mu <- mu.mean(vcv.matrix, y)[1, 1]
sigma.sq <- sig.sq(mu, vcv.matrix, y)[1, 1]
reml.lik <- mvtnorm::dmvnorm(y[, 1], mean = rep(mu,
ncol(vcv.matrix)), sigma = vcv.matrix * sigma.sq,
log = TRUE)
return(list(reml.lik = reml.lik, reml.sigma.sq = sigma.sq,
reml.mu = mu))
}
reml.out <- tre.tr(mode.param.input = vo$par[-rm.param])
vo$value[1] <- reml.out[[1]]
if (modelCIs == TRUE) {
ci.fun <- function(param.in, chiSq = TRUE) {
param2 <- vo$par[-rm.param]
param2[k] <- param.in
ll <- tre.tr(param2)[[1]]
if (chiSq) {
return(ll - vo$value + 1.92)
} else {
return(ll)
}
}
param <- vo$par[-rm.param]
UCI <- LCI <- c()
for (k in 1:length(param)) {
lower.attempt <- try(uniroot(ci.fun, interval = c(lowerBound[k],
param[k]))$root, silent = TRUE)
if (is.numeric(lower.attempt)) {
LCI[k] <- suppressWarnings(uniroot(ci.fun,
interval = c(lowerBound[k], param[k]))$root)
} else {
LCI[k] <- lowerBound[k]
lower.function.warning()
}
upper.attempt <- try(uniroot(ci.fun, interval = c(param[k],
upperBound[k]))$root, silent = TRUE)
if (is.numeric(upper.attempt)) {
UCI[k] <- suppressWarnings(uniroot(ci.fun,
interval = c(param[k], upperBound[k]))$root)
} else {
UCI[k] <- upperBound[k]
upper.function.warning()
}
}
}
for (u in 1:length(param)) if (transformation[u] == "log") param[u] <- exp(param[u])
for (u in 1:length(param)) if (transformation[u] == "log") LCI[u] <- exp(LCI[u])
for (u in 1:length(param)) if (transformation[u] == "log") UCI[u] <- exp(UCI[u])
out <- list()
out$MaximumLikelihood <- vo$value
out$brownianVariance <- reml.out$reml.sigma.sq
out$root.state <- reml.out$reml.mu
count <- 1
for (x in 1:length(mode.order)) {
if (mode.order[x] == "ou") x.name <- "alpha"
if (mode.order[x] == "kappa") x.name <- "kappa"
if (mode.order[x] == "acdc") x.name <- "acdc.rate"
if (mode.order[x] == "bm") {
if (rate.var) {
if (!modelCIs) {
x.temp <- matrix(param[count])
colnames(x.temp) <- "BM.rate"
out[[length(out) + 1]] <- x.temp
names(out)[length(out)] <- paste0("mode.",
x, ".", mode.order[x])
count <- count + 1
} else {
x.temp <- matrix(c(param[count], LCI[count],
UCI[count]), nrow = 1)
colnames(x.temp) <- c("BM.rate", "LCI", "UCI")
out[[length(out) + 1]] <- x.temp
names(out)[length(out)] <- paste0("mode.",
x, ".", mode.order[x])
count <- count + 1
}
}
} else {
if (!modelCIs) {
if (x.name == "acdc.rate" && acdcScalar) {
acdc <- param[count + 1]
acdc.scale <- param[count]
x.temp <- matrix(c(acdc, acdc.scale))
colnames(x.temp) <- c("acdc.rate", "acdc scalar")
out[[length(out) + 1]] <- x.temp
names(out)[length(out)] <- paste0("mode.",
x, ".", mode.order[x])
count <- count + 2
} else {
x.temp <- matrix(param[count])
colnames(x.temp) <- x.name
out[[length(out) + 1]] <- x.temp
names(out)[length(out)] <- paste0("mode.",
x, ".", mode.order[x])
count <- count + 1
}
} else {
if (x.name == "acdc.rate" && acdcScalar) {
acdc <- param[count + 1]
acdc.lci <- LCI[count + 1]
acdc.uci <- UCI[count + 1]
scalar <- param[count]
scalar.lci <- LCI[count]
scalar.uci <- UCI[count]
x.temp <- matrix(c(acdc, acdc.lci, acdc.uci,
scalar, scalar.lci, scalar.uci), nrow = 1)
colnames(x.temp) <- c("acdc.rate", "acdc.LCI",
"acdc.UCI", "scalar", "scalar.LCI", "scalar.UCI")
out[[length(out) + 1]] <- x.temp
names(out)[length(out)] <- paste0("mode.",
x, ".", mode.order[x])
count <- count + 2
} else {
x.temp <- matrix(c(param[count], LCI[count],
UCI[count]), nrow = 1)
colnames(x.temp) <- c(x.name, "LCI", "UCI")
out[[length(out) + 1]] <- x.temp
names(out)[length(out)] <- paste0("mode.",
x, ".", mode.order[x])
count <- count + 1
}
}
}
}
k <- 2 + length(param)
out[length(out) + 1] <- aic.fun(vo$value, k)
names(out)[length(out)] <- "AIC"
out[length(out) + 1] <- aicc.fun(vo$value, k, n)
names(out)[length(out)] <- "AICc"
class(out) <- "modeSlice.ML"
}, timeslice = {
if (!is.null(splitTime) && !is.null(testShiftTimes))
print("Both splitTime and testShiftTimes provided so testShiftTimes will be ignored. Please set splitTime to NULL for testShiftTimes to be modelled.")
maxTime <- nodeTimes(phy)[1, 1]
n <- Ntip(phy)
if (is.null(controlList["pgtol"])) controlList["pgtol"] <- 0.1
if (is.null(lowerBound)) {
lowerBound <- bounds["rate", 1]
}
if (is.null(upperBound)) {
upperBound <- bounds["rate", 2]
}
output.all <- FALSE
if (is.null(splitTime)) {
if (is.null(testShiftTimes)) {
boundaryAge <- sort(boundaryAge, decreasing = TRUE)
if ((maxTime - boundaryAge[1]) < 0) stop("Boundary age bigger than the tree age.")
if (length(boundaryAge) == 2) {
if ((maxTime - boundaryAge[2]) < 0) stop("Boundary age bigger than the tree age.")
boundaryAge2 <- boundaryAge[2]
boundaryAge <- boundaryAge[1]
} else {
boundaryAge2 <- boundaryAge
}
splitTime <- seq(maxTime - boundaryAge, boundaryAge2, -testAge)
if (min(splitTime) > boundaryAge2) splitTime <- c(splitTime, boundaryAge2)
splitTime.orig <- splitTime
} else {
splitTime <- unique(sort(testShiftTimes, decreasing = TRUE))
nSplits <- length(testShiftTimes)
splitTime.orig <- splitTime
}
output.mat <- matrix(NA, nrow = (nSplits + 1), ncol = (3 +
nSplits + (nSplits + 1)) + (2 * ncol(y)))
bm.phy <- transformPhylo(phy = phy, model = "bm",
meserr = meserr, y = y)
bm.model <- likTraitPhylo(y, bm.phy, covPIC = covPIC)
log.lik <- as.numeric(bm.model[[2]])
aic <- aic.fun(log.lik, 2)
aicc <- aicc.fun(log.lik, 2, Ntip(phy))
anc.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
bm.phy, method = "pic")[[1]][1])))
colnames(output.mat) <- 1:ncol(output.mat)
colnames(output.mat)[1:3] <- c("lnL", "AIC", "AICc")
c.y <- ncol(y)
colnames(output.mat)[4:(4 + c.y - 1)] <- paste0("sigma.sq.",
1:ncol(y))
n.c.ct <- (4 + c.y)
colnames(output.mat)[n.c.ct:(n.c.ct + c.y - 1)] <- paste0("anc.state.",
1:ncol(y))
n.c.ct <- (n.c.ct + c.y):(n.c.ct + c.y + nSplits)
colnames(output.mat)[n.c.ct] <- paste0("rates", 1:(nSplits +
1))
n.c.ct <- (max(n.c.ct) + 1):(max(n.c.ct) + nSplits)
colnames(output.mat)[n.c.ct] <- paste0("time.split",
1:nSplits)
to.here <- which(regexpr("rates", colnames(output.mat)) ==
1)[1] - 1
output.mat[1, 1:to.here] <- c(log.lik, aic, aicc,
as.numeric(diag(bm.model[[1]])), anc.state)
print("BM model", quote = FALSE)
print(output.mat[1, 1:to.here])
fixed.time <- NULL
vo.out <- list()
full.model.out <- list()
if (saveAll) output.all <- TRUE
for (q in 1:nSplits) {
all.models <- parallel::mclapply(splitTime, mc.cores = n.cores,
function(x_times) {
splitTimeInt <- sort(c(x_times, fixed.time))
nSplitInt.n <- length(splitTimeInt) + 1
rateVec <- rep(1, nSplitInt.n)
var.timeslice <- function(rate.vec) transformPhylo.ll(y,
phy, timeRates = rate.vec, splitTime = splitTimeInt,
model = "timeSlice", meserr = meserr, covPIC = covPIC)[[2]]
vo <- optim(rateVec, var.timeslice, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound,
control = controlList)
c(vo$par, vo$value)
})
all.models <- sapply(all.models, cbind)
colnames(all.models) <- splitTime
rownames(all.models) <- c(paste0("rate ", 1:(q + 1)), "loglikelihood")
full.model.out[[q]] <- all.models
best.model.n <- which.max(all.models[nrow(all.models),
])
shift.time <- splitTime[best.model.n]
fixed.time <- c(fixed.time, shift.time)
splitTime <- splitTime[-which(splitTime == shift.time)]
log.lik <- tail(all.models[, best.model.n], 1)
rates <- all.models[, best.model.n][-dim(all.models)[1]]
phy.temp <- transformPhylo(y = y, phy = phy,
timeRates = rates, splitTime = fixed.time,
model = "timeSlice", meserr = meserr)
anc.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
phy = phy.temp, method = "pic")[[1]][1])))
bVar <- as.numeric(likTraitPhylo(y, phy.temp,
covPIC = covPIC)[[1]])
param <- length(rates) + 2
aic <- aic.fun(log.lik, param)
aicc <- aicc.fun(log.lik, param, Ntip(phy))
output.mat[q + 1, 1:to.here] <- c(log.lik, aic,
aicc, bVar, anc.state)
output.mat[q + 1, (to.here + 1):(to.here + length(rates))] <- rates
start.time <- tail(1:dim(output.mat)[2], nSplits)[1:q]
output.mat[q + 1, start.time] <- sort(fixed.time)
na.test <- which(is.na(output.mat[q + 1, ]))
print(paste("shift", q), quote = F)
na.test <- which(is.na(output.mat[q + 1, ]))
if (length(na.test) > 0) {
print(output.mat[q + 1, -which(is.na(output.mat[q +
1, ]))])
} else {
print(output.mat[q + 1, ])
}
rateVec <- rep(1, length(rates))
var.timeslice <- function(rate.vec) transformPhylo.ll(y,
phy, timeRates = rate.vec, splitTime = fixed.time,
model = "timeSlice", meserr = meserr, covPIC = covPIC)[[2]]
vo.out[[q]] <- optim(rateVec, var.timeslice,
method = "L-BFGS-B", lower = lowerBound, upper = upperBound,
control = controlList)
}
} else {
nSplits <- length(splitTime)
rateVec <- rep(1, (nSplits + 1))
output.mat <- matrix(NA, nrow = 2, ncol = (3 + nSplits +
length(rateVec)) + (2 * ncol(y)))
bm.phy <- transformPhylo(phy = phy, model = "bm",
meserr = meserr, y = y)
bm.model <- likTraitPhylo(y, bm.phy, covPIC = covPIC)
log.lik <- as.numeric(bm.model[[2]])
aic <- aic.fun(log.lik, 2)
aicc <- aicc.fun(log.lik, 2, Ntip(phy))
anc.state <- apply(y, 2, function(col.y) as.numeric(as.numeric(ace(col.y,
bm.phy, method = "pic")[[1]][1])))
colnames(output.mat) <- 1:ncol(output.mat)
colnames(output.mat)[1:3] <- c("lnL", "AIC", "AICc")
c.y <- ncol(y)
colnames(output.mat)[4:(4 + c.y - 1)] <- paste0("sigma.sq.",
1:ncol(y))
n.c.ct <- (4 + c.y)
colnames(output.mat)[n.c.ct:(n.c.ct + c.y - 1)] <- paste0("anc.state.",
1:ncol(y))
n.c.ct <- (n.c.ct + c.y):(n.c.ct + c.y + nSplits)
colnames(output.mat)[n.c.ct] <- paste0("rates", 1:(nSplits +
1))
n.c.ct <- (max(n.c.ct) + 1):(max(n.c.ct) + nSplits)
colnames(output.mat)[n.c.ct] <- paste0("time.split",
1:(nSplits))
to.here <- which(regexpr("rates", colnames(output.mat)) ==
1)[1] - 1
output.mat[1, 1:to.here] <- c(log.lik, aic, aicc,
as.numeric(diag(bm.model[[1]])), anc.state)
print("BM model")
print(output.mat[1, 1:to.here])
var.timeslice <- function(rate.vec) transformPhylo.ll(y,
phy, timeRates = rate.vec, splitTime = splitTime,
model = "timeSlice", meserr = meserr, covPIC = covPIC)[[2]]
vo.out <- optim(rateVec, var.timeslice, method = "L-BFGS-B",
lower = lowerBound, upper = upperBound, control = controlList)
log.lik <- vo.out$value
rates <- vo.out$par
param <- length(rates) + 2
aic <- aic.fun(log.lik, param)
aicc <- aicc.fun(log.lik, param, Ntip(phy))
phyTemp <- transformPhylo(y = y, phy = phy, timeRates = rates,
splitTime = splitTime, model = "timeSlice", meserr = meserr)
bVar <- as.numeric(likTraitPhylo(y, phyTemp, covPIC = covPIC)[[1]])
anc.state <- apply(y, 2, function(col.y) as.numeric(ace(col.y,
phyTemp, method = "pic")[[1]][1]))
output.mat[2, 1:to.here] <- c(log.lik, aic, aicc,
bVar, anc.state)
output.mat[2, (to.here + 1):(to.here + length(rates))] <- rates
rt <- max(which(regexpr("rates", colnames(output.mat)) ==
1)) + 1
full.rt <- ncol(output.mat)
output.mat[2, rt:full.rt] <- splitTime
print("shiftModel")
print(output.mat[2, ])
}
out <- list()
out$timeSlice <- output.mat
out$optim.output <- vo.out
out$phy <- phy
out$y <- y
out$meserr <- meserr
out$covPIC <- covPIC
if (output.all)
out$all.models <- full.model.out
out$testShiftTimes <- testShiftTimes
class(out) <- "timeSlice.ML"
})
return(out)
}
|
"mouse"
|
polylo <-
function (x, degree = 1, monomial = FALSE)
{
if (degree >= 4)
warning("This is not a smart polynomial routine. You may get numerical problems with a degree of 4 or more")
x <- as.matrix(x)
dn <- dimnames(x)
dd <- dim(x)
np <- dd[2]
ad <- rep(1, ncol(x))
if (np == 1)
monomial <- TRUE
if (degree > 1) {
if (monomial) {
ad <- seq(degree)
px <- x
cc <- sapply(split(paste(diag(np)), rep(seq(np),
rep(np, np))), paste, collapse = "")
tx <- x
for (i in 2:degree) {
px <- px * tx
x <- cbind(x, px)
cc <- c(cc, sapply(split(paste(diag(np) * i),
rep(seq(np), rep(np, np))), paste, collapse = ""))
}
}
else {
matarray <- array(x, c(dd, degree))
for (i in 2:degree) matarray[, , i] <- x^i
matarray <- aperm(matarray, c(1, 3, 2))
x <- matarray[, , np, drop=TRUE]
ad0 <- seq(degree)
ad <- ad0
ncol.mat0 <- degree
ncol.x <- degree
d0 <- paste(ad0)
cc <- d0
for (ii in seq(np - 1, 1)) {
index0 <- rep(seq(ncol.mat0), ncol.x)
index <- rep(seq(ncol.x), rep(ncol.mat0, ncol.x))
newad <- ad0[index0] + ad[index]
retain <- newad <= degree
mat0 <- matarray[, , ii, drop = TRUE]
if (any(retain))
newmat <- mat0[, index0[retain]] *
x[, index[retain]]
else newmat <- NULL
ddn <- paste(d0[index0[retain]], cc[index[retain]],
sep = "")
zeros <- paste(rep(0, nchar(cc[1])), collapse = "")
cc <- paste(0, cc, sep = "")
d00 <- paste(d0, zeros, sep = "")
x <- cbind(mat0, x, newmat)
cc <- c(d00, cc, ddn)
ad <- c(ad0, ad, newad[retain])
ncol.x <- length(ad)
}
}
if (!is.null(dn))
dn[[2]] <- cc
else dn <- list(NULL, cc)
dimnames(x) <- dn
}
attr(x, "degree") <- ad
x
}
|
add.fragment.coordinates <- function(id.data) {
if( !is.data.frame(id.data) ) {
stop('id.data must be a data frame');
}
expanded.data <- id.data;
if( 'target.id' %in% names(id.data) ) {
target.coordinates <- get.id.components(id.data$target.id);
target.coordinates <- as.data.table( do.call(rbind, target.coordinates) );
names(target.coordinates) <- paste0('target.', c('chr', 'start', 'end'));
expanded.data <- cbind(expanded.data, target.coordinates);
}
if( 'bait.id' %in% names(id.data) ) {
bait.coordinates <- get.id.components(id.data$bait.id);
bait.coordinates <- as.data.table( do.call(rbind, bait.coordinates) );
names(bait.coordinates) <- paste0('bait.', c('chr', 'start', 'end'));
expanded.data <- cbind(expanded.data, bait.coordinates);
}
for(column in names(expanded.data)[ grepl('\\.(start|end)$', names(expanded.data) ) ] ) {
set(expanded.data, j = column, value = as.numeric( expanded.data[[ column ]] ) );
}
return(expanded.data);
}
|
summary.tam.linking <- function( object, file=NULL, ...)
{
tam_osink( file=file)
cat("------------------------------------------------------------\n")
tam_print_package_rsession(pack="TAM")
cat( paste0("Linking of ", object$NS, " Studies\n") )
tam_print_call(object$CALL)
tam_print_computation_time(object=object)
type <- object$type
cat("method","=", object$method, "\n")
cat("type","=", type, " | ")
if (type=="Hae"){ cat("Haebara Linking Method\n")}
if (type=="RobHae"){
cat("Robust Haebara Linking Method:")
cat(" pow","=", object$pow_rob_hae, "|")
cat(" eps","=", object$eps_rob_hae, "")
}
if (type=="SL"){ cat("Stocking Lord Linking Method\n")}
cat("\n------------------------------------------------------------\n")
cat( "Number of Linking Items\n" )
obji <- object$N_common
print(obji)
cat("------------------------------------------------------------\n")
cat( "Transformation Constants for Item Parameters\n" )
obji <- object$trafo_items
obji <- round(obji,3)
print(obji)
cat("------------------------------------------------------------\n")
cat( "Transformation Constants for Person Parameters\n" )
obji <- object$trafo_persons
obji <- round(obji,3)
print(obji)
cat("------------------------------------------------------------\n")
cat( "Means and Standard Deviations of Studies \n" )
obji <- object$M_SD
obji <- round(obji,3)
print(obji)
tam_csink(file=file)
}
|
rpartCVSingle <-
function(data, covars, cvNum, cpTable, dropGrps, numCPLvls, minsplit, minbucket){
dropLoc <- which(dropGrps == cvNum)
subData <- data[-dropLoc,, drop=FALSE]
dropData <- data[dropLoc,, drop=FALSE]
subCovs <- covars[-dropLoc,, drop=FALSE]
dropCovs <- covars[dropLoc,, drop=FALSE]
subRpartRes <- DM.Rpart.Base(subData, subCovs, FALSE, minsplit, minbucket)$fullTree
subData <- subData/(rowSums(subData))
dropData <- dropData/(rowSums(dropData))
MSEn <- rep(NA, numCPLvls)
subTree <- vector("list", numCPLvls)
for(i in 1:numCPLvls){
subTree[[i]] <- rpart::prune(subRpartRes, cp=cpTable[i, 1])
pruneSubTree <- subTree[[i]]
subPre <- predict(pruneSubTree, newdata=subCovs, type="vector")
dropPre <- predict(pruneSubTree, newdata=dropCovs, type="vector")
tempDist <- 0
for(j in 1:length(dropPre))
tempDist <- tempDist + (dist(rbind(dropData[j,], colMeans(subData[subPre == dropPre[j],]))))^2
MSEn[i] <- tempDist/length(dropPre)
}
names(MSEn) <- cpTable[,2] + 1
return(list(errorRate=MSEn, subTree=subTree))
}
|
divergent <- function (coordinates,
currentES,
proposedES){
dEdges <- which(currentES != proposedES)
dNodes <- unique(as.vector(coordinates[, dEdges]))
return (list(dEdges = dEdges,
dNodes = dNodes))
}
|
unname <- function (obj, force = FALSE)
{
if (!is.null(names(obj)))
names(obj) <- NULL
if (!is.null(dimnames(obj)) && (force || !is.data.frame(obj)))
dimnames(obj) <- NULL
obj
}
|
contToDisc <- function(dataSet, timeColumn, intervalLimits, equi=FALSE) {
if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")}
if(!(is.character(timeColumn))) {stop("Argument *timeColumn* is not in the correct format! Please specify as character.")}
if(length(timeColumn)!=1) {stop("Argument *timeColumn* is not in the correct format! Please specify as scalar with length one.")}
if(equi==FALSE) {
if(!(is.vector(intervalLimits))) {stop("Argument *intervalLimits* is not in the correct format! Please specify as numeric vector.")}
if(!(is.numeric(intervalLimits))) {stop("Argument *intervalLimits* is not in the correct format! Please specify as numeric vector.")}
}
if(equi==TRUE & length(intervalLimits) != 1) {stop("Argument *intervalLimits* is not in the correct format! Please specify an scalar integer value.")}
if(equi==TRUE & any(floor(intervalLimits) != intervalLimits)) {stop("Argument *intervalLimits* is not in the correct format! Please specify an scalar integer value.")}
if(any(class(tryCatch(dataSet [, timeColumn], error=function (e) e)) == "error"))
{stop("*timeColumn* is not available in *dataSet*! Please specify the correct column of observed times.")}
obsTime <- dataSet [, timeColumn]
if(equi==FALSE) {
intervalLimits <- c(0, intervalLimits)
Check <- tryCatch(cut(obsTime, intervalLimits, right = FALSE), error=function (e) "Bug!")
if(identical(Check, "Bug!")) {
intervalLimits [-1] <- jitter(intervalLimits [-1], factor=0.01)
}
}
timeDisc <- as.ordered(as.numeric(cut(obsTime, intervalLimits, right = FALSE)))
dataSet <- cbind(timeDisc=timeDisc, dataSet)
return(dataSet)
}
dataLong <- function (dataSet, timeColumn, censColumn, timeAsFactor=TRUE,
remLastInt=FALSE, aggTimeFormat=FALSE, lastTheoInt=NULL) {
if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")}
if(!(is.character(timeColumn))) {stop("Argument *timeColumn* is not in the correct format! Please specify as character.")}
if(length(timeColumn)!=1) {stop("Argument *timeColumn* is not in the correct format! Please specify as scalar with length one.")}
if(!(is.character(censColumn))) {stop("Argument *censColumn* is not in the correct format! Please specify as character.")}
if(length(censColumn)!=1) {stop("Argument *censColumn* is not in the correct format! Please specify as scalar with length one.")}
if(any(class(tryCatch(dataSet [, timeColumn], error=function (e) e)) == "error")) {
stop("*timeColumn* is not available in *dataSet*! Please specify the correct column of observed times.")
}
if(any(class(tryCatch(dataSet [, censColumn], error=function (e) e)) == "error")) {
stop("*censColumn* is not available in *dataSet*! Please specify the correct column of the event indicator.")
}
if(!all(dataSet [, timeColumn]==floor(as.numeric(as.character(dataSet [, timeColumn]))))) {
stop("*timeColumn* has not only integer values! Please convert the observed time in discrete intervals.")
}
if(!all(as.numeric(as.character(dataSet [, censColumn]))==0 | as.numeric(as.character(dataSet [, censColumn]))==1)) {
stop("*censColumn* is not a binary vector! Please check, that events equals 1 and 0 otherwise.")
}
c1 <- which(eval(timeColumn)==colnames(dataSet))
c2 <- which(eval(censColumn)==colnames(dataSet))
if(aggTimeFormat){
obj <- rep(1:nrow(dataSet), each=lastTheoInt)
} else{
obj <- rep(1:nrow(dataSet), as.vector(dataSet[, c1]))
}
dataSetLong <- dataSet[obj, ]
if(aggTimeFormat){
if(timeAsFactor) {
timeInt <- factor( rep(1:lastTheoInt, nrow(dataSet)) )
}
else{
timeInt <- rep(1:lastTheoInt, nrow(dataSet))
}
y <- c(unlist(apply(dataSet, 1, FUN =
function(k) c(rep(0, as.numeric(k[c1])-1), as.numeric(k[c2]),
rep(0, lastTheoInt - as.numeric(k[c1]) ) ) )))
} else{
if(timeAsFactor) {
timeInt <- factor(unlist(apply(dataSet, 1, FUN = function(k) 1:k[c1])))
}
else{
timeInt <- unlist(apply(dataSet, 1, FUN = function(k) 1:k[c1]))
}
y <- c(unlist(apply(dataSet, 1, FUN =
function(k) c(rep(0, as.numeric(k[c1])-1), as.numeric(k[c2])) )))
}
dataSetLong <- cbind(obj, timeInt, y, dataSetLong)
if(remLastInt) {
remInd <- which(dataSetLong$y==1 &
dataSetLong$timeInt==max(as.numeric(as.character(
dataSetLong$timeInt))) )
if(length(remInd)!=0) {
dataSetLong <- dataSetLong[-remInd, ]
}
}
return(dataSetLong)
}
dataLongTimeDep <- function (dataSet, timeColumn, censColumn, idColumn, timeAsFactor=TRUE) {
if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")}
if(!(is.character(timeColumn))) {stop("Argument *timeColumn* is not in the correct format! Please specify as character.")}
if(length(timeColumn)!=1) {stop("Argument *timeColumn* is not in the correct format! Please specify as scalar with length one.")}
if(!(is.character(censColumn))) {stop("Argument *censColumn* is not in the correct format! Please specify as character.")}
if(length(censColumn)!=1) {stop("Argument *censColumn* is not in the correct format! Please specify as scalar with length one.")}
if(any(class(tryCatch(dataSet [, timeColumn], error=function (e) e)) == "error")) {
stop("*timeColumn* is not available in *dataSet*! Please specify the correct column of observed times.")
}
if(any(class(tryCatch(dataSet [, censColumn], error=function (e) e)) == "error")) {
stop("*censColumn* is not available in *dataSet*! Please specify the correct column of the event indicator.")
}
if(any(class(tryCatch(dataSet [, idColumn], error=function (e) e)) == "error")) {
stop("*idColumn* is not available in *dataSet*! Please specify the correct column of the identification number.")
}
if(!all(dataSet [, timeColumn]==floor(as.numeric(as.character(dataSet [, timeColumn]))))) {
stop("*timeColumn* has not only integer values! Please convert the observed time in discrete intervals.")
}
if(!all(as.numeric(as.character(dataSet [, censColumn]))==0 | as.numeric(as.character(dataSet [, censColumn]))==1)) {
stop("*censColumn* is not a binary vector! Please check, that events equals 1 and 0 otherwise.")
}
dataSet <- dataSet[order(dataSet [, idColumn]), ]
splitDataSet <- split(x=dataSet, f=dataSet [, idColumn])
lengthSplitDataSet <- 1:length(splitDataSet)
Counts <- lapply(splitDataSet, function (x) c(diff(x [, timeColumn]), 1))
SumCounts <- as.numeric(sapply(Counts, function (x) sum(x)))
Indizes <- lapply(lengthSplitDataSet, function (x) rep(x=1:dim(splitDataSet [[x]])[1], times=Counts [[x]]))
dataList <- lapply(lengthSplitDataSet, function (x) splitDataSet [[x]] [Indizes [[x]], ])
dataList <- do.call(rbind, dataList)
dataListID <- lapply(lengthSplitDataSet, function (x) rep(x, SumCounts [x]))
dataListID <- do.call(c, dataListID)
dataListTimeInt <- lapply(lengthSplitDataSet, function (x) 1:SumCounts [x])
if(timeAsFactor) {
dataListTimeInt <- factor(do.call(c, dataListTimeInt))
}
else{
dataListTimeInt <- do.call(c, dataListTimeInt)
}
dataListResponse <- lapply(lengthSplitDataSet, function (x) c(rep(0, SumCounts [x]-1), as.numeric(as.character(tail(splitDataSet [[x]] [, censColumn], 1)))))
dataListResponse <- do.call(c, dataListResponse)
dataComplete <- cbind(obj=dataListID, timeInt=dataListTimeInt, y=dataListResponse, dataList)
return(dataComplete)
}
dataLongCompRisks <- function (dataSet, timeColumn, eventColumns,
eventColumnsAsFactor=FALSE, timeAsFactor=TRUE) {
if(!is.data.frame(dataSet)) {stop("Argument *dataSet* is not in the correct format! Please specify as data.frame object.")}
if(!(is.character(timeColumn))) {stop("Argument *timeColumn* is not in the correct format! Please specify as character.")}
if(length(timeColumn)!=1) {stop("Argument *timeColumn* is not in the correct format! Please specify as scalar with length one.")}
if(!all(is.character(eventColumns))) {stop("Argument *eventColumns* is not in the correct format! Please specify as character.")}
if(any(class(tryCatch(dataSet [, timeColumn], error=function (e) e)) == "error")) {
stop("*timeColumn* is not available in *dataSet*! Please specify the correct column of observed times.")
}
if(any(class(tryCatch(dataSet [, eventColumns], error=function (e) e)) == "error")) {
stop("*eventColumns* is not available in *dataSet*! Please specify the correct column of the event indicator.")
}
if(!all(dataSet [, timeColumn]==floor(as.numeric(as.character(dataSet [, timeColumn]))))) {
stop("*timeColumn* has not only integer values! Please convert the observed time in discrete intervals.")
}
if(eventColumnsAsFactor) {
respFact <- dataSet[, eventColumns]
respMat <- model.matrix(~., data.frame(respFact))[, -1]
eventColumns <- levels(respFact)[-1]
dimnames(respMat) [[2]] <- eventColumns
dataSet <- cbind(respMat, dataSet)
}
checkVec <- vector("logical", length(eventColumns))
for(i in 1:length(eventColumns)) {
checkVec [i] <- all(as.numeric(as.character(dataSet [, eventColumns [i] ]))==0 | as.numeric(as.character(dataSet [, eventColumns [i] ]))==1)
}
if(!all(checkVec)) {
stop("*eventColumns* is not a binary vector! Please check, that events equals 1 and 0 otherwise.")
}
indextimeColumn <- which(eval(timeColumn)==colnames(dataSet))
indizeseventColumns <- sapply(1:length(eventColumns), function (x) which(eval(eventColumns [x])==colnames(dataSet)))
dataSet_timeColumn <- as.numeric(as.character(dataSet[, indextimeColumn]))
obj <- rep(1:nrow(dataSet), dataSet_timeColumn)
dataSetLong <- dataSet[obj,]
timeInt <- unlist(apply(dataSet, 1, FUN = function(k) 1:k[indextimeColumn]))
if(timeAsFactor){timeInt <- factor(timeInt)}
dataSet_eventColumns <- dataSet [, indizeseventColumns]
eventColumnsorShort <- 1 - rowSums(dataSet_eventColumns)
responsesShort <- as.matrix(cbind(eventColumnsorShort, dataSet_eventColumns))
dimnames(responsesShort) [[2]] <- 1:length(dimnames(responsesShort) [[2]])
NoeventColumns <- length(indizeseventColumns)
responses <- matrix(0, nrow=0, ncol=NoeventColumns + 1)
for(i in 1:dim(dataSet) [1]) {
row_rep <- as.numeric(as.character(dataSet [i, indextimeColumn])) - 1
mat_temp <- matrix(rep(c(1, rep(0, NoeventColumns)), row_rep), nrow=row_rep, ncol=NoeventColumns + 1, byrow=TRUE)
mat_temp <- rbind(mat_temp, responsesShort [i, ])
responses <- rbind(responses, mat_temp)
}
dimnames(responses) [[2]] <- paste("e", 0:NoeventColumns, sep="")
if(eventColumnsAsFactor) {
dataSetLong <- dataSetLong[, -which(names(dataSetLong) %in% eventColumns)]
}
dataSetLong <- cbind(obj, timeInt, responses, dataSetLong)
return(dataSetLong)
}
dataLongCompRisksTimeDep <- function (dataSet, timeColumn, eventColumns,
eventColumnsAsFactor=FALSE, idColumn,
timeAsFactor=TRUE) {
if(eventColumnsAsFactor) {
respFact <- dataSet[, eventColumns]
respMat <- model.matrix(~., data.frame(respFact))[, -1]
eventColumns <- levels(respFact)[-1]
dimnames(respMat) [[2]] <- eventColumns
dataSet <- cbind(respMat, dataSet)
}
indizeseventColumns <- sapply(1:length(eventColumns), function (x) which(eval(eventColumns [x])==colnames(dataSet)))
NoeventColumns <- length(indizeseventColumns)
responsesShort <- cbind(1, matrix(0, nrow=nrow(dataSet), ncol=NoeventColumns))
namesEventColumnsNew <- paste("e", 0:NoeventColumns, sep="")
dimnames(responsesShort) [[2]] <- namesEventColumnsNew
dataSet <- cbind(responsesShort, dataSet)
dataSet <- dataSet[order(dataSet [, idColumn]), ]
splitDataSet <- split(x=dataSet, f=dataSet [, idColumn])
lengthSplitDataSet <- 1:length(splitDataSet)
Counts <- lapply(splitDataSet, function (x) c(diff(x [, timeColumn]), 1))
SumCounts <- as.numeric(sapply(Counts, function (x) sum(x)))
Indizes <- lapply(lengthSplitDataSet, function (x) rep(x=1:dim(splitDataSet [[x]])[1], times=Counts [[x]]))
dataList <- lapply(lengthSplitDataSet, function (x) splitDataSet [[x]] [Indizes [[x]], ])
dataList <- do.call(rbind, dataList)
dataListID <- lapply(lengthSplitDataSet, function (x) rep(x, SumCounts [x]))
dataListID <- do.call(c, dataListID)
dataListTimeInt <- lapply(lengthSplitDataSet, function (x) 1:SumCounts [x])
if(timeAsFactor) {
dataListTimeInt <- factor(do.call(c, dataListTimeInt))
}
else{
dataListTimeInt <- do.call(c, dataListTimeInt)
}
cumSumSumCounts <- cumsum(SumCounts)
rowSumsPre <- rowSums(dataList [, eventColumns])
for(i in 1:length(cumSumSumCounts)) {
if(rowSumsPre[ cumSumSumCounts[i] ]==1) {
dataList[cumSumSumCounts[i], namesEventColumnsNew[1] ] <- 0
relCol <- which(dataList [cumSumSumCounts[i], eventColumns]==1) + 1
dataList[cumSumSumCounts[i], namesEventColumnsNew[relCol] ] <- 1
}
}
if(eventColumnsAsFactor) {
dataList <- dataList[, -which(names(dataList) %in% eventColumns)]
}
dataComplete <- cbind(obj=dataListID, timeInt=dataListTimeInt, dataList)
return(dataComplete)
}
dataCensoring <- function(dataSetLong, respColumn, timeColumn){
lastTimeInd <- c((which(dataSetLong[, timeColumn]==1)-1)[-1], dim(dataSetLong)[1])
ResultVec <- dataSetLong[, respColumn]
ResultVec[lastTimeInd] <- ifelse(dataSetLong[lastTimeInd, "y"]==0, 1, NA)
NewDataSet <- cbind(yCens = ResultVec, dataSetLong)
return(NewDataSet)
}
dataCensoringShort <- function(dataSet, eventColumns, timeColumn){
ResultVec <- ifelse(rowSums(dataSet[, eventColumns, drop=FALSE])==0, 1, 0)
deleteIndices <- ResultVec==0 & dataSet[, timeColumn]==1
dataSet <- dataSet[!deleteIndices, ]
ResultVec <- ResultVec[!deleteIndices]
timeCens <- as.numeric(as.character(dataSet[, timeColumn]))
timeCens[ResultVec==0] <- timeCens[ResultVec==0]-1
NewDataSet <- cbind(yCens = ResultVec, timeCens=timeCens, dataSet)
return(NewDataSet)
}
dataLongSubDist <- function(dataSet, timeColumn, eventColumns,
eventFocus, timeAsFactor=TRUE) {
eventColumns <- c(eventColumns[eventColumns==eventFocus],
eventColumns[eventColumns!=eventFocus])
dataSet_timeColumn <- as.numeric(as.character(dataSet[, timeColumn]))
tmax <- max(dataSet_timeColumn)
delta_i <- rowSums(dataSet[, eventColumns])==1
epsilon_i <- sapply(1:dim(dataSet)[1],
function(x) ifelse(delta_i[x],
which(dataSet[x, eventColumns]==1), 0))
dataSet_timeColumn <- ifelse(delta_i &
dataSet[, eventFocus] == 0, tmax,
dataSet_timeColumn)
obj <- rep(1:nrow(dataSet), each=tmax)
timeInt <- c(sapply(1:length(dataSet_timeColumn),
function(k) 1:tmax))
eventFocus <- dataSet[, eventFocus]
y <- c(sapply(1:length(dataSet_timeColumn),
function(k) c(rep(0, dataSet_timeColumn[k]-1),
eventFocus[k],
rep(0, tmax-dataSet_timeColumn[k]) ) ))
estG <- estSurvCens(dataSet=dataSet, timeColumn=timeColumn,
eventColumns=eventColumns)
weights <- estG[timeInt] /
estG[pmin(dataSet[obj, timeColumn], timeInt)] *
(ifelse(timeInt <= dataSet[obj, timeColumn], 1, 0) +
ifelse(dataSet[obj, timeColumn] <= (timeInt-1) &
delta_i[obj] * epsilon_i[obj] > 1, 1, 0) )
if(timeAsFactor){timeInt <- factor(timeInt)}
dataSetLong <- cbind(obj=obj, timeInt=timeInt, y=y, dataSet[obj, ])
Output <- cbind(dataSetLong, subDistWeights=weights)
return(Output)
}
dataLongMultiSpell <- function(dataSet, timeColumn, censColumn, idColumn,
timeAsFactor=FALSE){
if(!is.factor(dataSet[, censColumn])){
dataSet[, censColumn] <- factor(dataSet[, censColumn])
}
eventExpand <- model.matrix(~.-1, dataSet[, censColumn, drop=FALSE])
dimnames(eventExpand)[[2]] <- paste("e", 0:(dim(eventExpand)[2]-1), sep="")
dataSet <- cbind(obj=NA, timeInt=NA, eventExpand, dataSet)
splitDat <- split(dataSet, dataSet[, idColumn])
lenSplitDat <- length(splitDat)
for( j in 1:lenSplitDat ){
actualTime <- splitDat[[j]][, timeColumn]
diffTime <- diff( actualTime )
defIndices <- 1:length(actualTime)
if(actualTime[1] > 1){
defIndices <- c( defIndices, rep(1, actualTime[1]-1) )
}
for( i in 1:length(diffTime) ){
if(length(diffTime) > 0){
if(diffTime[i] > 1){
defIndices <- c( defIndices, rep(i+1, diffTime[i]-1) )
}
}
}
defIndices <- sort(defIndices)
splitDat[[j]] <- splitDat[[j]][defIndices, ]
splitDat[[j]][, "obj"] <- j
splitDat[[j]][, "timeInt"] <- 1:dim(splitDat[[j]])[1]
for( k in 1:length(actualTime) ){
if(length(splitDat[[j]][defIndices==k, "e0"]) > 1){
relInd <- which(defIndices==k)
relInd <- relInd[-length(relInd)]
splitDat[[j]][relInd, "e0"] <- 1
splitDat[[j]][relInd, paste("e",
1:(dim(eventExpand)[2]-1), sep="")] <- 0
}
}
}
allDat <- as.data.frame(rbindlist(splitDat))
if(timeAsFactor){
allDat$timeInt <- factor(allDat$timeInt)
}
return(allDat)
}
|
gfunction.alp.bet.cc <- function(para, map, ref, Delta, delta, ncase, nctrl, xi, pr){
nmodel <- length(map$bet)
g.alp.bet <- list()
n <- nrow(ref)
const <- list()
for(i in 1:nmodel){
id <- c(alp.index.cc(map, i), map$bet[[i]])
gam <- para[id]
rx <- as.matrix(ref[, names(gam), drop = FALSE])
rho.i <- ncase[i, i] / nctrl[i, i]
const[[i]] <- -rx * (delta[, i] * (1 - rho.i * delta[, i]) * (1 + rho.i * Delta) / (1 + rho.i * delta[, i])^3)
}
nlam <- max(map$lam)
offset <- max(map$the)
foo <- function(j, l){
paste0(j,'-',l)
}
for(i in 1:nmodel){
id.a <- alp.index.cc(map, i)
if(is.null(id.a)){
next
}
id.b <- map$bet[[i]]
id <- c(id.a, id.b)
for(j in id.a){
fxj <- ref[, names(para)[j]]
tmp <- const[[i]] * fxj
for(l in id.b){
fxl <- ref[, names(para)[l]]
gt <- matrix(0, nrow = n, ncol = nlam - 1)
gt[, id - offset] <- tmp * fxl
g.alp.bet[[foo(j,l)]] <- t(gt %*% xi) %*% pr
}
}
}
if(length(g.alp.bet) == 0){
g.alp.bet <- NULL
}
g.alp.bet
}
|
bridge <- function()
{
left <- c(0, 1, 2.1, 3.2)
right <- c(4.5, 2, 3.1, 4.2)
data.frame(left = left, right = right)
}
clique <- function()
{
left <- 0:9 / 10
right <- left + 1
data.frame(left = left, right = right)
}
integers <- function()
{
left <- c(0, 0, 0, 1, 2)
right <- c(0, 1, 2, 2, 2)
data.frame(left = left, right = right)
}
parts <- function()
{
left <- sort(c(1:3, 1:3 + 0.1))
right <- left + 0.7
data.frame(left = left, right = right)
}
simple <- function()
{
left <- 0:2 * 0.5 + 1
right <- left + 0.75
data.frame(left = left, right = right)
}
|
dmixing=function (x, sevdist, log = FALSE){
cmu=sevdist$par[[3]][[5]][1]
ctau=sevdist$par[[3]][[5]][2]
rx <- function(x, cmu, ctau) {
(sevdist$par[[1]][[1]](x) - sevdist$par[[2]][[1]](x)) *
atan((x - cmu)/ctau)
}
d = x
r = try(pracma::quadinf(function(x){rx(x, cmu=cmu, ctau = ctau)}, xa = 0, xb=Inf)$Q)
pweights = pcauchy(x, cmu, ctau)
d = ((1 - pweights) * sevdist$par[[2]][[1]](x) + pweights *
sevdist$par[[1]][[1]](x))/(1+r/pi)
if (log)
d = log(d)
return(d)
}
pmixing=function (q, sevdist, lower.tail = TRUE){
sapply(q, function(q){
cmu=sevdist$par[[3]][[5]][1]
ctau=sevdist$par[[3]][[5]][2]
rx <- function(x, cmu, ctau) {
(sevdist$par[[1]][[1]](x) - sevdist$par[[2]][[1]](x)) *
atan((x - cmu)/ctau)
}
r = try(pracma::quadinf(function(x){rx(x, cmu = cmu, ctau = ctau)}, xa = 0,xb = Inf)$Q)
p=NULL
rx_body <- function(x, cmu, ctau) {
(1 - pcauchy(x, cmu, ctau)) * sevdist$par[[2]][[1]](x)
}
rx_tail <- function(x, cmu, ctau) {
pcauchy(x, cmu, ctau) * sevdist$par[[1]][[1]](x)
}
r1 = try(pracma::integral(function(x){rx_body(x,cmu = cmu, ctau = ctau)}, xmin = 0, xmax = q))
r2 = try(pracma::integral(function(x){rx_tail(x, cmu = cmu, ctau = ctau)}, xmin = 0, xmax = q))
p=c(p,(r1+r2)/(1+r/pi))
if (!lower.tail) p = 1 - p
return(p)
})
}
qmixing<-function (p, sevdist, lower.tail = TRUE)
{
sapply(p, function(p){
if (!lower.tail) p = 1 - p
q =uniroot(f = function(x) {pmixing(x,sevdist)-p}, interval= c(sevdist$par[[2]][[3]](p),sevdist$par[[1]][[3]](p)), extendInt = "yes")$root
return(as.numeric(q))
})
}
rmixing = function(n,sevdist){
rslt=NULL
while(length(rslt)<n){
u=rbinom(1,1,.5)
x=u*sevdist$par[[2]][[4]](1)+(1-u)*sevdist$par[[1]][[4]](1)
p=sevdist$par[[3]][[2]](x)
if(runif(1)<u*p+(1-u)*p) rslt=c(rslt,x)
}
return(rslt)
}
|
initialize_ctv_env <- function(cran = FALSE)
{
.ctv_env <- new.env()
.ctv_env$pkg_url <- if(cran) "../packages/%s/index.html" else "https://CRAN.R-project.org/package=%s"
.ctv_env$view_url <- if(cran) "%s.html" else "https://CRAN.R-project.org/view=%s"
.ctv_env$packagelist <- data.frame(
name = character(0),
core = logical(0),
stringsAsFactors = FALSE
)
.ctv_env$viewlist <- character(0)
.ctv_env$otherlist <- data.frame(
name = character(0),
source = character(0),
stringsAsFactors = FALSE
)
return(.ctv_env)
}
.ctv_env <- initialize_ctv_env()
pkg <- function(name, priority = "normal", register = TRUE) {
if(register) {
if(name %in% .ctv_env$packagelist$name) {
if(identical(priority, "core")) .ctv_env$packagelist$core <- TRUE
} else {
.ctv_env$packagelist <- rbind(.ctv_env$packagelist,
data.frame(name = name, core = identical(priority, "core"), stringsAsFactors = FALSE))
}
}
sprintf("[%s](%s)", name, sprintf(.ctv_env$pkg_url, name))
}
view <- function(name, register = TRUE) {
if(register) .ctv_env$viewlist <- unique(c(.ctv_env$viewlist, name))
sprintf("[%s](%s)", name, sprintf(.ctv_env$view_url, name))
}
bioc <- function(name, register = TRUE) {
if(register && !(name %in% .ctv_env$otherlist$name)) {
.ctv_env$otherlist <- rbind(.ctv_env$otherlist,
data.frame(name = name, source = "bioc", stringsAsFactors = FALSE))
}
sprintf("[%s](https://www.Bioconductor.org/packages/release/bioc/html/%s)", name, name)
}
rforge <- function(name, register = TRUE) {
if(register && !(name %in% .ctv_env$otherlist$name)) {
.ctv_env$otherlist <- rbind(.ctv_env$otherlist,
data.frame(name = name, source = "rforge", stringsAsFactors = FALSE))
}
sprintf("[%s](https://R-Forge.R-project.org/projects/%s)", name, tolower(name))
}
gcode <- function(name, register = TRUE) {
if(register && !(name %in% .ctv_env$otherlist$name)) {
.ctv_env$otherlist <- rbind(.ctv_env$otherlist,
data.frame(name = name, source = "gcode", stringsAsFactors = FALSE))
}
sprintf("[%s](https://code.google.com/archive/p/%s)", name, name)
}
ohat <- function(name, register = TRUE) {
if(register && !(name %in% .ctv_env$otherlist$name)) {
.ctv_env$otherlist <- rbind(.ctv_env$otherlist,
data.frame(name = name, source = "ohat", stringsAsFactors = FALSE))
}
sprintf("[%s](http://www.Omegahat.net/%s)", name, name)
}
github <- function(name, register = TRUE) {
if(register && !(name %in% .ctv_env$otherlist$name)) {
.ctv_env$otherlist <- rbind(.ctv_env$otherlist,
data.frame(name = name, source = "github", stringsAsFactors = FALSE))
}
sprintf("[%s](https://github.com/%s)", sapply(strsplit(name, "/", fixed = TRUE), "[", 2L), name)
}
doi <- function(name) {
sprintf("[doi:%s](https://doi.org/%s)", name, name)
}
read_ctv_rmd <- function(file, cran = FALSE, format = "html")
{
assignInNamespace(".ctv_env", initialize_ctv_env(cran = cran), ns = "ctv")
rmd <- readLines(file)
file_rmd <- gsub("\\.([[:alnum:]]+)$", ".Rmd", basename(file))
file_md <- gsub("\\.Rmd$", ".md", file_rmd)
format <- match.arg(format, c("html", "markdown"))
x <- which(substr(rmd, 1L, 3L) == "---")
if(length(x) < 2L) stop("YAML header missing or malformatted")
x <- strsplit(rmd[(x[1L] + 1L):(x[2L] - 1L)], ": ")
names(x) <- sapply(x, "[", 1L)
x <- lapply(x, "[", 2L)
if(!("url" %in% names(x))) x$url <- NULL
if(!("source" %in% names(x))) x$source <- NULL
odir <- getwd()
tdir <- tempfile()
if(!file.exists(tdir)) dir.create(tdir)
setwd(tdir)
on.exit(setwd(odir))
writeLines(rmd[-(1L:(which(substr(rmd, 1L, 3L) == "---")[2L]))], file_rmd)
knitr::knit(file_rmd, quiet = TRUE)
md <- readLines(file_md)
li <- which(substr(md, 1L, 9L) == "
if(length(li) < 1L) {
links <- NULL
} else {
links <- md[(li + 1L):length(md)]
md <- md[1L:(li - 1L)]
links <- gsub("^\\* ", "\\\\item ", links)
links <- gsub("^- ", "\\\\item ", links)
links <- paste(links, collapse = " ")
links <- gsub("^ *\\\\item *", "", links)
links <- paste0(links, " ")
links <- strsplit(links, " *\\\\item")[[1L]]
links <- gsub("^ +", "", links)
links <- gsub(" +$", "", links)
links <- gsub(" +", " ", links)
}
otherlinks <- NULL
if(length(.ctv_env$viewlist) > 0L) otherlinks <- c(otherlinks, paste("CRAN Task View:", view(sort(.ctv_env$viewlist))))
if(NROW(.ctv_env$otherlist) > 0L) {
olinks <- .ctv_env$otherlist
olinks <- olinks[order(tolower(sapply(strsplit(olinks$name, "/", fixed = TRUE), function(x) x[length(x)]))), , drop = FALSE]
olinks$source <- factor(olinks$source, levels = c("bioc", "rforge", "github", "ohat", "gcode"))
olinks <- olinks[order(olinks$source), , drop = FALSE]
for(i in levels(olinks$source)) {
ii <- which(olinks$source == i)
if(length(ii) > 0L) otherlinks <- c(otherlinks, paste0(
switch(i,
"bioc" = "Bioconductor Package",
"rforge" = "R-Forge Project",
"github" = "GitHub Project",
"ohat" = "Omegahat Package",
"gcode" = "Google Code Project"),
": ",
do.call(i, list(name = olinks$name[ii], register = FALSE))
))
}
}
x$info <- if(format == "html") pandoc(md) else md
x$packagelist <- .ctv_env$packagelist[order(.ctv_env$packagelist$name), ]
x$links <- links
if(!is.null(x$links) && format == "html") {
x$links <- as.character(pandoc(as.list(x$links)))
x$links <- gsub("(^<p>)(.*)(</p>$)", "\\2", x$links)
}
x$otherlinks <- otherlinks
if(!is.null(x$otherlinks) && format == "html") {
x$otherlinks <- as.character(pandoc(as.list(x$otherlinks)))
x$otherlinks <- gsub("(^<p>)(.*)(</p>$)", "\\2", x$otherlinks)
}
class(x) <- "ctv"
return(x)
}
ctv_xml_to_rmd <- function(x) {
file <- gsub("\\.ctv$", ".md", x)
x0 <- xml2::read_xml(x)
x <- read.ctv(x)
reg <- x$packagelist
reg$core <- c("pkg", "corepkg")[1L + reg$core]
names(reg)[2L] <- "type"
pkg <- sort(unique(xml2::xml_text(xml2::xml_find_all(x0, "//info//pkg"))))
if(length(setdiff(pkg, reg$name)) > 0L) {
warning("not all <pkg> listed in <packagelist>")
reg <- rbind(reg, data.frame(name = setdiff(pkg, reg$name), type = "pkg", stringsAsFactors = FALSE))
}
add_reg <- function(name) {
rval <- sort(unique(xml2::xml_text(xml2::xml_find_all(x0, sprintf("//info//%s", name)))))
rval <- if(length(rval) < 1L) {
NULL
} else {
data.frame(name = rval, type = name, stringsAsFactors = FALSE)
}
return(rval)
}
reg <- rbind(reg, add_reg("view"), add_reg("rforge"), add_reg("gcode"), add_reg("bioc"), add_reg("ohat"), add_reg("github"))
for(i in which(reg$type == "corepkg")) {
nami <- reg$name[i]
urli <- sprintf('<a href="../packages/%s/index.html">%s</a>', nami, nami)
rmdi <- sprintf('`r_chunk_pkg("%s",priority="core")`', nami)
x$info <- sub(urli, rmdi, x$info, fixed = TRUE)
}
make_url <- function(type, name) {
switch(type,
"pkg" = sprintf('<a href="../packages/%s/index.html">%s</a>', name, name),
"view" = sprintf('<a href="%s.html">%s</a>', name, name),
"rforge" = sprintf('<a href="https://R-Forge.R-project.org/projects/%s/"><span class="Rforge">%s</span></a>', tolower(name), name),
"gcode" = sprintf('<a href="https://code.google.com/archive/p/%s/"><span class="Gcode">%s</span></a>', name, name),
"bioc" = sprintf('<a href="https://www.Bioconductor.org/packages/release/bioc/html/%s.html"><span class="BioC">%s</span></a>', name, name),
"ohat" = sprintf('<a href="http://www.Omegahat.net/%s/"><span class="Ohat">%s</span></a>', name, name),
"github" = sprintf('<a href="https://github.com/%s/"><span class="GitHub">%s</span></a>', name, strsplit(name, "/", fixed = TRUE)[[1L]][2L])
)
}
for(j in c("corepkg", "pkg", "view", "rforge", "gcode", "bioc", "ohat", "github")) {
for(i in which(reg$type == j)) {
typj <- if(j == "corepkg") "pkg" else j
nami <- reg$name[i]
urli <- make_url(typj, nami)
rmdi <- sprintf('`r_chunk_%s("%s")`', typj, nami)
x$info <- gsub(urli, rmdi, x$info, fixed = TRUE)
}
}
x$info <- gsub("<tt>", "<code>", x$info, fixed = TRUE)
x$info <- gsub("</tt>", "</code>", x$info, fixed = TRUE)
x$info <- pandoc(x$info, from = "html", to = "markdown")
x$info <- gsub("(<div>|</div>)", "", x$info)
xi <- which(substr(x$info, 1L, 2L) == "**")
x$info[xi] <- gsub("(\\*\\*)(.*)(\\*\\*)", "
x$links <- pandoc(c("<ul>", paste0("<li>", x$links[substr(x$links, 1L, 3L) == "<a "], "</li>"), "</ul>"),
from = "html", to = "markdown")
x$header <- c("---", paste0(names(x)[1L:5L], ": ", unlist(x[1L:5L])), "---")
writeLines(c(
x$header,
"",
x$info,
"",
"
x$links
), file)
invisible(x)
}
pandoc <- function(x, ..., from = "markdown", to = "html", fixup = (from == "html" && to == "markdown"))
{
infile <- tempfile()
outfile <- tempfile()
on.exit(unlink(c(infile, outfile)))
xlist <- is.list(x)
if(xlist) {
sep <- "\007\007\007\007\007"
x <- unlist(lapply(x, c, c("", sep, "")))
}
writeLines(x, infile)
rmarkdown::pandoc_convert(input = infile, output = outfile, from = from, to = to, ...)
rval <- readLines(outfile)
if(fixup) {
rval <- gsub("\\_chunk\\_", " ", rval, fixed = TRUE)
rval <- gsub("_chunk_", " ", rval, fixed = TRUE)
rval <- gsub("\\`", "`", rval, fixed = TRUE)
rval <- gsub("\\\"", "\"", rval, fixed = TRUE)
rval <- gsub("\\'", "'", rval, fixed = TRUE)
rval <- gsub(',priority="core"', ', priority = "core"', rval, fixed = TRUE)
}
if(xlist) {
ix <- grepl(sep, rval, fixed = TRUE)
rval <- split(rval, c(0, head(cumsum(ix), -1L)))
cleansep <- function(x) {
n <- length(x)
if(n < 1L) return(x)
del <- c(
if(x[1L] == "") 1L else NULL,
if(n > 1L && grepl(sep, x[n], fixed = TRUE) && x[n - 1L] == "") n - 1L else NULL,
if(x[n] %in% c(sep, paste0("<p>", sep, "</p>"))) n else NULL
)
x[n] <- gsub(sep, "", x[n], fixed = TRUE)
if(length(del) > 0L) return(x[-del]) else return(x)
}
rval <- lapply(rval, cleansep)
}
return(rval)
}
|
chib_location <- function(s.l,X,y, verb){
beta <- do.call(rbind,s.l$beta)
Sig <- s.l$Sig
x.unit <- X
Bprior <- s.l$priors$beta
Sprior <- s.l$priors$Sig$S
nu0 <- s.l$priors$Sig$nu0
M <- length(y)
N <- nrow(y[[1]])
K <- ncol(y[[1]])
T <- ncol(beta)
P <- nrow(beta)
p.M <- P/M
X.unit <- bdiag(replicate(M,x.unit,simplify = FALSE))
X.unit <- as.matrix(X.unit)
X.shuffle <- matrix(1:(N*M), ncol = N, nrow = M, byrow = TRUE)
X.shuffle <- as.vector(X.shuffle)
X.unit <- X.unit[X.shuffle,]
X <- do.call("rbind", replicate(K, X.unit, simplify=FALSE))
y.reorg <- list()
X.N <- list()
for(i in 1:N){
y.reorg[[i]] <- matrix(NA,ncol = K, nrow = M)
X.N[[i]] <- X.unit[((i-1)*M+1):(i*M),]
for(j in 1:M){
y.reorg[[i]][j,] <- y[[j]][i,]
}
}
ybar <- lapply(y.reorg,rowMeans)
ybar <- do.call(rbind, ybar)
ybar <- as.vector(t(ybar))
Y <- do.call(rbind,y.reorg)
Y <- as.vector(Y)
S0 <- Bprior$V0
B0 <- Bprior$mu0
S0i <- solve(S0)
S0iB0 <- S0i %*% B0
B.bar <- apply(beta,1,mean)
Sig.bar <- list()
for(j in 1:N){
Sig.bar[[j]] <- apply(Sig[[j]],1,mean)
}
Sig.barfull <- list()
Si.full <- Bcov.full <- list()
S <- matrix(NA, M,M)
postB <- rep(NA, times = T)
lpost.Sig <- rep(NA, times = M)
lprior.Sig <- rep(NA, times = M)
Si <- list()
if(verb != 0){
message("Approximating integral for log-marignal likelihood")
pb <- txtProgressBar(min = 0, max = T/100, initial = 0, style = 3)
step <- 0
}
for(t in 1:T){
if(verb != 0 & (t/100) %% 1 == 0){
step <- step + 1
setTxtProgressBar(pb,value = step)
}
for(i in 1:N){
s <- Sig[[i]][,t]
S[upper.tri(S, diag = TRUE)] <- s
S[lower.tri(S)] <- t(S)[lower.tri(S)]
Si[[i]] <- solve(S)
}
Wi <- as.matrix(bdiag(Si))
XtWiX <- t(X.unit) %*% Wi %*% X.unit * K
cov.use <- solve(XtWiX + S0i)
bhat <- cov.use %*% (S0iB0 + t(X.unit)%*%Wi %*% ybar * K)
postB[t] <- dtmvnorm(B.bar, mean = bhat[,1], sigma = cov.use, lower = rep(0, times= P))
}
if(verb != 0){close(pb)}
lpostB <- log(mean(postB))
for(i in 1:N){
s <- Sig.bar[[i]]
S[upper.tri(S, diag = TRUE)] <- s
S[lower.tri(S)] <- t(S)[lower.tri(S)]
Sig.barfull[[i]] <- S
B.use <- B.bar[(((i-1)*p.M)+1):(i*p.M)]
xB <- X.N[[i]] %*% B.bar
xB <- xB[,1]
psi <- matrix(0, ncol = M, nrow = M)
for(j in 1:K){
psi <- (y.reorg[[i]][,j] - xB) %*% t(y.reorg[[i]][,j] - xB) + psi
}
psi <- psi + Sprior[[i]]*(nu0)
lpost.Sig[i] <- dinvwishart(S,nu0+K,psi, log= TRUE)
lprior.Sig[i] <- dinvwishart(S,nu0,Sprior[[i]]*nu0, log = TRUE)
}
lpriorB <- dtmvnorm(B.bar, mean = B0, sigma = S0, lower =rep(0, times = P), log = TRUE)
lpost <- sum(lpost.Sig) + lpostB
lprior <- sum(lprior.Sig) + lpriorB
Omega <- bdiag(rep(Sig.barfull, times = K))
llik <- dtmvnorm(Y,mean = as.numeric(X%*%B.bar), sigma = Omega, lower =rep(0, times = length(Y)), log = TRUE)
lml <- llik + lprior - lpost
return(list(lpost = lpost, llik = llik, lprior =lprior, lml= lml))
}
|
mask_img <- function(img,
mask,
allow.NA = TRUE
){
UseMethod("mask_img")
}
mask_img.default = function(img, mask, allow.NA = TRUE){
img = check_nifti(img)
stopifnot(inherits(img, "nifti"))
mask = ensure_array(mask)
check_mask_fail(mask = mask, allow.NA = allow.NA, allow.array = TRUE)
niftiarr(img, img * mask)
}
mask_img.nifti = function(img, mask, allow.NA = TRUE){
mask = ensure_array(mask)
mask_img.default(img = img, mask = mask, allow.NA = allow.NA)
}
mask_img.anlz = function(img, mask, allow.NA = TRUE){
img = as.nifti(img)
mask_img.nifti(img = img, mask = mask, allow.NA = allow.NA)
}
mask_img.array = function(img, mask, allow.NA = TRUE){
mask = ensure_array(mask)
check_mask_fail(mask = mask, allow.NA = allow.NA, allow.array = TRUE)
img * mask
}
mask_img.niftiImage = function(img, mask, allow.NA = TRUE){
mask = ensure_array(mask)
check_mask_fail(mask = mask, allow.NA = allow.NA, allow.array = TRUE)
img * mask
}
|
"scaleConList" <-
function (conList, specList)
{
maxDim <- max(unlist(lapply(conList, ncol)))
listProd <- vector("list", maxDim)
for(i in 1:length(conList)) {
for(j in 1:maxDim) {
if(j <= ncol(conList[[i]])) {
dtemp <- abs(conList[[i]][,j] %*% t(specList[[i]][,j]))
listProd[[j]] <- append(listProd[[j]], dtemp)
}
}
}
compMax <- unlist(lapply(listProd, max))
maxall <- max(compMax)
factScale <- sqrt(compMax / maxall)
for(i in 1:length(conList)) {
conListMax <- apply(conList[[i]], 2, max)
conList[[i]] <- t(t(conList[[i]]) * (factScale / conListMax))
}
conList
}
|
NULL
validateProbUnDes <- function(object) {
errors <- character()
if(length(errors) == 0) TRUE else errors
}
setClass("probUnDesirable",
slots = c(D = "data.frame", design = "character", N = "numeric", K = "numeric",
desFuncs = "character", weights = "numeric"),
validity = validateProbUnDes)
setMethod("$", "probUnDesirable",
function(x, name) slot(x, name))
setMethod("show", "probUnDesirable", function(object) {
cat("\nObject of class \"", class(object)[1],"\"\n\n", sep="")
names <- slotNames(object)
names <- names[!(names == "D")]
for(name in names) {
if(is.numeric(slot(object, name))){
cat(name, "=", round(slot(object, name), digits = 3), "\n")
} else{
cat(name, "=", slot(object, name), "\n")
}
}
cat("\n")
object@D <- round(object@D, digits = 3)
print(object@D)
cat("\n")
}
)
NULL
setGeneric("probUnDes", function(desScore) standardGeneric("probUnDes"))
setMethod("probUnDes", signature(desScore = "desScores"),
function(desScore) {
stopifnot(is(desScore, "desScores"))
D <- desScore$D[, -c(1,2), drop = FALSE]
W <- apply(D, 2, function(x) which(x==0))
if(is.matrix(W)){
dColnames <- colnames(W)
} else{
dColnames <- names(W)
max.length <- max(sapply(W, length))
W <- data.frame(lapply(W, function(v) { c(v, rep(0, max.length-length(v)))}))
}
P <- desScore$D[2]
Z <- data.frame(t(apply(W, 2 , function(x) sum(P[x,]))))
rownames(Z) <- "1"
colnames(Z) <- unlist(lapply(dColnames, function(x) paste("P(", x, "=0)", sep = "")))
new("probUnDesirable",
D = Z, design = desScore$design, N = desScore$N, K = desScore$K,
desFuncs = desScore$desFuncs, weights = desScore$weights)
}
)
|
netphenogeno = function(data, method = "gibbs", rho = NULL, n.rho = NULL, rho.ratio = NULL, ncores = 1, em.iter = 5, em.tol = .001, verbose = TRUE)
{
gcinfo(FALSE)
if(!is.matrix(data)) data <- as.matrix(data)
if(ncores == "all") ncores <- detectCores() - 1
if(is.null(em.iter)) em.iter = 5
if(is.null(em.tol)) em.tol = 0.001
data <-cleaning.dat(data)
n = nrow(data)
p = ncol(data)
result = list()
if( method == "gibbs" || method== "approx" )
{
if( method == "gibbs")
{
if((is.null(rho)) && (is.null(n.rho)) ) n.rho = 6
if(! is.null(rho)) n.rho = length(rho)
if(is.null(rho.ratio))
{
if( p <= 50) rho.ratio = 0.3 else rho.ratio = 0.35
}
est = vector("list", n.rho)
for(chain in 1 : n.rho )
{
if(verbose)
{
m <- paste(c("Reconstructing genotype-phenotypes networks is in progress ... :", floor(100 * chain/n.rho), "%"), collapse="")
cat(m, "\r")
flush.console()
}
if( chain == 1)
{
est[[chain]] = vector("list", n.rho)
Theta = sparseMatrix(i = 1:ncol(data), j = 1:ncol(data), x = 1)
est[[chain]] = Gibbs_method(data, rho=rho, n_rho=n.rho, rho_ratio=rho.ratio, Theta = Theta, ncores = ncores, chain = chain, max.elongation = em.iter, em.tol=em.tol)
}else{
est[[chain]] = vector("list", n.rho)
Theta = est[[(chain - 1)]]$Theta
Theta = as(Theta, "dgTMatrix")
Theta = as(Theta, "sparseMatrix")
est[[chain]] = Gibbs_method(data, rho=rho, n_rho=n.rho, rho_ratio=rho.ratio, Theta= Theta, ncores = ncores, chain = chain, max.elongation = em.iter, em.tol=em.tol)
}
}
rm(Theta)
gc()
}
if(method == "approx")
{
if( !is.null(rho) ) n.rho = length(rho)
if( is.null(n.rho) ) n.rho = 6
if(is.null(rho.ratio)) rho.ratio = 0.4
ini = initialize(data, rho = rho, n_rho = n.rho, rho_ratio = rho.ratio, ncores=ncores )
rho = ini$rho
Z = ini$Z
ES = ini$ES
lower_upper = ini$lower_upper
rm(ini)
gc()
est <- vector("list", n.rho)
for(chain in 1 : n.rho)
{
if(verbose)
{
m <- paste(c("Reconstructing genotype-phenotypes networks is in progress ... :", floor(100 * chain/n.rho), "%"), collapse="")
cat(m, "\r")
flush.console()
}
est[[chain]] <- vector("list", n.rho)
est[[(chain)]] <- approx_method(data, Z, ES=ES, rho=rho, lower_upper=lower_upper, chain = chain, ncores = ncores, em_tol=em.tol, em_iter=em.iter)
}
rm(lower_upper)
gc()
}
result$Theta = vector("list", n.rho)
result$path = vector("list", n.rho)
result$ES = vector("list", n.rho)
result$Z = vector("list", n.rho)
result$rho = vector()
result$loglik = vector()
result$data = data
rm(data)
for(chain in 1:n.rho)
{
result$Theta[[chain]] = est[[chain]]$Theta
if(!is.null(colnames(result$data))) colnames(result$Theta[[chain]]) = colnames(result$data)
result$path[[chain]] = abs(sign(result$Theta[[chain]])) - Diagonal(p)
result$ES[[chain]] = est[[chain]]$ES
result$Z[[chain]] = est[[chain]]$Z
result$rho[chain] = est[[chain]]$rho
result$loglik[chain] = est[[chain]]$loglik
}
rm(est)
if(verbose) cat("Reconstructing genotype-phenotypes networks done. \n")
}else{
if( method == "npn" ){
if(verbose)
{
m <- paste("Reconstructing genotype-phenotypes networks is in progress ... \n")
cat(m, "\r")
flush.console()
}
if((is.null(rho)) && (is.null(n.rho)) ) n.rho = 6
if(! is.null(rho)) n.rho = length(rho)
if(is.null(rho.ratio))
{
if( p <= 50) rho.ratio = 0.25 else rho.ratio = 0.3
}
if( any(is.na(data)) ) npn.func = "shrinkage" else npn.func = "skeptic"
tdata <- npn(data, npn.func= npn.func)
est <- huge(tdata, lambda= rho, nlambda=n.rho, lambda.min.ratio=rho.ratio, method="glasso", verbose=FALSE)
result$Theta = est$icov
result$path = est$path
result$rho = est$lambda
result$loglik = n/2 * (est$loglik)
result$data = data
rm(est)
if(verbose)
{
m <- paste("Reconstructing genotype-phenotype networks done. \n")
cat(m, "\r")
flush.console()
}
}
}
class(result) = "netgwas"
return(result)
}
plot.netgwas = function( x, n.markers=NULL , ...)
{
if(length(x$rho) == 1 ) par(mfrow = c(1, 2), pty = "s", omi=c(0.3,0.3,0.3,0.3), mai = c(0.3,0.3,0.3,0.3))
if(length(x$rho) == 2 ) par(mfrow = c(2, 2), pty = "s", omi=c(0.3,0.3,0.3,0.3), mai = c(0.3,0.3,0.3,0.3))
if(length(x$rho) >= 3 ) par(mfrow = c(2, ceiling(length(x$rho)/2)), pty = "s", omi=c(0.3,0.3,0.3,0.3), mai = c(0.3,0.3,0.3,0.3))
for(chain in 1:length(x$rho))
{
if(length(x$rho) == 1 ) image(as.matrix(x$path[[chain]]), col = gray.colors(256), xlab= "", ylab="" ,main=paste( "rho ", x$rho[chain], sep=""))
if(length(x$rho) == 2 ) image(as.matrix(x$path[[chain]]), col = gray.colors(256), xlab= "", ylab="" ,main=paste( "rho ", x$rho[chain], sep=""))
adj = graph.adjacency(as.matrix(x$path[[chain]]), mode="undirected", diag=FALSE)
if(is.null(n.markers))
{
memberships = 1
vertex.color = "red"
}else{
LG = length(n.markers)
memberships = NULL
i = 1
while( i <= LG){
grp <- rep(i, n.markers[i])
memberships = c(memberships, grp)
i = i + 1
}
if(chain == 1){
color = sample(terrain.colors(max(memberships) + 10), max(memberships))
cl = color[memberships]
}
vertex.color = cl
}
adj$layout = layout.fruchterman.reingold
plot(adj, vertex.color = vertex.color, edge.color='gray40', vertex.size = 7, vertex.label = NA , vertex.label.dist = NULL)
}
if(length(memberships) > 1) legend("bottomright", paste("group", 1:length(n.markers)), cex=0.7, col= color, pch=rep(20,10))
}
print.netgwas = function(x, ...){
cat("Estimated a graph path for", length(x$rho), "penalty term(s)" , "\n")
cat("Number of variables: p =", ncol(x$data), "\n")
cat("Number of sample size: n =", nrow(x$data), "\n")
sparsLevel <- sapply(1:length(x$rho), function(i) sum(x$Theta[[i]])/ncol(x$data)/(ncol(x$data)-1))
cat("Sparsity level for each graph in the path:", sparsLevel,"\n")
cat("To visualize the graph path consider plot() function \n")
cat("To SELECT an optimal graph consider selectnet() function \n")
}
|
sad <- function(object,
n,
show_original = FALSE,
show_contour = FALSE,
nrow = NULL,
ncol = NULL,
...){
patt <- object$parms$pattern
h <- object$parms$img_healthy
s <- object$parms$img_symptoms
b <- object$parms$img_background
dir <- object$parms$dir_original
dir_proc <- object$parms$dir_processed
save_image <- object$parms$save_image
nsamples <- n
measures <-
transform(object$severity,
rank = rank(symptomatic))
n <- nrow(measures)
seq <- trunc(seq(1, n, length.out = nsamples))
seq[c(1, length(seq))] <- c(1, n)
leaves <- measures[which(measures$rank %in% seq),]
leaves <- leaves[order(leaves$rank),]
leaves_name <- paste0("proc_", leaves$img, ".jpg")
if(isFALSE(save_image)){
if(is.null(patt) | is.null(h) | is.null(s)){
stop("'pattern', 'img_healthy', and 'img_symptoms' are mandatory arguments.")
}
td <- tempdir()
temp <-
measure_disease(pattern = patt,
img_healthy = h,
img_symptoms = s,
img_background = b,
dir_original = dir,
dir_processed = td,
show_original = show_original,
show_contour = FALSE,
save_image = TRUE,
parallel = TRUE,
verbose = FALSE,
...)
sads <- image_import(leaves_name, path = td)
image_combine(sads,
labels = paste0(round(leaves$symptomatic, 1), "%"),
ncol = ncol,
nrow = nrow)
} else{
sads <- image_import(leaves_name, path = dir_proc)
image_combine(sads,
labels = paste0(round(leaves$symptomatic, 1), "%"),
ncol = ncol,
nrow = nrow)
}
return(leaves)
}
|
utils::globalVariables(c("objFAMDshiny","myListOfThingsFAMDshiny"))
FAMDshiny <- function(X){
G <- .GlobalEnv
assign("objFAMDshiny",ls(all.names=TRUE, envir=G),envir=G)
assign("x",X, envir=G)
assign("nomData",sys.calls()[[1]][2], envir=G)
if (!(inherits(X, "FAMDshiny") | inherits(X, "data.frame") | inherits(X, "matrix") | inherits(X, "FAMD"))){
stop(gettext('X is not a dataframe, a matrix, the results of the FAMDshiny function or a FAMD result',domain="R-Factoshiny"))
}
if (is.matrix(X)==TRUE) X <- as.data.frame(X)
if(is.data.frame(X)==TRUE){
quanti=names(which(sapply(X,is.numeric)))
quali=names(which(!(sapply(X,is.numeric))))
if(length(quanti)==0 || length(quali)==0) stop(gettext('Your dataset is not mixed',domain="R-Factoshiny"))
}
outShiny <-shiny::runApp(system.file("FactoFAMDapp2", package="Factoshiny"),launch.browser = TRUE)
assign("myListOfThingsFAMDshiny",setdiff(ls(all.names=TRUE,envir=G),c("outShiny",objFAMDshiny)),envir=G)
rm(list=myListOfThingsFAMDshiny, envir=G)
rm(list=c("myListOfThingsFAMDshiny"),envir=G)
if (outShiny$hcpcparam==TRUE) resHCPC <- HCPCshiny(outShiny)
return(invisible(outShiny))
}
|
library(hamcrest)
he <- as.environment("package:hamcrest")
print(he)
assertFalse(is.null(attr(he, "path")))
library(utils)
print(.Library)
print(file.path(.Library, "base"))
print(packageDescription("base"))
si <- sessionInfo()
hamcrest <- si$otherPkgs$hamcrest
str(hamcrest)
assertFalse(is.null(hamcrest))
hv <- hamcrest$Version
assertTrue(compareVersion('0.0.0',hv) < 0)
|
angoff<-function(x, split.method="even.odd", missing="complete", standardize=FALSE){
n <- dim(x)[1]
p <- dim(x)[2]
sigma <- impute.cov(x, missing)
if(standardize==TRUE){
sigma <- cov2cor(sigma)
}
if(split.method[1]=="even.odd") t1t.split<-rep(c(1,0),ceiling(p/2))[1:p]
if(split.method[1]=="random") t1t.split<-round(runif(p))
if(split.method[1]=="evenly.random") t1t.split<-sample(rep(c(1,0),ceiling(p/2))[1:p])
if(split.method[1]==1 | split.method[1]==0) t1t.split<-split.method
if(length(t1t.split)!=p)
warning("The length of split is not the same as the number of items")
Split<-t1t.split
t1<-matrix(Split, ncol=1)
t1t<-t(t1)
t2<-(t1-1)*-1
t2t<-t(t2)
angoff<-4*(t1t%*%sigma%*%t2)/(sum(sigma)-((t1t%*%sigma%*%t1-t2t%*%sigma%*%t2)/sqrt(sum(sigma)))^2)
result<-list(angoff=angoff, Split=Split)
class(result)<-c("angoff")
return(result)
}
|
test_me <- function(x, y) {
if (TRUE) { x + y } else { 0 }
}
|
test.log_ss_ratio <- function() {
dataPath <- file.path(path.package(package="clusterCrit"),"unitTests","data","testsInternal_400_4.Rdata")
load(file=dataPath, envir=.GlobalEnv)
idx <- intCriteria(traj_400_4, part_400_4[[4]], c("Log_SS_Ratio"))
cat(paste("\nFound idx =",idx))
val <- 3.40114842491597
cat(paste("\nShould be =",val,"\n"))
checkEqualsNumeric(idx[[1]],val)
}
|
img.file <- file.path( R.home("doc"), "html", "logo.jpg" )
fpt_blue_bold <- fp_text(color = "
fpt_red_italic <- fp_text(color = "
value <- block_list(
fpar(ftext("hello world", fpt_blue_bold)),
fpar(ftext("hello", fpt_blue_bold), " ",
ftext("world", fpt_red_italic)),
fpar(
ftext("hello world", fpt_red_italic),
external_img(
src = img.file, height = 1.06, width = 1.39)))
value
doc <- read_docx()
doc <- body_add(doc, value)
print(doc, target = tempfile(fileext = ".docx"))
value <- block_list(
fpar(ftext("hello world", fpt_blue_bold)),
fpar(ftext("hello", fpt_blue_bold), " ",
ftext("world", fpt_red_italic)),
fpar(
ftext("blah blah blah", fpt_red_italic)))
value
doc <- read_pptx()
doc <- add_slide(doc)
doc <- ph_with(doc, value, location = ph_location_type(type = "body"))
print(doc, target = tempfile(fileext = ".pptx"))
|
`.form.data` <-
function (ordered.info, m, n, Xmat, XmatNames = NULL)
{
data <- data.frame(cbind(sort(rep(seq(1, n), m)),
rep(0, m * n), rep(ordered.info$obs.t, each = m), rep(seq(0, (m-1)), n),
rep(seq(0, (m-1)), n) + 1, Xmat))
if (is.null(XmatNames) == TRUE) {
XmatNames <- paste("X", seq(1, dim(Xmat)[2]), sep = "")
}
colnames(data) <- c("Id", "Event", "Fup", "Start", "Stop",
XmatNames)
data$Event[data$Stop == data$Fup & rep(ordered.info$d, each = m) ==
1] <- 1
data <- subset(data, data$Stop <= data$Fup)
}
`.partialHazards` <-
function (t, v, covArray, betas)
{
if (length(betas) > 1) {return(exp(covArray[v, t, ] %*% betas))} else {return(exp(covArray[v, t, ] * betas))}
}
`.PermuteCovariateVectors` <-
function (t, d, count, I, covArray, betas)
{
n = sum(count[I])
p <- integer(n)
v <- seq(n)
ip = 1
for (k in I) {
if (d[k]) {
J = sample(length(v), size = count[k], replace = FALSE, prob = .partialHazards(t[k], v, covArray, betas))
}
else {
J = sample(length(v), size = count[k], replace = FALSE,
prob = NULL)
}
p[seq(from = ip, along.with = J)] <- v[J]
ip <- ip + count[k]
v = v[-J]
}
return(p)
}
|
icc <- function(fit, obj.name) {
if (!requireNamespace("lme4", quietly = TRUE)) {
stop("Package `lme4` needed for this function to work. Please install it.",
call. = FALSE)
}
fitfam <- stats::family(fit)$family
is_negbin <- grepl(ignore.case = TRUE, pattern = "Negative Binomial",
x = fitfam)
reva <- lme4::VarCorr(fit)
vars <- lapply(reva, function(x) x[[1]])
tau.00 <- sapply(vars, function(x) x[1])
tau.11 <- unlist(lapply(reva, function(x) diag(x)[-1]))
if (inherits(fit, "glmerMod") && fitfam == "binomial") {
resid_var <- (pi ^ 2) / 3
} else if (inherits(fit, "glmerMod") && is_negbin) {
resid_var <- 0
} else {
resid_var <- attr(reva, "sc") ^ 2
}
total_var <- sum(sapply(vars, sum), resid_var)
if (is_negbin) {
beta <- as.numeric(lme4::fixef(fit)["(Intercept)"])
r <- lme4::getME(fit, "glmer.nb.theta")
ri.icc <-
(exp(tau.00) - 1) /
((exp(total_var) - 1) + (exp(total_var) / r)
+ exp(-beta - (total_var / 2)))
} else {
ri.icc <- tau.00 / total_var
}
has_rnd_slope <-
unlist(lapply(reva, function(x) dim(attr(x, "correlation"))[1] > 1))
tau.01 <- rho.01 <- NULL
if (any(has_rnd_slope)) {
rnd_slope <- reva[has_rnd_slope]
cor_ <- lapply(rnd_slope, function(x) attr(x, "correlation")[1, 2])
std_ <- lapply(rnd_slope, function(x) prod(attr(x, "stddev")))
tau.01 <- apply(as.matrix(cbind(unlist(cor_), unlist(std_))),
MARGIN = 1, FUN = prod)
rho.01 <- unlist(cor_)
}
names(ri.icc) <- names(reva)
class(ri.icc) <- c("icc.lme4", class(ri.icc))
attr(ri.icc, "family") <- stats::family(fit)$family
attr(ri.icc, "link") <- stats::family(fit)$link
attr(ri.icc, "formula") <- stats::formula(fit)
attr(ri.icc, "model") <- ifelse(inherits(fit, "glmerMod"),
"Generalized linear mixed model",
"Linear mixed model")
attr(ri.icc, "tau.00") <- tau.00
attr(ri.icc, "tau.01") <- tau.01
attr(ri.icc, "rho.01") <- rho.01
attr(ri.icc, "tau.11") <- tau.11
attr(ri.icc, "sigma_2") <- resid_var
return(ri.icc)
}
get_re_tables_mer <- function(model, re.variance, groups, ngroups, iccs) {
gvmat <- matrix(ncol = 3, nrow = length(ngroups))
colnames(gvmat) <- c("Group","
for (i in seq_len(length(ngroups))) {
gvmat[i,1] <- groups[i]
gvmat[i,2] <- ngroups[i]
gvmat[i,3] <- iccs[i]
}
rcmat <- as.data.frame(lme4::VarCorr(model))
rcmat <- rcmat[is.na(rcmat$var2),]
re_variance <- switch(re.variance, sd = "sdcor", var = "vcov")
re_var_lab <- switch(re.variance, sd = "Std. Dev.", var = "Var.")
rcmat <- rcmat[, names(rcmat) %in% c("grp", "var1", re_variance)]
rcmat <- as.matrix(rcmat)
colnames(rcmat) <- c("Group", "Parameter", re_var_lab)
attr(rcmat, "variance") <- re_var_lab
return(list(gvmat = gvmat, rcmat = rcmat))
}
pR2_merMod <- function(model) {
ret <- list()
if (any(class(model) %in% c("lmerMod", "lmerModLmerTest"))) {
varF <- var(as.vector(lme4::fixef(model) %*% t(model@pp$X)))
random.slopes <- if ("list" %in% class(lme4::ranef(model))) {
unique(as.vector(sapply(lme4::ranef(model), colnames)))
} else {
colnames(lme4::ranef(model))
}
n.obs <- names(
unlist(
lapply(
lme4::ranef(model), nrow))[!unlist(lapply(lme4::ranef(model), nrow)) ==
nrow(model@pp$X)]
)
varRand <- sum(
sapply(lme4::VarCorr(model)[n.obs], function(Sigma) {
X <- model.matrix(model)
Z <- X[, rownames(Sigma), drop = FALSE]
Z.m <- Z %*% Sigma
sum(diag(crossprod(Z.m, Z))) / nrow(X)
} )
)
varResid <- attr(lme4::VarCorr(model), "sc")^2
ret$Marginal <- varF / (varF + varRand + varResid)
ret$Conditional <- (varF + varRand) / (varF + varRand + varResid)
}
if (any(class(model) %in% c("glmerMod"))) {
ret$Family <- summary(model)$family
ret$Link <- summary(model)$link
varF <- var(as.vector(lme4::fixef(model) %*% t(model@pp$X)))
random.slopes <- if ("list" %in% class(lme4::ranef(model))) {
unique(as.vector(sapply(lme4::ranef(model), colnames)))
} else {
colnames(lme4::ranef(model))
}
n.obs <- names(
unlist(
lapply(
lme4::ranef(model), nrow)
)[!unlist(lapply(lme4::ranef(model), nrow)) == nrow(model@pp$X)]
)
varRand <- sum(
sapply(lme4::VarCorr(model)[n.obs], function(Sigma) {
X <- model.matrix(model)
Z <- X[, rownames(Sigma), drop = FALSE]
Z.m <- Z %*% Sigma
sum(diag(crossprod(Z.m, Z))) / nrow(X)
} )
)
obs <- names(
unlist(
lapply(
lme4::ranef(model), nrow))[unlist(
lapply(lme4::ranef(model), nrow)) == nrow(model@pp$X)]
)
if (length(obs) == 0) {
varDisp <- 0
} else {
varDisp <- sum(
sapply(lme4::VarCorr(model)[obs], function(Sigma) {
X <- model.matrix(model)
Z <- X[, rownames(Sigma)]
Z.m <- Z %*% Sigma
sum(diag(crossprod(Z.m, Z))) / nrow(X)
} )
)
}
if (ret$Family == "binomial") {
if (ret$Link == "logit") {
varDist <- (pi^2)/3
} else if (ret$Link == "probit") {
varDist <- 1
} else {
warning(paste("Model link '", summary(model)$link,
"' is not yet supported for the ",
summary(model)$family, "distribution"))
varDist <- NA
}
} else if (ret$Family == "poisson" | grepl("Negative Binomial", ret$Family)) {
null.model <-
update(model, formula = paste(". ~ ", get.random.formula(model, "~1")))
null.fixef <- as.numeric(lme4::fixef(null.model))
if (ret$Link == "log") {varDist <- log(1 + 1/exp(null.fixef))}
} else if (ret$Link == "sqrt") {
varDist <- 0.25
} else {
warning(paste("Model link '", summary(model)$link,
"' is not yet supported for the ",
summary(model)$family, "distribution"))
varDist <- NA
}
ret$Marginal <- varF / (varF + varRand + varDisp + varDist)
ret$Conditional <- (varF + varRand) / (varF + varRand + varDisp + varDist)
}
return(ret)
}
get.random.formula <- function(model, rhs) {
if (class(rhs) == "formula") {rhs <- Reduce(paste, deparse(rhs))}
random.formula <- if (any(class(model) %in% c("lmerMod", "lmerModLmerTest",
"glmerMod", "glmmTMB"))) {
paste("(", lme4::findbars(formula(model)), ")", collapse = " + ")
}
random.structure <- if (any(class(model) %in% c("lmerMod", "lmerModLmerTest",
"glmerMod", "glmmTMB"))) {
ran.ef.splt <- strsplit(random.formula, "\\+.")[[1]]
sapply(ran.ef.splt[sapply(ran.ef.splt, function(x) grepl("\\|", x))],
function(x)
gsub(" ", "", gsub(".*\\|(.*)\\)", "\\1", x))
)
}
random.structure <- unname(random.structure[!duplicated(random.structure)])
random.slopes <- if (any(class(model) %in% c("glmerMod", "lmerModLmerTest",
"glmmTMB"))) {
ran.ef <- ifelse(any(class(lme4::ranef(model)) != "list"),
list(lme4::ranef(model)),
lme4::ranef(model))
as.vector(sapply(ran.ef, function(x) colnames(x)))
}
random.slopes <- unname(random.slopes[!duplicated(random.slopes) &
random.slopes != "(Intercept)"])
new.random.slopes <- random.slopes[which(random.slopes %in%
unlist(strsplit(rhs, ".\\+.")))]
if (length(new.random.slopes) == 0) {
new.random.slopes <- 1
} else {
new.random.slopes <- paste0(new.random.slopes, collapse = " + ")
}
if (length(random.slopes) != 0) {
if (any(class(model) %in% c("glmerMod", "lmerModLmerTest", "glmmTMB"))) {
paste(
sapply(random.structure, function(x)
paste("(", new.random.slopes, " | ", x, ")") ),
collapse = " + ")
}
} else if (length(random.slopes) == 0) {
if (is.list(random.structure)) {
eval(parse(text = gsub("*\\~(.*)", paste0("~ ", new.random.slopes, "))"),
random.formula)))
} else {
random.formula
}
}
}
get_df_kr <- function(model) {
L <- diag(rep(1, length(lme4::fixef(model))))
L <- as.data.frame(L)
dfs <- sapply(L, pbkrtest::get_Lb_ddf, object = model)
names(dfs) <- names(lme4::fixef(model))
return(dfs)
}
get_se_kr <- function(model) {
vcov_adj <- pbkrtest::vcovAdj(model)
fes <- lme4::fixef(model)
len <- length(fes)
Lmat <- diag(len)
qform <- function(x, A) sum(x * (A %*% x))
ses <- sapply(1:len, function(.x) {
sqrt(qform(Lmat[.x, ], as.matrix(vcov_adj)))
})
names(ses) <- names(fes)
return(ses)
}
get_all_sat <- function(model) {
if ("lmerModLmerTest" %nin% class(model)) {
new_mod <- lmerTest::as_lmerModLmerTest(model)
} else {new_mod <- model}
coefs <- summary(new_mod)$coefficients
return(coefs)
}
predict_merMod <- function(object, newdata = NULL, se.fit = FALSE,
use.re.var = FALSE, allow.new.levels = FALSE,
type = c("link", "response", "terms"),
na.action = na.pass, re.form = NULL,
boot = FALSE, sims = 100, prog.arg = "none", ...) {
type <- match.arg(type, c("link", "response", "terms"))
if (is.null(newdata) & is.null(re.form)) {
if (lme4::isLMM(object) || lme4::isNLMM(object)) {
fit <- na.omit(fitted(object))
} else {
fit <- switch(type, response = object@resp$mu,
link = object@resp$eta)
if (is.null(nm <- rownames(model.frame(object)))) {
nm <- seq_along(fit)
}
names(fit) <- nm
}
fit.na.action <- NULL
X <- lme4::getME(object, "X")
X.col.dropped <- attr(X, "col.dropped")
} else {
fit.na.action <- attr(object@frame, "na.action")
nobs <- if (is.null(newdata)) nrow(object@frame) else nrow(newdata)
fit <- rep(0,nobs)
X <- lme4::getME(object, "X")
X.col.dropped <- attr(X, "col.dropped")
if (is.null(newdata)) {
offset <- model.offset(model.frame(object))
if (is.null(offset)) offset <- 0
} else {
RHS <- formula(substitute(~R,
list(R = RHSForm(formula(object,
fixed.only = TRUE)))))
Terms <- terms(object, fixed.only = TRUE)
mf <- model.frame(object, fixed.only = TRUE)
isFac <- vapply(mf, is.factor, FUN.VALUE = TRUE)
isFac[attr(Terms,"response")] <- FALSE
orig_levs <- if (length(isFac) == 0) NULL else lapply(mf[isFac], levels)
mfnew <- suppressWarnings(
model.frame(delete.response(Terms), newdata,
na.action = na.action, xlev = orig_levs))
X <- model.matrix(RHS, data = mfnew,
contrasts.arg = attr(X,"contrasts"))
offset <- 0
tt <- terms(object)
if (!is.null(off.num <- attr(tt, "offset"))) {
for (i in off.num)
offset <- offset + eval(attr(tt,"variables")[[i + 1]], newdata)
}
fit.na.action <- attr(mfnew, "na.action")
if (is.numeric(X.col.dropped) && length(X.col.dropped) > 0) {
X <- X[, -X.col.dropped, drop = FALSE]
}
fit <- drop(X %*% lme4::fixef(object))
fit <- fit + offset
}
}
if (se.fit == TRUE & boot == FALSE) {
.vcov <- as.matrix(vcov(object))
fit.ses <- sqrt(diag(X %*% .vcov %*% t(X)))
if (lme4::isGLMM(object)) {
switch(type, response = {
fit.ses <- fit.ses * abs(family(object)$mu.eta(fit))
fit <- object@resp$family$linkinv(fit)
}, link = , terms = )
} else {
fit.ses <- fit.ses * abs(family(object)$mu.eta(fit))
}
re_vcov <- lme4::VarCorr(object)
re_variances <- sum(sapply(re_vcov, function(x) {x[1]}))
if (use.re.var == TRUE) {
fit.ses <- fit.ses + re_variances
}
} else if (se.fit == TRUE & boot == TRUE) {
bootfun <- function(object) {
drop( X %*% lme4::fixef(object) )
}
bo <- lme4::bootMer(object, FUN = bootfun, nsim = sims,
.progress = prog.arg, ...)
fit <- bo$t
if (lme4::isGLMM(object)) {
switch(type, response = {
fit <- object@resp$family$linkinv(fit)
}, link = , terms = )
}
}
if (!noReForm(re.form)) {
if (is.null(re.form))
re.form <- reOnly(formula(object))
rfd <- if (is.null(newdata)) {object@frame} else {newdata}
newRE <- mkNewReTrms(object, rfd, re.form, na.action = na.action,
allow.new.levels = allow.new.levels)
REvals <- base::drop(methods::as(newRE$b %*% newRE$Zt, "matrix"))
fit <- fit + REvals
}
if (se.fit == FALSE & lme4::isGLMM(object)) {
switch(type, response = {
fit <- object@resp$family$linkinv(fit)
}, link = , terms = )
}
if (se.fit == TRUE & boot == FALSE) {
return(list(fit = fit, se.fit = fit.ses))
} else if (se.fit == TRUE & boot == TRUE) {
return(list(fit = fit))
} else {
return(fit)
}
}
predict_mer <- function(object, use_re_var = FALSE, prog_arg = "none", ...) {
predict_merMod(object, use.re.var = use_re_var, prog.arg = prog_arg, ...)
}
noReForm <- function(re.form) {
(!is.null(re.form) && !methods::is(re.form, "formula") && is.na(re.form)) ||
(methods::is(re.form, "formula") && length(re.form) == 2 &&
identical(re.form[[2]], 0))
}
reOnly <- function(f, response = FALSE) {
response <- if (response && length(f) == 3) { f[[2]] } else { NULL }
reformulate(paste0("(", vapply(lme4::findbars(f), safeDeparse,
""), ")"), response = response)
}
safeDeparse <- function (x, collapse = " ") {
paste(deparse(x, 500L), collapse = collapse)
}
mkNewReTrms <- function(object, newdata, re.form = NULL, na.action = na.pass,
allow.new.levels = FALSE) {
Lind <- NULL
if (is.null(newdata)) {
rfd <- mfnew <- model.frame(object)
}
else {
mfnew <- model.frame(delete.response(terms(object, fixed.only = TRUE)),
newdata, na.action = na.action)
old <- FALSE
if (old) {
rfd <- na.action(newdata)
if (is.null(attr(rfd, "na.action")))
attr(rfd, "na.action") <- na.action
}
else {
newdata.NA <- newdata
if (!is.null(fixed.na.action <- attr(mfnew, "na.action"))) {
newdata.NA <- newdata.NA[-fixed.na.action, ]
}
tt <- delete.response(terms(object, random.only = TRUE))
rfd <- model.frame(tt, newdata.NA, na.action = na.pass)
if (!is.null(fixed.na.action))
attr(rfd, "na.action") <- fixed.na.action
}
}
if (inherits(re.form, "formula")) {
if (length(fit.na.action <- attr(mfnew, "na.action")) >
0) {
newdata <- newdata[-fit.na.action, ]
}
ReTrms <- lme4::mkReTrms(lme4::findbars(re.form[[2]]), rfd)
ReTrms <- within(ReTrms, Lambdat@x <- unname(lme4::getME(object,
"theta")[Lind]))
if (!allow.new.levels && any(vapply(ReTrms$flist, anyNA,
NA)))
stop("NAs are not allowed in prediction data",
" for grouping variables unless allow.new.levels is TRUE")
ns.re <- names(re <- lme4::ranef(object))
nRnms <- names(Rcnms <- ReTrms$cnms)
if (!all(nRnms %in% ns.re))
stop("grouping factors specified in re.form that were not present in original model")
new_levels <- lapply(ReTrms$flist, function(x) levels(factor(x)))
re_x <- Map(function(r, n) levelfun(r, n, allow.new.levels = allow.new.levels),
re[names(new_levels)], new_levels)
re_new <- lapply(seq_along(nRnms), function(i) {
rname <- nRnms[i]
if (!all(Rcnms[[i]] %in% names(re[[rname]])))
stop("random effects specified in re.form that were not present in original model")
re_x[[rname]][, Rcnms[[i]]]
})
re_new <- unlist(lapply(re_new, t))
}
Zt <- ReTrms$Zt
attr(Zt, "na.action") <- attr(re_new, "na.action") <- attr(mfnew,
"na.action")
list(Zt = Zt, b = re_new, Lambdat = ReTrms$Lambdat)
}
levelfun <- function(x, nl.n, allow.new.levels = FALSE) {
if (!all(nl.n %in% rownames(x))) {
if (!allow.new.levels)
stop("new levels detected in newdata")
newx <- as.data.frame(
matrix(0, nrow = length(nl.n), ncol = ncol(x),
dimnames = list(nl.n, names(x)))
)
newx[rownames(x), ] <- x
x <- newx
}
if (!all(r.inn <- rownames(x) %in% nl.n)) {
x <- x[r.inn, , drop = FALSE]
}
return(x)
}
RHSForm <- function (form, as.form = FALSE) {
rhsf <- form[[length(form)]]
if (as.form)
reformulate(deparse(rhsf))
else rhsf
}
|
testthat::test_that("Kappa: 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(Kappa$new(performance = confMatrix),
"Kappa")
})
testthat::test_that("Kappa: 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(Kappa$new(performance = confMatrix)$compute(performance.output = NULL),
"numeric")
testthat::expect_is(Kappa$new(performance = NULL)$compute(performance.output = confMatrix),
"numeric")
})
testthat::test_that("Kappa: compute function checks parameter type", {
testthat::expect_error(Kappa$new(performance = NULL)$compute(performance.output = NULL),
"[Kappa][FATAL] Performance output parameter must be defined as 'MinResult' or 'ConfMatrix' type. Aborting...",
fixed = TRUE)
})
|
PayoffMatrix_QHawkDove <- function(moves, v, j, D){
Alice <- matrix(0, 2, 2)
Bob <- matrix(0, 2, 2)
for(i in 1:2){
for (j in 1:2){
X <- QHawkDove(i-1, j-1, moves, v, j, D)
Alice[i, j] <- X[[1]]
Bob[i, j] <- X[[2]]
}
}
return(list(Alice, Bob))
}
|
erase <- function(pattern = NULL, envir = parent.frame(), verbose = FALSE){
.abstract_erase(pattern = pattern, filtering.function = NULL, list.function = ls,
envir = envir, verbose = verbose)
}
erase_if <- function(condition, pattern = NULL, envir = parent.frame(), verbose = FALSE){
condition <- as_function(condition)
filtering_function <- function(x){
condition(get(x, envir = envir))
}
.abstract_erase(filtering.function = filtering_function,
list.function = ls, envir = envir, verbose = verbose)
}
|
findfrequency <- function(x) {
n <- length(x)
x <- as.ts(x)
x <- residuals(tslm(x ~ trend))
n.freq <- 500
spec <- spec.ar(c(na.contiguous(x)), plot = FALSE, n.freq = n.freq)
if (max(spec$spec) > 10)
{
period <- floor(1 / spec$freq[which.max(spec$spec)] + 0.5)
if (period == Inf)
{
j <- which(diff(spec$spec) > 0)
if (length(j) > 0) {
nextmax <- j[1] + which.max(spec$spec[(j[1] + 1):n.freq])
if (nextmax < length(spec$freq)) {
period <- floor(1 / spec$freq[nextmax] + 0.5)
} else {
period <- 1L
}
}
else {
period <- 1L
}
}
}
else {
period <- 1L
}
return(as.integer(period))
}
|
dieharderGenerators <- function() {
val <- .Call("dieharderGenerators", PACKAGE="RDieHarder")
return(data.frame(names=val[[1]], id=val[[2]]))
}
dieharderTests <- function() {
val <- .Call("dieharderTests", PACKAGE="RDieHarder")
return(data.frame(names=val[[1]], id=val[[2]]))
}
dieharder <- function(rng="mt19937",
test=1,
psamples=100,
seed=0,
verbose=FALSE,
inputfile="",
ntuple=5) {
UseMethod("dieharder")
}
dieharder.default <- function(rng="mt19937",
test="diehard_runs",
psamples=100,
seed=0,
verbose=FALSE,
inputfile="",
ntuple=5) {
if (length(rng) > 1) {
warning("Only one rng argument supported in dieharder")
return(NULL)
}
if (is.character(rng)) {
genpos <- charmatch(rng, as.character(.dieharder.generators$names))
} else {
genpos = which(.dieharder.generators[,"id"] == rng)
}
if (length(genpos)==0 || is.na(genpos)) {
warning("rng argument ", rng, " unknown")
return(NULL)
}
if (genpos == 0 && rng != 1) {
warning("rng argument ", rng, " ambiguous")
return(NULL)
}
gen <- .dieharder.generators$id[genpos]
if (length(test) > 1) {
warning("Only one test argument supported in dieharder")
return(NULL)
}
if (is.character(test)) {
runtestpos <- charmatch(test, as.character(.dieharder.tests$names))
if (is.na(runtestpos)) {
warning("test argumement ", test, " unknown")
return(NULL)
}
if (runtestpos == 0) {
warning("test argumment ", test, " ambiguous")
return(NULL)
}
runtest <- .dieharder.tests$id[runtestpos]
} else {
runtest <- test
}
val <- .Call("dieharder",
as.integer(gen),
as.integer(runtest),
as.integer(seed),
as.integer(psamples),
as.integer(verbose),
as.character(inputfile),
as.integer(ntuple),
PACKAGE="RDieHarder")
obj <- list(p.value=val[[1]][1],
data=val[[2]],
method=val[[3]],
data.name=paste("Created by RNG `",
.dieharder.generators[genpos,"names"], "' with seed=",
as.integer(seed), ", sample of size ",
as.integer(psamples), sep=""),
generator=as.character(.dieharder.generators[genpos,"names"]),
nvalues=val[[4]],
p.values=val[[1]]
)
class(obj) <- c("dieharder", "htest")
return(obj)
}
plot.dieharder <- function(x, ...) {
local.par <- par(mfrow=c(2,1), mar=c(2,4,3,1), oma=c(0,0,3.5,0))
vec <- x$data
hist(vec, probability=TRUE, main="Histogram and Density estimate",
xlab="", ylab="density")
lines(density(x$data, from=0, to=1), col='darkgray')
plot(ecdf(x$data), main="ECDF", ylab="", xlab="",
verticals= TRUE, do.p = FALSE)
segments(0,0,1,1, col='darkgray', lty="dotted")
mtext(text = x$method, outer = TRUE, cex = 1.2, font = 2, line = 2)
mtext(text = x$data.name, outer = TRUE, cex = 1.0, font = 1, line = 1)
pksk <- round(x$p.value, 4)
pks <- round(ks.test(x$data, "punif", 0, 1, exact=TRUE)$p.value, 4)
pw <- round(wilcox.test(x$data, mu=0.5)$p.value, 4)
mtext(text = paste("Test p-values: ",
pksk, " (Kuiper-K-S), ",
pks, " (K-S), ",
pw, " (Wilcoxon)"),
outer = TRUE, cex = 1.0, font = 1, line = 0)
par(local.par)
invisible(x)
}
print.dieharder <- function(x, ...) {
z <- x
class(z) <- "htest"
print(z)
invisible(x)
}
summary.dieharder <- function(object, ...) {
print(object, ...)
cat("\nSummary for test data\n")
print(summary(object$data))
if (any(!is.na(object$data))) {
cat("\n\nStem and leaf plot for test data\n")
print(stem(object$data))
print(ks.test(object$data, "punif", 0, 1, exact=TRUE))
print(wilcox.test(object$data, mu=0.5))
}
invisible(object)
}
|
cluster.im.glm<-function(mod, dat, cluster, ci.level = 0.95, report = TRUE, drop = FALSE, truncate = FALSE, return.vcv = FALSE){
form <- mod$formula
variables <- all.vars(form)
clust.name <- all.vars(cluster)
used.idx <- which(rownames(dat) %in% rownames(mod$model))
dat <- dat[used.idx,]
clust <- as.vector(unlist(dat[[clust.name]]))
G<-length(unique(clust))
ind.variables.full <- names(coefficients(mod))
ind.variables <- rownames(summary(mod)$coefficients)
b.clust <- matrix(data = NA, nrow = G, ncol = length(ind.variables))
n.clust <- c()
G.o <- G
for(i in 1:G){
clust.ind <- which(clust == unique(clust)[i])
clust.dat <- dat[clust.ind,]
clust.mod <- suppressWarnings(tryCatch(glm(form, data = clust.dat, family = mod$family),
error = function(e){return(NULL)}))
if(is.null(clust.mod) == FALSE ){
if(clust.mod$converged == 0){clust.mod <- NULL}
}
fail <- is.null(clust.mod)
if(drop==FALSE){
if(fail == T){stop("cluster-specific model returned error (try drop = TRUE)", call.=FALSE)}
if(length(rownames(summary(clust.mod)$coefficients)) != length(ind.variables)){
stop("cluster-specific model(s) dropped variables; ensure that all variables vary within clusters", call.=FALSE)
}
b.clust[i,] <- coefficients(clust.mod)[ind.variables]
}else{
if(fail == F){
if(length(rownames(summary(clust.mod)$coefficients)) != length(ind.variables)){
stop("cluster-specific model(s) dropped variables; ensure that all variables vary within clusters", call.=FALSE)
}
b.clust[i,] <- coefficients(clust.mod)[ind.variables]
}else{
b.clust[i,] <- NA
}
}
}
if(drop==TRUE){
dropped.nc <- 0
b.clust <- na.omit(b.clust)
dropped.nc <- length(attr(b.clust, "na.action"))
G.t <- dim(b.clust)[1]
if(G.t == 0){stop("all clusters were dropped (see help file).")}
}
dropped <- 0
if(truncate==TRUE){
IQR <- apply(FUN=quantile, MARGIN=2, X=b.clust, probs=c(0.25, 0.75))
b.clust.save <- b.clust
for(i in 1:dim(b.clust)[2]){
b.clust.save[,i] <- ifelse( abs(b.clust[,i]) >
(abs(mean(b.clust[,i])) + 6*abs(IQR[2,i] - IQR[1,i])), 0, 1)
}
save.clust <- apply(X=b.clust.save, MARGIN=1, FUN=min)
dropped <- dim(b.clust)[1] - sum(save.clust)
b.clust.adj <- cbind(b.clust, save.clust)
b.clust <- subset(b.clust,
subset=(save.clust==1), select=1:dim(b.clust)[2])
}
G <- dim(b.clust)[1]
if(G == 0){stop("all clusters were dropped (see help file).")}
b.hat <- colMeans(b.clust)
b.dev <- sweep(b.clust, MARGIN = 2, STATS = b.hat)
vcv.hat <- cov(b.dev)
rownames(vcv.hat) <- ind.variables
colnames(vcv.hat) <- ind.variables
s.hat <- sqrt(diag(vcv.hat))
t.hat <- sqrt(G) * (b.hat / s.hat)
names(b.hat) <- ind.variables
p.out <- 2*pmin( pt(t.hat, df = G-1, lower.tail = TRUE), pt(t.hat, df = G-1, lower.tail = FALSE) )
ci.lo <- b.hat - qt((1-ci.level)/2, df=(G-1), lower.tail=FALSE)*(s.hat/sqrt(G))
ci.hi <- b.hat + qt((1-ci.level)/2, df=(G-1), lower.tail=FALSE)*(s.hat/sqrt(G))
out <- matrix(p.out, ncol=1)
rownames(out) <- ind.variables
out.p <- cbind( ind.variables, round(out, 3))
out.p <- rbind(c("variable name", "cluster-adjusted p-value"), out.p)
out.ci <- cbind(ci.lo, ci.hi)
rownames(out.ci) <- ind.variables
colnames(out.ci) <- c("CI lower", "CI higher")
print.ci <- cbind(ind.variables, ci.lo, ci.hi)
print.ci <- rbind(c("variable name", "CI lower", "CI higher"), print.ci)
printmat <- function(m){
write.table(format(m, justify="right"), row.names=F, col.names=F, quote=F, sep = " ")
}
if(report==T){
cat("\n", "Cluster-Adjusted p-values: ", "\n", "\n")
printmat(out.p)
cat("\n", "Confidence Intervals (centered on cluster-averaged results):", "\n", "\n")
printmat(print.ci)
if(G.o > G){
cat("\n", "Note:", G.o - G, "clusters were dropped (see help file).", "\n", "\n")
}
if(length(ind.variables) < length(ind.variables.full)){
cat("\n", "\n", "****", "Note: ", length(ind.variables.full) - length(ind.variables), " variables were unidentified in the model and are not reported.", "****", "\n", sep="")
cat("Variables not reported:", "\n", sep="")
cat(ind.variables.full[!ind.variables.full %in% ind.variables], sep=", ")
cat("\n", "\n")
}
}
out.list<-list()
out.list[["p.values"]] <- out
out.list[["ci"]] <- out.ci
if(return.vcv == TRUE){out.list[["vcv.hat"]] <- vcv.hat}
if(return.vcv == TRUE){out.list[["beta.bar"]] <- b.hat}
return(invisible(out.list))
}
|
calculate_EM_approx = function(chain, y, Z, rho, Sigma, Theta, lower_upper, em_tol, em_iter, ncores=4, verbose=FALSE )
{
c_em_iter = 1
dif <- 100
p <- ncol(y)
n <- nrow(y)
s <- proc.time()
while((c_em_iter < em_iter) && (dif >= em_tol ))
{
S_obj <- calculate.R.approx.internal(y=y, Z=Z, lower_upper=lower_upper, Sigma= Sigma, ncores=ncores)
Z <- S_obj$Z
S_gl <- glasso(s=S_obj$ES, rho=rho, maxit=1000, penalize.diagonal=FALSE)
Theta <- (t(S_gl$wi) + S_gl$wi) / 2
Sigma_new <- (t(S_gl$w) + S_gl$w) / 2
sd_marginal <- sqrt(diag(Sigma_new))
sd_marginal[abs(sd_marginal) < 1e-10] <- 1e-10
Sigma_new <- diag(1/sd_marginal) %*% Sigma_new %*% diag(1/sd_marginal)
Theta <- Matrix(diag(sd_marginal) %*% Theta %*% diag(sd_marginal))
dif <- sum(abs(Sigma_new - Sigma)/p^2)
Sigma <- Sigma_new
c_em_iter <- c_em_iter + 1
rm(Sigma_new, sd_marginal, S_gl)
gc()
}
results <- list()
results$Theta <- Theta
results$Sigma <- Sigma
results$ES <- S_obj$ES
results$Z <- Z
results$rho <- rho
results$loglik <- n/2 *(determinant(results$Theta, logarithm = TRUE)$modulus - sum(diag(results$ES %*%results$Theta)))
return(results)
}
|
load(file = "helper_data.rda")
dfSAV <- import_spss(file = "helper_spss_missings.sav")
test_that("errors", {
expect_error(compareGADS(df1, df1, varNames = "other"),
"The following 'vars' are not variables in the GADSdat: other")
})
test_that("standard functionality", {
df1_b <- df1
df1_b$dat[, 2] <- c(9, 9)
out <- compareGADS(df1, df1_b, varNames = namesGADS(df1))
expect_equal(out[[1]], "all equal")
expect_equal(out[[2]], data.frame(value = c("3", "5"), frequency = c(1, 1),
valLabel = c(NA, NA), missings = c(NA, NA),
stringsAsFactors = FALSE))
dfSAV_b <- dfSAV
dfSAV_b$dat[, 1] <- c(9, 9, 9, 9)
dfSAV_b$dat[, 3] <- c(9, 9, 9, 9)
out2 <- compareGADS(dfSAV, dfSAV_b, varNames = namesGADS(dfSAV))
expect_equal(out2[["VAR1"]], data.frame(value = c("-99", "-96", "1", "2"), frequency = rep(1, 4),
valLabel = c("By design", "Omission", "One", NA),
missings = c("miss", "miss", "valid", NA),
stringsAsFactors = FALSE))
expect_equal(out2[["VAR2"]], "all equal")
expect_equal(out2[[3]], data.frame(value = c("-98", "1"), frequency = c(1, 3),
valLabel = NA_character_, missings = c("miss", NA),
stringsAsFactors = FALSE))
})
test_that("with character variable", {
iris_char <- iris
iris_char$Species <- as.character(iris_char$Species)
suppressMessages(iris2 <- iris1 <- import_DF(iris_char))
iris2$dat[c(1, 51, 52), 5] <- c(9, "test", "x")
expect_silent(out <- compareGADS(iris1, iris2, varNames = namesGADS(iris1)))
expect_equal(out[[1]], "all equal")
expect_equal(out[[4]], "all equal")
expect_equal(out[[5]], data.frame(value = c("setosa", "versicolor"), frequency = c(1, 2),
valLabel = c(NA, NA), missings = c(NA, NA),
stringsAsFactors = FALSE))
})
test_that("recodes in NA", {
df1_c <- df1_b <- df1
df1_b$dat[, 2] <- c(NA, NA)
df1_c$dat[, 2] <- c(9, 9)
out <- compareGADS(df1_b, df1_c, varNames = namesGADS(df1))
expect_equal(out[[1]], "all equal")
expect_equal(out[[2]], data.frame(value = c(NA_character_), frequency = c(2),
valLabel = c(NA_character_), missings = c(NA_character_),
stringsAsFactors = FALSE))
df1_c <- df1_b <- df1
df1_c$dat[, 2] <- c(NA, NA)
df1_b$dat[, 2] <- c(9, 9)
out2 <- compareGADS(df1_b, df1_c, varNames = namesGADS(df1))
expect_equal(out2[[1]], "all equal")
expect_equal(out2[[2]], data.frame(value = c("9"), frequency = c(2),
valLabel = c(NA), missings = c(NA),
stringsAsFactors = FALSE))
})
test_that("recodes in NA with labeled NAs", {
dfSAV2 <- dfSAV
dfSAV2$labels[c(1, 4:5), "value"] <- NA
dfSAV3 <- dfSAV2
dfSAV2$dat[1:2, 1] <- NA
dfSAV2$dat[4, 1] <- 1
expect_silent(out3 <- compareGADS(dfSAV2, dfSAV3, varNames = namesGADS(dfSAV3)))
expect_equal(out3[[2]], "all equal")
expect_equal(out3[["VAR1"]]$value, c("1", NA))
expect_equal(out3[["VAR1"]]$frequency, c(1, 2))
expect_equal(out3[["VAR1"]]$missings, c("valid", "miss"))
dfSAV4 <- dfSAV
dfSAV4$dat[1:2, 1] <- NA
dfSAV4$labels[c(1:2, 4:5), "value"] <- NA
dfSAV5 <- dfSAV4
dfSAV5$dat[1:2, 1] <- -99
expect_error(out4 <- compareGADS(dfSAV4, dfSAV5, varNames = namesGADS(dfSAV5)),
"Meta information on value level is not unique for variable: VAR1 and value: NA")
dfSAV4 <- dfSAV
dfSAV4$dat[1:2, 1] <- -99
dfSAV4$labels[c(1:2, 4:5), "value"] <- NA
dfSAV5 <- dfSAV4
dfSAV5$dat[1:2, 1] <- NA
expect_silent(out5 <- compareGADS(dfSAV4, dfSAV5, varNames = namesGADS(dfSAV5)))
expect_equal(out5[[2]], "all equal")
expect_equal(out5[["VAR1"]], data.frame(value = "-99", frequency = 2, valLabel = NA, missings = NA,
stringsAsFactors = FALSE))
})
test_that("Compare GADS data.frame and aggregate output", {
dfSAV2 <- dfSAV
dfSAV2$dat[1, 2:3] <- -96
dfSAV2$labels[4, "missings"] <- "miss"
dfSAV2$labels[c(4, 6), "value"] <- -96
dfSAV_b <- dfSAV2
dfSAV_b$dat[, 2] <- c(9, 9, 9, 9)
dfSAV_b$dat[, 3] <- c(9, 9, 9, 9)
out2 <- compareGADS(dfSAV2, dfSAV_b, varNames = namesGADS(dfSAV), output = "data.frame")
expect_equal(out2, data.frame(variable = c(rep("VAR2", 2), rep("VAR3", 3)),
value = c("-96", "1", "-98", "-96", "1"), frequency = c(1, 3, 1, 1, 2),
valLabel = c("missing", NA, NA, "missing", NA),
missings = c("miss", NA, "miss", "miss", NA),
stringsAsFactors = FALSE))
out3 <- compareGADS(dfSAV2, dfSAV_b, varNames = namesGADS(dfSAV), output = "aggregated")
expect_equal(out3, data.frame(value = c("-96", "1", "-98"),
valLabel = c("missing", NA, NA),
missings = c("miss", NA, "miss"),
stringsAsFactors = FALSE))
})
test_that("data.frame and aggregate output with all equals", {
dfSAV2 <- dfSAV
out2 <- compareGADS(dfSAV2, dfSAV, varNames = namesGADS(dfSAV), output = "data.frame")
expect_equal(out2, "all equal")
out3 <- compareGADS(dfSAV2, dfSAV, varNames = namesGADS(dfSAV), output = "aggregated")
expect_equal(out3, "all equal")
})
|
style <- function(string, as = NULL, bg = NULL) {
as <- use_or_make_style(as)
bg <- use_or_make_style(bg, bg = TRUE)
if (!is(as, "crayon")) stop("Cannot make style from 'as'")
if (!is(bg, "crayon")) stop("Cannot make style from 'bg'")
as(bg(string))
}
use_or_make_style <- function(style, bg = FALSE) {
if (is.null(style)) {
structure(base::identity, class = "crayon")
} else if (is(style, "crayon")) {
style
} else if (style %in% names(styles())) {
make_crayon(styles()[style])
} else {
make_style(style, bg = bg)
}
}
|
print.aov.ltm <-
function (x, digits = 3, ...) {
if (!inherits(x, "aov.ltm"))
stop("Use only with 'aov.ltm' objects.\n")
p.val <- round(x$p.value, 3)
p.val <- if (p.val < 0.001) "<0.001" else p.val
dat <- data.frame(AIC = round(c(x$aic0, x$aic1), 2), BIC = round(c(x$bic0, x$bic1), 2),
log.Lik = round(c(x$L0, x$L1), 2), LRT = c(" ", round(x$LRT, 2)), df = c("", x$df),
p.value = c("", p.val), row.names = c(x$nam0, x$nam1))
cat("\n Likelihood Ratio Table\n")
print(dat)
cat("\n")
invisible(x)
}
|
expected <- eval(parse(text="\"Inf\""));
test(id=0, code={
argv <- eval(parse(text="list(Inf)"));
do.call(`as.character`, argv);
}, o=expected);
|
context("pitch")
test_that("pitch_seq returns as expected", {
expect_equal(pitch_seq("a,", 13),
as_noteworthy("a, b_, b, c d_ d e_ e f g_ g a_ a"))
expect_equal(pitch_seq("c5", -2), as_noteworthy("c5 b4"))
expect_equal(pitch_seq("c", "b"),
as_noteworthy("c d_ d e_ e f g_ g a_ a b_ b"))
x <- pitch_seq("c", 8, key = "c")
expect_equal(x, as_noteworthy("c d e f g a b c'"))
expect_equal(pitch_seq("c", 8, "am"), x)
expect_equal(
pitch_seq("c
as_noteworthy("d, e, f, g, a, b, c d e f g a b c' d' e' f' g' a'")
)
expect_equal(pitch_seq("a", 8, "am", "harmonic minor"),
as_noteworthy("a b c' d' e' f' g
expect_equal(pitch_seq("a'", -2), as_noteworthy("a' a_'"))
expect_equal(pitch_seq("a'", -8, key = "a"),
as_noteworthy("a' g
expect_error(pitch_seq(c("a", "b")), "`x` must be a single pitch.")
expect_error(pitch_seq("a", 0), "Cannot have zero timesteps.")
expect_error(pitch_seq("a", 1:2),
"`y` must be a single pitch or single number.")
expect_error(pitch_seq("b,,,,,", 1),
"Pitch semitones must range from 0 to 131.")
expect_error(pitch_seq("a'", -71), "Semitones must range from 0 to 131.")
expect_error(pitch_seq("a'", "b,,,,,"),
"Pitch semitones must range from 0 to 131.")
})
|
library("aroma.affymetrix")
log <- verbose <- Arguments$getVerbose(-8, timestamp=TRUE)
dataSetName <- "Affymetrix_2006-TumorNormal"
tags <- "ACC,-XY,BPN,-XY,RMA,FLN,-XY"
chipType <- "Mapping250K_Nsp"
pairs <- matrix(c(
"CRL-2325D", "CRL-2324D",
"CRL-5957D", "CRL-5868D",
"CCL-256.1D", "CCL-256D",
"CRL-2319D", "CRL-2320D",
"CRL-2362D", "CRL-2321D",
"CRL-2337D", "CRL-2336D",
"CRL-2339D", "CRL-2338D",
"CRL-2341D", "CRL-2340D",
"CRL-2346D", "CRL-2314D"
), ncol=2, byrow=TRUE)
colnames(pairs) <- c("normal", "tumor")
if (!exists("cesN")) {
cdf <- AffymetrixCdfFile$byName(chipType)
gi <- getGenomeInformation(cdf)
cdfM <- getMonocellCdf(cdf)
cesN <- SnpChipEffectSet$byName(dataSetName, tags=tags, cdf=cdfM)
print(cesN)
cesN <- cesN[indexOf(cesN, pairs)]
names <- getNames(cesN)
dim(names) <- dim(pairs)
print(names)
Blim <- c(0,1)
Clim <- c(0,4)
Clab <- expression(C[T]/C[N])
BTlab <- expression(beta[T])
BNlab <- expression(beta[N])
Flab <- expression(beta[T]-beta[N])
Flim <- c(-1/2,1/2)
}
chromosome <- 9
units <- getUnitsOnChromosome(gi, chromosome)
pos <- getPositions(gi, units=units)/1e6
o <- order(pos)
units <- units[o]
pos <- pos[o]
str(units)
isSNP <- (getUnitTypes(cdf, units=units) == 2)
units <- units[isSNP]
pos <- pos[isSNP]
data <- extractTotalAndFreqB(cesN, units=units)
dim(data) <- c(dim(data)[1:2], dim(names))
dimnames(data) <- list(NULL, c("total", "freqB"), NULL, colnames(pairs))
C <- data[,"total",,"tumor"] / data[,"total",,"normal"]
B <- data[,"freqB",,]
F <- B[,,"tumor"] - B[,,"normal"]
F2 <- 2*(1/2-abs(B[,,"normal"]-1/2))
dAA <- sqrt((B[,,"normal"]-0)^2)
dBB <- sqrt((B[,,"normal"]-1)^2)
devSet(2)
subplots(3, ncol=1)
par(mar=c(2,4,1,1)+0.1)
par(ask=TRUE)
for (kk in seq_len(ncol(C))) {
plot(pos, C[,kk], ylim=Clim, ylab=Clab)
abline(h=1, lty=3, col="red")
stext(side=3, pos=0, paste(pairs[kk,], collapse="/"))
stext(side=3, pos=1, sprintf("Chr %d", chromosome))
plot(pos, B[,kk,"tumor"], ylim=Blim, ylab=BTlab)
plot(pos, F[,kk], cex=F2, ylim=Flim, ylab=Flab)
abline(h=0, lty=3, col="red")
}
devSet(3)
BNlab <- expression(beta[N])
BTlab <- expression(beta[T])
unitNames <- getUnitNames(cdf, units=units)
col <- seq_len(ncol(C))
par(ask=TRUE)
for (kk in seq_len(nrow(C))) {
plot(NA, xlim=Blim, ylim=Blim, xlab=BNlab, ylab=BTlab)
stext(side=3, pos=0, unitNames[kk])
points(B[kk,,], col=col, pch=19)
}
|
validate_data <- function(
dataset = NULL,
path = NULL) {
validate_arguments(fun.name = "validate_data", fun.args = as.list(environment()))
criteria <- read_criteria()
if (!is.null(path)) {
d <- read_data(from = path)
} else {
d <- dataset
}
id <- d$id
d <- d$tables
if (is.null(id)) {
id <- "unknown data ID"
}
message("Validating ", id, ":")
issues_table_presence <- validate_table_presence(d)
issues_column_names <- validate_column_names(d)
issues_column_presence <- validate_column_presence(d)
issues_column_classes <- validate_column_classes(d)
issues_datetime <- validate_datetime(d)
issues_primary_keys <- validate_primary_keys(d)
issues_composite_keys <- validate_composite_keys(d)
issues_referential_integrity <- validate_referential_integrity(d)
issues_validate_latitude_longitude_format <-
validate_latitude_longitude_format(d)
issues_validate_latitude_longitude_range <-
validate_latitude_longitude_range(d)
issues_validate_elevation <- validate_elevation(d)
issues_validate_variable_mapping <- validate_variable_mapping(d)
issues_validate_mapped_id <- validate_mapped_id(d)
validation_issues <- as.list(
c(
issues_table_presence,
issues_column_names,
issues_column_presence,
issues_column_classes,
issues_datetime,
issues_primary_keys,
issues_composite_keys,
issues_referential_integrity,
issues_validate_latitude_longitude_format,
issues_validate_latitude_longitude_range,
issues_validate_elevation,
issues_validate_variable_mapping,
issues_validate_mapped_id))
if (length(validation_issues) != 0) {
warning(" Validation issues found for ", id, call. = FALSE)
}
validation_issues
}
validate_table_presence <- function(data.list) {
message(" Required tables")
criteria <- read_criteria()
expected <- criteria$table[
(is.na(criteria$class)) & (criteria$required == TRUE)]
required_missing <- expected[!(expected %in% names(data.list))]
if (length(required_missing) != 0) {
paste0("Required table. Missing required table: ",
paste(required_missing, collapse = ", "))
}
}
validate_column_names <- function(data.list) {
message(' Column names')
criteria <- read_criteria()
r <- lapply(
names(data.list),
function(x) {
expected <- criteria$column[
(criteria$table %in% x) & !is.na(criteria$column)]
invalid_columns <- !(colnames(data.list[[x]]) %in% expected)
if (any(invalid_columns)) {
paste0(
"Column names. The ", x, " table has these invalid column ",
"names: ",
paste(colnames(data.list[[x]])[invalid_columns], collapse = ", "))
}
})
unlist(r)
}
validate_column_presence <- function(data.list){
message(' Required columns')
criteria <- read_criteria()
r <- lapply(
names(data.list),
function(x) {
expected <- criteria$column[
(criteria$table %in% x) &
!is.na(criteria$column) &
(criteria$required == TRUE)]
if ((x == "observation") & ("observation_ancillary" %in% names(data.list))) {
expected <- c(expected, "event_id")
}
missing_columns <- !(expected %in% colnames(data.list[[x]]))
if (any(missing_columns)) {
paste0(
"Required columns. The ", x, " table is missing these ",
"required columns: ",
paste(expected[missing_columns], collapse = ", "))
}
})
unlist(r)
}
validate_datetime <- function(data.list) {
message(' Datetime formats')
criteria <- read_criteria()
r <- lapply(
names(data.list),
function(x) {
datetime_column <- criteria$column[
(criteria$table %in% x) &
(criteria$class == "Date") &
!is.na(criteria$column)]
if (length(datetime_column) > 0) {
v <- data.list[[x]][[datetime_column]]
na_count_raw <- sum(is.na(v))
v <- as.character(v)
v <- stringr::str_remove_all(v, "(Z|z).+$")
v <- stringr::str_replace(v, "T", " ")
use_i <- suppressWarnings(
list(
lubridate::parse_date_time(v, "ymd HMS"),
lubridate::parse_date_time(v, "ymd HM"),
lubridate::parse_date_time(v, "ymd H"),
lubridate::parse_date_time(v, "ymd")))
na_count_parsed <- unlist(
lapply(
use_i,
function(k) {
sum(is.na(k))
}))
if (min(na_count_parsed) > na_count_raw) {
use_i <- seq(
length(v))[
is.na(
use_i[[
(which(na_count_parsed %in% min(na_count_parsed)))[1]]])]
paste0(
"Datetime format. The ", x, " table has unsupported ",
"datetime formats in rows: ",
paste(use_i, collapse = ' '))
}
}
})
return(unlist(r))
}
validate_column_classes <- function(data.list) {
message(" Column classes")
criteria <- read_criteria()
r <- invisible(
lapply(
names(data.list),
function(x) {
lapply(
colnames(data.list[[x]]),
function(k) {
if (k %in% criteria$column) {
expected <- criteria$class[
(criteria$table %in% x) &
!is.na(criteria$column) &
(criteria$column %in% k)]
detected <- class(data.list[[x]][[k]])
if (expected == "numeric") {
if ((detected != "integer") &
(detected != "integer64") &
(detected != "double") &
(detected != "numeric")) {
issues <- list(
column = k, expected = expected, detected = detected)
}
} else if (expected == "character") {
if (detected != "character") {
issues <- list(
column = k, expected = expected, detected = detected)
}
}
if (exists("issues", inherits = FALSE)) {
paste0(
"Column classes. The column ", k, " in the table ",
x, " has a class of ", detected, " but a class of ",
expected, " is expected.")
}
}
})
}))
unlist(r)
}
validate_primary_keys <- function(data.list) {
message(" Primary keys")
criteria <- read_criteria()
r <- invisible(
lapply(
names(data.list),
function(x) {
primary_key <- criteria$column[
(criteria$table == x) &
!is.na(criteria$primary_key) &
(criteria$primary_key == TRUE)]
v <- data.list[[x]][[primary_key]]
use_i <- seq(length(v))[duplicated(v)]
if (length(use_i) > 0) {
paste0("Primary keys. The ", x, " table contains non-unique ",
"primary keys in the column ", primary_key, " at rows: ",
paste(use_i, collapse = " "))
}
}))
unlist(r)
}
validate_composite_keys <- function(data.list) {
message(" Composite keys")
criteria <- read_criteria()
r <- invisible(
lapply(
names(data.list),
function(x) {
composite_columns <- criteria$column[
(criteria$table == x) &
!is.na(criteria$column) &
(criteria$composite_key == TRUE)]
composite_columns <- composite_columns[
composite_columns %in% colnames(data.list[[x]])]
if (length(composite_columns) > 0) {
d <- dplyr::select(data.list[[x]], composite_columns)
duplicates <- seq(nrow(d))[duplicated.data.frame(d)]
if (length(duplicates) > 0) {
paste0(
"Composite keys. The composite keys composed of the columns ",
paste(composite_columns, collapse = ", "),
", in the table ", x, " contain non-unique values in rows: ",
paste(duplicates, collapse = " "))
}
}
}))
unlist(r)
}
validate_referential_integrity <- function(data.list) {
message(" Referential integrity")
criteria <- read_criteria()
r <- invisible(
lapply(
names(data.list),
function(x) {
primary_key <- criteria$column[
(criteria$table == x) &
!is.na(criteria$column) &
(criteria$primary_key == TRUE)]
primary_key_data <- stats::na.omit(data.list[[x]][[primary_key]])
foreign_key_table <- criteria$table[
!is.na(criteria$column) &
(criteria$column == primary_key)]
output <- lapply(
foreign_key_table,
function(k) {
if (k == "location") {
foreign_key_data <- stats::na.omit(data.list[[k]][["parent_location_id"]])
use_i <- foreign_key_data %in% primary_key_data
if (length(use_i) == 0) {
use_i <- TRUE
}
} else {
foreign_key_data <- stats::na.omit(data.list[[k]][[primary_key]])
use_i <- foreign_key_data %in% primary_key_data
}
if (!all(use_i)) {
paste0(
"Referential integrity. The ", k, " table has these foreign ",
"keys without a primary key reference in the ", x, " table: ",
paste(unique(foreign_key_data[!use_i]), collapse = ", "))
}
})
unlist(output)
}))
unlist(r)
}
validate_latitude_longitude_format <- function(data.list) {
message(" Latitude and longitude format")
r <- invisible(
lapply(
c("latitude", "longitude"),
function(colname) {
na_before <- sum(is.na(data.list$location[[colname]]))
na_after <- suppressWarnings(
sum(is.na(as.numeric(data.list$location[[colname]]))))
if (na_before < na_after) {
paste0(
"The ", colname, " column of the location table contains values ",
"that are not in decimal degree format.")
}
}))
unlist(r)
}
validate_latitude_longitude_range <- function(data.list) {
message(" Latitude and longitude range")
r <- invisible(
lapply(
c("latitude", "longitude"),
function(colname) {
values <- suppressWarnings(
as.numeric(data.list$location[[colname]]))
if (colname == "latitude") {
use_i <- (values >= -90) & (values <= 90)
use_i <- stats::na.omit(seq(length(use_i))[!use_i])
if (length(use_i) > 0) {
return(
paste0(
"The ", colname, " column of the location table contains ",
"values outside the bounds -90 to 90 in rows: ",
paste(use_i, collapse = ", ")))
}
} else if (colname == "longitude") {
use_i <- (values >= -180) & (values <= 180)
use_i <- stats::na.omit(seq(length(use_i))[!use_i])
if (length(use_i) > 0) {
return(
paste0(
"The ", colname, " column of the location table contains ",
"values outside the bounds -180 to 180 in rows: ",
paste(use_i, collapse = ", ")))
}
}
}))
unlist(r)
}
validate_elevation <- function(data.list) {
message(" Elevation")
r <- invisible(
lapply(
c("elevation"),
function(colname) {
values <- suppressWarnings(
as.numeric(data.list$location[[colname]]))
use_i <- (values <= 8848) & (values >= -10984)
use_i <- stats::na.omit(seq(length(use_i))[!use_i])
if (length(use_i) > 0) {
return(
paste0(
"The ", colname, " column of the location table contains ",
"values that may not be in the unit of meters. Questionable ",
"values exist in rows: ",
paste(use_i, collapse = ", ")))
}
}))
unlist(r)
}
validate_variable_mapping <- function(data.list) {
if ("variable_mapping" %in% names(data.list)) {
message(" variable_mapping")
output <- lapply(
unique(data.list$variable_mapping$table_name),
function(tbl) {
foreign_keys <- unique(data.list[[tbl]]$variable_name)
i <- data.list$variable_mapping$table_name %in% tbl
primary_keys <- data.list$variable_mapping$variable_name[i]
use_i <- primary_keys %in% foreign_keys
if (!all(use_i)) {
paste0(
"Variable mapping. The variable_mapping table has these variable_name values ",
"without a match in the ", tbl, " table: ",
paste(primary_keys[!use_i], collapse = ", "))
}
})
return(unlist(output))
}
}
validate_mapped_id <- function(data.list) {
callstack <- as.character(sys.calls())
continue <- any(stringr::str_detect(callstack, "validate_data\\(path")) |
any(stringr::str_detect(callstack, "test_that\\("))
if (continue) {
if ("variable_mapping" %in% names(data.list)) {
message(" mapped_id")
output <- lapply(
unique(data.list$variable_mapping$mapped_id),
function(m_id) {
m_id <- trimws(m_id)
i <- try(httr::GET(m_id)$status, silent = T)
if (i != 200 & !is.na(m_id)) {
paste(m_id)
}
})
output <- unlist(output)
if (!is.null(output)) {
output <- paste0("Variable mapping. The variable_mapping table has ",
"these mapped_id values that don't resolve: ",
paste(unlist(output), collapse = ", "))
}
return(output)
}
}
}
|
library(ggplot2)
this_base <- "fig02-01_structured-data-set"
my_data <- data.frame(
variable = paste("Item", 10:1),
value = c(11.5, 6.5, 13.5, 8.5, 12.5, 7.5, 13.0, 8.0, 12.0, 7.0))
p <- ggplot(my_data, aes(x = factor(1), y = value)) +
geom_bar(width = 1, colour = "black", fill = "white", stat = "identity") +
geom_text(aes(x = 1.75, y = cumsum(value) - value/2, label = variable)) +
coord_polar(theta = "y", start = pi/2) +
ggtitle("Fig 2.1 Structured Data Set") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.border = element_blank(),
plot.title = element_text(size = rel(1.2), face = "bold", vjust = 1.5),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank())
p
ggsave(paste0(this_base, ".png"),
p, width = 6, height = 5)
|
setMethod("extent", "LAScatalog",
function(x, ...) {
return(raster::extent(min(x@data$Min.X), max(x@data$Max.X), min(x@data$Min.Y), max(x@data$Max.Y)))
}
)
setMethod("[", "LAScatalog", function(x, i, j, ..., drop = TRUE) {
ctgname <- deparse(substitute(x))
iname <- deparse(substitute(i))
nargs <- nargs()
if (!missing(i) & !missing(j))
stop(glue::glue("This action is not allowed for a {class(x)}. j must be missing. Maybe you meant: {ctgname}[{iname}, ]."), call. = FALSE)
if (missing(i) & !missing(j))
stop(glue::glue("This action is not allowed for a {class(x)}. i cannot be missing."), call. = FALSE)
if (!missing(i) & missing(j) & nargs == 2L)
stop(glue::glue("This action is not allowed for a {class(x)}. Maybe you meant: {ctgname}[{iname}, ]."), call. = FALSE)
y <- callNextMethod()
new_ctg <- new("LAScatalog")
new_ctg@chunk_options <- x@chunk_options
new_ctg@processing_options <- x@processing_options
new_ctg@output_options <- x@output_options
new_ctg@input_options <- x@input_options
new_ctg@data <- y@data
new_ctg@polygons <- y@polygons
new_ctg@plotOrder <- y@plotOrder
new_ctg@bbox <- y@bbox
new_ctg@proj4string <- y@proj4string
return(new_ctg)
})
setMethod("[[<-", "LAScatalog", function(x, i, j, value)
{
if (i %in% LASCATALOGATTRIBUTES)
stop("LAScatalog data read from standard files cannot be modified", call. = FALSE)
x@data[[i]] = value
return(x)
})
setMethod("$<-", "LAScatalog", function(x, name, value)
{
if (name %in% LASCATALOGATTRIBUTES)
stop("LAScatalog data read from standard files cannot be modified", call. = FALSE)
x@data[[name]] = value
return(x)
})
|
DS.prior.bbu <-
function(yn.df, max.m = 8, start.par, iter.c = 200,
B = 1000, smooth.crit = "BIC", LP.type = c("L2","MaxEnt")){
LP.type <- match.arg(LP.type)
fam <- "Binomial"
out <- list()
if(dbeta(0, start.par[1], start.par[2]) != Inf){
theta.vals <- seq(0,1, length.out = B)
}else{
theta.vals <- seq(1/B,1-(1/B), length.out = B)
}
PEB.g <- dbeta(theta.vals, start.par[1], start.par[2])
u.grid <- pbeta(theta.vals, start.par[1], start.par[2])
if(max.m == 0){
out$g.par <- start.par
out$LP.par <- 0
out$prior.fit <- data.frame(theta.vals = theta.vals,
parm.prior = PEB.g)
out$UF.data <- data.frame(UF.x = u.grid, UF.y = rep(1,length(u.grid)))
out$obs.data <- data.frame(y = yn.df[,1], n = yn.df[,2])
out$dev.df <- data.frame(m = 0, dev = 0)
out$fam <- fam
out$LP.type <- "L2"
class(out) <- "DS_GF"
return(out)
}
c.vec <- NULL
dev.m <- NULL
B.loop <- 150
u.loop <- seq(1/B.loop,1-(1/B.loop), length.out = B.loop)
post.alpha.i <- start.par[1] + yn.df[,1]
post.beta.i <- yn.df[,2] - yn.df[,1] + start.par[2]
post.mat <- data.frame(al = post.alpha.i, be = post.beta.i)
wght.loop <- apply(post.mat, 1, function(x) weight.fun.univ(u.loop, start.par[1], start.par[2], x[1], x[2], family = fam))
if(smooth.crit == "BIC"){
out$sm.crit <- "BIC"
for(j in 1:max.m){
c.vec[j]<-0
cutoff.c <- 0
leg.mat.j <- gLP.basis(u.loop, c(1,1), length(c.vec), con.prior = "Beta")
for(i in 1:iter.c){
c.L.new <- Reduce.LP.coef.univ(wght.mat=wght.loop, c.vec, leg.mat.j, freq.vec = NULL, k.tot = NULL)
cutoff.c[i+1] <- sqrt(sum((c.L.new - c.vec)^2))
c.vec[j] <- c.L.new[j]
if (cutoff.c[i+1] < 0.006 | abs(cutoff.c[i+1] - cutoff.c[(i)]) < 0.000006 ) {break}
}
dev.m[j] <- max(0,sum(c.vec^2)-(log(dim(yn.df)[1]))*(j/dim(yn.df)[1]))
}
} else {
out$sm.crit <- "AIC"
for(j in 1:max.m){
c.vec[j]<-0
cutoff.c <- 0
leg.mat.j <- gLP.basis(u.loop, c(1,1), length(c.vec), con.prior = "Beta")
for(i in 1:iter.c){
c.L.new <- Reduce.LP.coef.univ(wght.mat=wght.loop, c.vec, leg.mat.j, freq.vec = NULL, k.tot = NULL)
cutoff.c[i+1] <- sqrt(sum((c.L.new - c.vec)^2))
c.vec[j] <- c.L.new[j]
if (cutoff.c[i+1] < 0.006 | abs(cutoff.c[i+1] - cutoff.c[(i)]) < 0.000006 ) {break}
}
dev.m[j] <- max(0,sum(c.vec^2) - (2 * (j/dim(yn.df)[1])))
}
}
m.vec <- c(1:max.m)
if(sum(dev.m)==0){
out$m.val <- 0
out$g.par <- start.par
names(out$g.par) <- c("alpha","beta")
out$LP.par <- 0
out$LP.max.uns <- c.vec
out$LP.max.smt <- LP.smooth(c.vec,dim(yn.df)[1], method = smooth.crit)
out$prior.fit <- data.frame(theta.vals = theta.vals,
parm.prior = PEB.g)
out$UF.data <- data.frame(UF.x = u.grid, UF.y = rep(1,length(u.grid)))
out$obs.data <- data.frame(y = yn.df[,1], n = yn.df[,2])
out$dev.df <- data.frame( m = m.vec, dev = dev.m)
out$LP.type <- "L2"
out$fam <- fam
class(out) <- "DS_GF"
return(out)
}else{
out$m.val <- m.vec[which.max(dev.m)]
out$LP.max.smt <- LP.smooth(c.vec,dim(yn.df)[1], method = smooth.crit)
out$LP.par <- out$LP.max.smt[1:out$m.val]
out$LP.max.uns <- c.vec
out$dev.df <- data.frame( m = m.vec, dev = dev.m)
out$g.par <- c(start.par[1], start.par[2])
names(out$g.par) <- c("alpha","beta")
names(out$LP.par) <- paste("LP",1:length(out$LP.par),sep = "")
d.u <- 1 + gLP.basis(u.grid,c(1,1),out$m.val, con.prior = "Beta")%*%out$LP.par
Leg.mat <- gLP.basis(theta.vals, start.par, out$m.val, con.prior = "Beta")
d.G <- 1+Leg.mat%*%out$LP.par
DS.sm <- PEB.g*d.G
DS.sm[DS.sm<0]<-0.0000000001
d.u[d.u<0] <- 0.0000000001
area <- sintegral(u.grid, d.u)$int
out$prior.fit <- data.frame(theta.vals = theta.vals,
parm.prior = PEB.g,
ds.prior = DS.sm/area)
out$UF.data <- data.frame(UF.x = u.grid, UF.y = d.u/area)
out$obs.data <- data.frame(y = yn.df[,1], n = yn.df[,2])
out$fam <- fam
if(LP.type == "L2"){
out$LP.type <- "L2"
} else {
out <- maxent.obj.convert(out)
out$LP.type <- "MaxEnt"
}
class(out) <- "DS_GF"
return(out)
}
}
|
spectralslice = function (sound, padding = length(sound) * 2, fs = 1, show = TRUE,
add = FALSE, window = "kaiser", windowparameter = 3, zeromax = TRUE,
preemphasisf = 0, type, line = FALSE, removeDC = TRUE, ...){
if (class(sound) == "ts") fs = frequency (sound)
if (class(sound) == "sound") {
fs = sound$fs
sound = sound$sound
}
if (preemphasisf > 0)
sound = preemphasis(sound, preemphasisf, fs)
n = length(sound)
if (removeDC)
sound = sound - mean(sound)
sound = sound * windowfunc(n, window, windowparameter)
N = n + padding
if (fs > 1)
hz = seq(0, fs, length.out = N + 1)
if (fs == 1)
hz = seq(0, 1, length.out = N + 1)
hz = hz[hz <= fs/2]
sound = c(sound, rep(0, padding))
power = abs(fft(sound))
power = power[1:length(hz)]/(n/2)
power = log(power, 10) * 20
power[which(power == min(power))] = sort(power)[2]
if (zeromax == TRUE)
power = power - max(power)
if (missing(type))
type = "l"
if (fs > 1)
xlab = "Frequency (Hz)"
if (fs == 1)
xlab = "Frequency / Sampling Freq."
if (add == FALSE & show == TRUE & line == FALSE)
plot(hz, power, ylab = "Power (dB)", xlab = xlab, type = type,
xaxs = "i", ...)
if (add == TRUE & show == TRUE & line == FALSE)
lines(hz, power, type = type, ...)
if (line == TRUE) {
plot(hz, power, ylab = "Power (dB)", xlab = xlab, type = "p",
pch = 16, xaxs = "i", ...)
segments(hz, rep(-5000, length(hz)), hz, power)
}
dB = power
invisible(cbind(hz, dB))
}
slice = function (sound, padding = length(sound) * 2, fs = 1, show = TRUE,
add = FALSE, window = "kaiser", windowparameter = 3, zeromax = TRUE,
preemphasisf = 0, type, line = FALSE, removeDC = TRUE, ...){
cl = match.call()
args = sapply (2:length(cl), function(x) cl[[x]])
names(args) = names(cl)[-1]
do.call (spectralslice, args)
}
|
mod_search_ui <- function(id) {
ns <- NS(id)
tabPanel(
title = "Search",
column(
width = 12,
fluidRow(column(width = 12,
h2(textOutput(
ns("heading")
)))),
fluidRow(column(
width = 12,
textInput(inputId = ns("search_string"),
label = "Search:")
)),
fluidRow(column(
width = 12,
tags$div(
align = "left",
class = "multicol",
checkboxGroupInput(
inputId = ns("search_columns"),
label = "Select columns to search in:",
choices = NULL
)
)
)),
fluidRow(column(
width = 12,
tags$div(
align = "left",
class = "multicol",
checkboxGroupInput(
inputId = ns("display_columns"),
label = "Select columns to display:",
choices = NULL
)
)
)),
fluidRow(
column(width = 3,
radioButtons(
inputId = ns("search_type"),
label = NULL,
choices = c(
"Use SQLite Style Wildcard Characters",
"Use UNIX Style Wildcard Characters",
"Use Regex"
)
)),
column(
width = 9,
conditionalPanel(
condition = paste0(
"input['",
ns("search_type"),
"'] == 'Use SQLite Style Wildcard Characters'"
),
checkboxInput(inputId = ns("escape_characters"),
label = "Escape % and _ characters.")
)
)
),
fluidRow(column(
width = 12,
actionButton(inputId = ns("search_button"),
label = "Search")
)),
fluidRow(column(width = 12, uiOutput(
ns("search_results_ui")
))),
br(),
br()
)
)
}
mod_search_server <- function(input, output, session, conn) {
ns <- session$ns
info <- reactiveValues(data = NULL)
output$heading <-
renderText({
paste0("Search - ", conn$active_table)
})
output$search_results_ui <- renderUI({
column(
width = 12,
id = "search_results",
conditionalPanel(condition = !is.null(info$data),
fluidRow(DT::DTOutput(
ns("search_results")
)))
)
})
output$search_results <-
DT::renderDT(expr = {
DT::datatable(data = info$data)
})
observeEvent(conn$active_table, {
if (conn$active_table != "") {
updateCheckboxGroupInput(
session = session,
inputId = "display_columns",
choices = RSQLite::dbGetQuery(
conn$active_db,
table_structure_query(conn$active_table)
)$name,
selected = RSQLite::dbGetQuery(
conn$active_db,
table_structure_query(conn$active_table)
)$name
)
updateCheckboxGroupInput(
session = session,
inputId = "search_columns",
choices = RSQLite::dbGetQuery(
conn$active_db,
table_structure_query(conn$active_table)
)$name,
selected = RSQLite::dbGetQuery(
conn$active_db,
table_structure_query(conn$active_table)
)$name
)
}
})
observeEvent(input$search_button, {
if (input$search_string == "") {
showNotification(ui = "Please enter a search query.",
duration = 3,
type = "error")
}
else if (is.null(input$display_columns))
showNotification(ui = "Please select columns to display.",
duration = 3,
type = "error")
else if (input$search_type == "Use SQLite Style Wildcard Characters") {
info$data <- RSQLite::dbGetQuery(
conn$active_db,
search_query_sqlite(
input$display_columns,
input$search_columns,
conn$active_table,
input$search_string,
input$escape_characters
)
)
}
else if (input$search_type == "Use UNIX Style Wildcard Characters") {
info$data <- RSQLite::dbGetQuery(
conn$active_db,
search_query_unix(
input$display_columns,
input$search_columns,
conn$active_table,
input$search_string
)
)
}
else if (input$search_type == "Use Regex") {
RSQLite::initRegExp(conn$active_db)
info$data <- RSQLite::dbGetQuery(
conn$active_db,
search_query_regex(
input$display_columns,
input$search_columns,
conn$active_table,
input$search_string
)
)
}
})
}
|
lambdak_pos <-
function(times, subj, X, y, d, tau, kn, degree, lambda, gam){
dim = length(y)
X = matrix(X, nrow=dim)
px = ncol(X)
lambdasic = Lamb_pos(times, subj, X, y, d, tau, kn, degree, lambda)$lambdasic
qvc2=qrvcp_pos(times, subj, y, X, tau=tau, kn=kn, degree=degree, lambda=rep(0,px), d)$hat_bt
lambdasicr = NULL
for(k in 1:px){
lambdasicr[k] = lambdasic*(max(qvc2[seq((k-1)*dim+1,k*dim)])-min(qvc2[seq((k-1)*dim+1,k*dim)]))^(-(gam))
}
out = list(lambdasic = lambdasic, lambdasicr=lambdasicr)
return(out)
}
|
PMCP <- "polyMatrixCharPolynomial"
.check.polyMatrixCharClass <- function (object) {
if (nrow(object@coef) != 1) {
return("Char polynomial matrix should contain only one row")
}
return(TRUE)
}
polyMatrixCharClass <- setClass(
PMCP,
slots = c(coef=PM),
validity = .check.polyMatrixCharClass
)
|
normalizeNames <-
function(x, pattern=list(" "), replacement=list("_"), alnum = FALSE, ...)
{
if (!is.factor(x))
x <- as.character(x)
l0 <- if (is.factor(x))
levels(x) else unique(x)
l <- l0
if (length(pattern) != length(replacement))
stop("pattern and replacement lengths must be equal")
pattern <- as.list(pattern)
replacement <- as.list(replacement)
for (i in seq_len(length(pattern))) {
l <- gsub(as.character(pattern[[i]]), as.character(replacement[[i]]),
l, fixed=TRUE)
}
if (alnum)
l <- nameAlnum(l, ...)
if (is.factor(x)) {
levels(x) <- l
} else {
x <- l[match(x, l0)]
}
x
}
|
getBandWidth <-
function(A, kmax = 3) {
estkappa <- numeric(kmax)
for (k in 1:kmax) {
trigmom <- TrigMomRad(A, k)
if (Afun(0.0001, trigmom, k) * Afun(345, trigmom, k) <= 0)
estkappa[k] <- uniroot(Afun, c(0.0001,345), trigmom, k)$root
}
kappahat <- max(estkappa[1:kmax])
if(kappahat > 0) {
return( ( 3 * length(A) * kappahat^2 * besselI(2 * kappahat, 2) /
(4 * sqrt(pi) * besselI(kappahat, 0)^2) )^(2/5) )
} else {
return(NA)
}
}
TrigMomRad <-
function(x, p) {
sinr <- sum(sin(x))
cosr <- sum(cos(x))
circmean <- atan2(sinr, cosr)
sin.p <- mean(sin(p * (x - circmean)))
cos.p <- mean(cos(p * (x - circmean)))
sqrt(sin.p^2 + cos.p^2)
}
Afun <-
function(kappa, trigmom, k) {
besselI(kappa, k) / besselI(kappa, 0) - trigmom
}
|
cstar<-function(regobject, r){
s<-sign(regobject$coefficients)
b<-abs(regobject$coefficients)
v<-sqrt(diag(vcov(regobject)))
degfr<-regobject$df
utility<-function(t,a,x,m,sigma,degfr){
k<-as.numeric((x-t)>0)*2-1
xx<-(x-m)/sigma;
tt<-(t-m)/sigma;
out<-a^(-k)*dt(xx, df=degfr)*(x-t);
return(out)
}
maximand<-function(t,a,m,sigma,degfr){as.numeric(integrate(utility, m-8*sigma, m+8*sigma, rel.tol=.Machine$double.eps^0.5, t=t, a=a, m=m, sigma=sigma, degfr=degfr)[1])}
out<-c()
for(i in 1:length(b)){
if(floor(i/10)==(i/10)){print(c("Iteration ",i))}
if(b[i]!=0){out[i]<- sign(s[i])*uniroot(maximand, interval=c(-v[i]-b[i],v[i]+b[i]), tol=.Machine$double.eps^0.5, a=r, m=b[i], sigma=v[i], degfr=degfr)$root}
else{out[i]<- 0}
}
for(i in 1:length(b)){
if(sign(out[i])!=s[i]){out[i]<-0}
}
return(out)
}
cstari<-function(b,v,degfr,r){
s<-sign(b)
b<-abs(b)
utility<-function(t,a,x,m,sigma,degfr){
k<-as.numeric((x-t)>0)*2-1
xx<-(x-m)/sigma;
tt<-(t-m)/sigma;
out<-a^(-k)*dt(xx, df=degfr)*(x-t);
return(out)
}
maximand<-function(t,a,m,sigma,degfr){as.numeric(integrate(utility, b-8*sigma, b+8*sigma, rel.tol=.Machine$double.eps^0.5, t=t, a=a, m=m, sigma=sigma, degfr=degfr)[1])}
out<-c()
for(i in 1:length(b)){
if(floor(i/10)==(i/10)){print(c("Iteration ",i))}
if(b[i]!=0){out[i]<- sign(s[i])*uniroot(maximand, interval=c(-v[i]-b[i],v[i]+b[i]), tol=.Machine$double.eps^0.5, a=r, m=b[i], sigma=v[i], degfr=degfr)$root}
else{out[i]<- 0}
}
for(i in 1:length(b)){
if(sign(out[i])!=s[i]){out[i]<-0}
}
return(out)
}
|
TS_on_LDA <- function(LDA_models, document_covariate_table, formulas = ~ 1,
nchangepoints = 0, timename = "time", weights = NULL,
control = list()){
check_TS_on_LDA_inputs(LDA_models, document_covariate_table, formulas,
nchangepoints, timename, weights, control)
control <- do.call("TS_control", control)
mods <- expand_TS(LDA_models, formulas, nchangepoints)
nmods <- nrow(mods)
TSmods <- vector("list", nmods)
for(i in 1:nmods){
print_model_run_message(mods, i, LDA_models, control)
formula_i <- mods$formula[[i]]
nchangepoints_i <- mods$nchangepoints[i]
data_i <- prep_TS_data(document_covariate_table, LDA_models, mods, i)
TSmods[[i]] <- TS(data_i, formula_i, nchangepoints_i, timename, weights,
control)
}
package_TS_on_LDA(TSmods, LDA_models, mods)
}
prep_TS_data <- function(document_covariate_table, LDA_models, mods, i = 1){
check_document_covariate_table(document_covariate_table, LDA_models)
check_LDA_models(LDA_models)
if(is(LDA_models, "LDA")){
LDA_models <- c(LDA_models)
class(LDA_models) <- c("LDA_set", "list")
}
data_i <- document_covariate_table
data_i$gamma <- LDA_models[[mods$LDA[i]]]@gamma
data_i
}
select_TS <- function(TS_models, control = list()){
if (!("TS_on_LDA" %in% class(TS_models))){
stop("TS_models must be of class TS_on_LDA")
}
check_control(control)
control <- do.call("TS_control", control)
measurer <- control$measurer
selector <- control$selector
TS_measured <- vapply(TS_models, measurer, 0) %>%
matrix(ncol = 1)
TS_selected <- apply(TS_measured, 2, selector)
which_selected <- which(TS_measured %in% TS_selected)
if (length(which_selected) > 1){
warning("Selection results in multiple models, returning first")
which_selected <- which_selected[1]
}
out <- TS_models[[which_selected]]
class(out) <- c("TS_fit", "list")
out
}
package_TS_on_LDA <- function(TSmods, LDA_models, models){
check_LDA_models(LDA_models)
if(is(LDA_models, "LDA")){
LDA_models <- c(LDA_models)
class(LDA_models) <- c("LDA_set", "list")
}
nmodels <- nrow(models)
nms <- rep(NA, nmodels)
for (i in 1:nmodels){
nms[i] <- paste0(names(LDA_models)[models$LDA[i]], ", ",
deparse(models$formula[[i]]), ", ",
models$nchangepoints[i], " changepoints")
}
names(TSmods) <- nms
class(TSmods) <- list("TS_on_LDA", "list")
TSmods
}
print.TS_on_LDA <- function(x, ...){
print(names(x))
}
print_model_run_message <- function(models, i, LDA_models, control){
control <- do.call("TS_control", control)
equation <- deparse(models$formula[[i]])
chngpt_msg <- paste0("with ", models$nchangepoints[i], " changepoints ")
reg_msg <- paste0("and equation ", equation)
ts_msg <- paste0(chngpt_msg, reg_msg)
lda_msg <- names(LDA_models)[models$LDA[i]]
msg <- paste0("Running TS model ", ts_msg, " on LDA model ", lda_msg, "\n")
messageq(msg, control$quiet)
}
expand_TS <- function(LDA_models, formulas, nchangepoints){
check_LDA_models(LDA_models)
check_nchangepoints(nchangepoints)
if (is(LDA_models, "LDA")) {
LDA_models <- c(LDA_models)
class(LDA_models) <- c("LDA_set", "list")
}
if (!is(formulas, "list")) {
if (is(formulas, "formula")) {
formulas <- c(formulas)
} else{
stop("formulas does not contain formula(s)")
}
} else if (!all(vapply(formulas, is, TRUE, "formula"))) {
stop("formulas does not contain all formula(s)")
}
formulas
out <- formulas
for (i in seq_along(formulas)) {
tformula <- paste(as.character(formulas[[i]]), collapse = "")
out[[i]] <- as.formula(paste("gamma", tformula))
}
formulas <- out
nmods <- length(LDA_models)
mods <- 1:nmods
out <- expand.grid(mods, formulas, nchangepoints, stringsAsFactors = FALSE)
colnames(out) <- c("LDA", "formula", "nchangepoints")
out
}
check_nchangepoints <- function(nchangepoints){
if (!is.numeric(nchangepoints) || any(nchangepoints %% 1 != 0)){
stop("nchangepoints must be integer-valued")
}
if (any(nchangepoints < 0)){
stop("nchangepoints must be non-negative")
}
return()
}
check_weights <- function(weights){
if(is.logical(weights)){
if(weights){
return()
} else{
stop("if logical, weights need to be TRUE")
}
}
if(!is.null(weights)){
if (!is.numeric(weights)){
stop("weights vector must be numeric")
}
if (any(weights <= 0)){
stop("weights must be positive")
}
if (round(mean(weights)) != 1){
warning("weights should have a mean of 1, fit may be unstable")
}
}
return()
}
check_LDA_models <- function(LDA_models){
if(("LDA_set" %in% class(LDA_models)) == FALSE){
if(is(LDA_models, "LDA") == FALSE){
stop("LDA_models is not an LDA object or LDA_set object")
}
}
return()
}
check_document_covariate_table <- function(document_covariate_table,
LDA_models = NULL,
document_term_table = NULL){
dct_df <- tryCatch(data.frame(document_covariate_table),
warning = function(x){NA}, error = function(x){NA})
if(is(LDA_models, "LDA")){
LDA_models <- c(LDA_models)
class(LDA_models) <- c("LDA_set", "list")
}
if (length(dct_df) == 1 && is.na(dct_df)){
stop("document_covariate_table is not conformable to a data frame")
}
if (!is.null(LDA_models)){
if (nrow(data.frame(document_covariate_table)) !=
nrow(LDA_models[[1]]@gamma)){
stop("number of documents in covariate table is not equal to number of
documents observed")
}
} else if (!is.null(document_term_table)){
if (nrow(data.frame(document_covariate_table)) !=
nrow(data.frame(document_term_table))){
stop("number of documents in covariate table is not equal to number of
documents observed")
}
}
return()
}
check_timename <- function(document_covariate_table, timename){
if (!("character" %in% class(timename))){
stop("timename is not a character value")
}
if (length(timename) > 1){
stop("timename can only be one value")
}
covariate_names <- colnames(document_covariate_table)
if ((timename %in% covariate_names) == FALSE){
stop("timename not present in document covariate table")
}
time_covariate <- document_covariate_table[ , timename]
if (!(is.Date(time_covariate)) &
(!is.numeric(time_covariate) || !all(time_covariate %% 1 == 0))){
stop("covariate indicated by timename is not an integer or a date")
}
return()
}
check_formulas <- function(formulas, document_covariate_table,
control = list()){
check_document_covariate_table(document_covariate_table)
check_control(control)
control <- do.call("TS_control", control)
dct <- document_covariate_table
if (!is(formulas, "list")) {
if (is(formulas, "formula")) {
formulas <- c(formulas)
} else{
stop("formulas does not contain formula(s)")
}
} else if (!all(vapply(formulas, is, TRUE, "formula"))) {
stop("formulas does not contain all formula(s)")
}
resp <- unlist(lapply(lapply(formulas, terms), attr, "response"))
pred <- unlist(lapply(lapply(formulas, terms), attr, "term.labels"))
if (any(resp != 0)) {
stop("formula inputs should not include response variable")
}
if (!all(pred %in% colnames(dct))) {
misses <- pred[which(pred %in% colnames(dct) == FALSE)]
mis <- paste(misses, collapse = ", ")
stop(paste0("formulas include predictors not present in data: ", mis))
}
return()
}
check_TS_on_LDA_inputs <- function(LDA_models, document_covariate_table,
formulas = ~ 1, nchangepoints = 0,
timename = "time", weights = NULL,
control = list()){
check_LDA_models(LDA_models)
check_document_covariate_table(document_covariate_table, LDA_models)
check_timename(document_covariate_table, timename)
check_formulas(formulas, document_covariate_table, control)
check_nchangepoints(nchangepoints)
check_weights(weights)
check_control(control)
}
|
add_line_layer <- function(deckgl, id = "line-layer", data = NULL, properties = list(), ...) {
add_layer(deckgl, "LineLayer", id, data, properties, ...)
}
|
shinydashboard::tabItem(
tabName = "amgauge",
fluidRow(
column(
width = 12,
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("amangular"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
verbatimTextOutput("code_amangular"))
)
)
),
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Bands", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("amangular2"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Bands", align="center"),
column(
width = 12,
verbatimTextOutput("code_amangular2"))
)
)
),
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Multi bands", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("amangular3"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Multi bands", align="center"),
column(
width = 12,
verbatimTextOutput("code_amangular3"))
)
)
),
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Solid", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("amangular4"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Solid", align="center"),
column(
width = 12,
verbatimTextOutput("code_amangular4"))
)
)
)
)
)
)
|
cec2013 <- function (i, x) {
if (missing(i)) stop("Missing argument; 'i' has to be provided !")
if (missing(x)) stop("Missing argument; 'x' has to be provided !")
if (is.numeric(i) && i >= 1 && i <= 28) {
if (is.vector(x)) {
row <- 1; col <- length(x)
} else if (is.matrix(x)) {
row <- nrow(x); col <- ncol(x)
} else {
stop("x should be a vector or a matrix")
}
if (!(col %in% c(2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100))) {
stop("Invalid argument: Only 2, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90 and 100 dimensions/variables are allowed !")
}
extdatadir <- system.file("extdata", package = "cec2013")
f <- .C("cec2013", extdatadir = as.character(extdatadir),
i = as.integer(i), x = as.double(x), row = as.integer(row),
col = as.integer(col), f = double(row),
PACKAGE = "cec2013")$f
} else stop("Invalid argument: 'i' should be an integer between 1 and 28 !")
return(f)
}
|
context("Property getters")
tenant <- Sys.getenv("AZ_TEST_TENANT_ID")
app <- Sys.getenv("AZ_TEST_APP_ID")
password <- Sys.getenv("AZ_TEST_PASSWORD")
subscription <- Sys.getenv("AZ_TEST_SUBSCRIPTION")
if(tenant == "" || app == "" || password == "" || subscription == "")
skip("ARM credentials not set")
rgname <- Sys.getenv("AZ_TEST_STORAGE_RG")
stornamenohns <- Sys.getenv("AZ_TEST_STORAGE_NOHNS")
stornamehns <- Sys.getenv("AZ_TEST_STORAGE_HNS")
if(rgname == "" || stornamenohns == "" || stornamehns == "")
skip("Property getter tests skipped: resource names not set")
sub <- AzureRMR::az_rm$new(tenant=tenant, app=app, password=password)$get_subscription(subscription)
stornohns <- sub$get_resource_group(rgname)$get_storage_account(stornamenohns)
storhns <- sub$get_resource_group(rgname)$get_storage_account(stornamehns)
options(azure_storage_progress_bar=FALSE)
bl <- stornohns$get_blob_endpoint()
cont <- create_storage_container(bl, paste0(sample(letters, 10, TRUE), collapse=""))
storage_upload(cont, "../resources/iris.csv", "iris.csv")
fl <- stornohns$get_file_endpoint()
share <- create_storage_container(fl, paste0(sample(letters, 10, TRUE), collapse=""))
create_storage_dir(share, "dir")
storage_upload(share, "../resources/iris.csv", "iris.csv")
ad <- storhns$get_adls_endpoint()
fs <- create_storage_container(ad, paste0(sample(letters, 10, TRUE), collapse=""))
create_storage_dir(fs, "dir")
storage_upload(fs, "../resources/iris.csv", "iris.csv")
test_that("Blob property getters work",
{
expect_is(cont, "blob_container")
prop1 <- get_storage_properties(cont)
expect_true(is.list(prop1) && !is_empty(prop1))
prop2 <- get_storage_properties(cont, "iris.csv")
expect_true(is.list(prop2) && !is_empty(prop2))
expect_identical(prop2$`content-type`, "text/csv")
})
test_that("File property getters work",
{
expect_is(share, "file_share")
prop1 <- get_storage_properties(share)
expect_true(is.list(prop1) && !is_empty(prop1))
prop2 <- get_storage_properties(share, "iris.csv")
expect_true(is.list(prop2) && !is_empty(prop2))
expect_identical(prop2$`content-type`, "text/csv")
prop3 <- get_storage_properties(share, "dir")
expect_true(is.list(prop3) && !is_empty(prop3))
})
test_that("ADLS property getters work",
{
expect_is(fs, "adls_filesystem")
prop1 <- get_storage_properties(fs)
expect_true(is.list(prop1) && !is_empty(prop1))
prop2 <- get_storage_properties(fs, "iris.csv")
expect_true(is.list(prop2) && !is_empty(prop2))
expect_identical(prop2$`content-type`, "text/csv")
prop3 <- get_storage_properties(fs, "dir")
expect_true(is.list(prop3) && !is_empty(prop3))
expect_type(get_adls_file_acl(fs, "iris.csv"), "character")
stat <- get_adls_file_status(fs, "iris.csv")
expect_true(is.list(stat) && !is_empty(stat))
})
teardown(
{
blconts <- list_storage_containers(bl)
lapply(blconts, delete_storage_container, confirm=FALSE)
flconts <- list_storage_containers(fl)
lapply(flconts, delete_storage_container, confirm=FALSE)
adconts <- list_storage_containers(ad)
lapply(adconts, delete_storage_container, confirm=FALSE)
})
|
baggedModel <- function(y, bootstrapped_series=bld.mbb.bootstrap(y, 100), fn=ets, ...) {
if(!is.function(fn)){
warning(paste0("Using character specification for `fn` is deprecated. Please use `fn = ", match.arg(fn,c("ets", "auto.arima")), "`."))
fn <- utils::getFromNamespace(match.arg(fn,c("ets", "auto.arima")), "forecast")
}
mod_boot <- lapply(bootstrapped_series, function(x) {
mod <- fn(x, ...)
})
out <- list()
out$y <- as.ts(y)
out$bootstrapped_series <- bootstrapped_series
out$models <- mod_boot
out$modelargs <- list(...)
fitted_boot <- lapply(out$models, fitted)
fitted_boot <- as.matrix(as.data.frame(fitted_boot))
out$fitted <- ts(apply(fitted_boot, 1, mean))
tsp(out$fitted) <- tsp(out$y)
out$residuals <- out$y - out$fitted
out$series <- deparse(substitute(y))
out$method <- "baggedModel"
out$call <- match.call()
return(structure(out, class = c("baggedModel")))
}
baggedETS <- function(y, bootstrapped_series=bld.mbb.bootstrap(y, 100), ...) {
out <- baggedModel(y, bootstrapped_series, fn = ets, ...)
class(out) <- c("baggedETS", class(out))
out
}
forecast.baggedModel <- function(object, h=ifelse(frequency(object$y) > 1, 2 * frequency(object$y), 10), ...) {
out <- list(
model = object, series = object$series, x = object$y, method = object$method, fitted = object$fitted,
residuals = object$residuals
)
tspx <- tsp(out$x)
forecasts_boot <- lapply(out$model$models, function(mod) {
if (inherits(mod, "ets")) {
forecast(mod, PI = FALSE, h = h, ...)$mean
} else {
forecast(mod, h = h, ...)$mean
}
})
forecasts_boot <- as.matrix(as.data.frame(forecasts_boot))
colnames(forecasts_boot) <- NULL
if (!is.null(tspx)) {
start.f <- tspx[2] + 1 / frequency(out$x)
} else {
start.f <- length(out$x) + 1
}
out$forecasts_boot <- forecasts_boot
out$mean <- ts(apply(forecasts_boot, 1, mean), frequency = frequency(out$x), start = start.f)
out$median <- ts(apply(forecasts_boot, 1, median))
out$lower <- ts(apply(forecasts_boot, 1, min))
out$upper <- ts(apply(forecasts_boot, 1, max))
out$level <- 100
tsp(out$median) <- tsp(out$lower) <- tsp(out$upper) <- tsp(out$mean)
class(out) <- "forecast"
out
}
print.baggedModel <- function(x, digits = max(3, getOption("digits") - 3), ...) {
cat("Series:", x$series, "\n")
cat("Model: ", x$method, "\n")
cat("Call: ")
print(x$call)
invisible(x)
}
is.baggedModel <- function(x) {
inherits(x, "baggedModel")
}
|
library(gplots)
options(max.print=1000000)
dd <- read.delim("C:\\Users\\junior\\Downloads\\rpkm-50.txt",sep="\t",header=TRUE,dec=".",stringsAsFactors = FALSE,strip.white = TRUE)
x <- as.matrix(dd)
rc <- rainbow(nrow(x), start=0, end=.3)
cc <- rainbow(ncol(x), start=0, end=.3)
hr <- hclust(as.dist(1-cor(t(x), method="spearman")), method="complete")
hc <- hclust(as.dist(1-cor(x, method="spearman")), method="complete")
heatmap.2(x, col=bluered(75), Colv=as.dendrogram(hc), Rowv=as.dendrogram(hr), scale="row", key=T, keysize=1.5,density.info="none", trace="none",cexCol=0.9, cexRow=0.9,labRow=NA, dendrogram="both")
library(heatmaply)
heatmaply(x, color=bluered(75),
Colv=as.dendrogram(hc), Rowv=as.dendrogram(hr),
k_col = 2, k_row = 2,
scale="row", row_dend_left = TRUE,
dendrogram="both")
|
isStringVectorOrNull <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) {
checkarg(argument, "S", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = NA, naAllowed = FALSE, emptyStringAllowed = TRUE, message = message, argumentName = argumentName)
}
|
par.eCAR.Leroux <- function(y,x,W,E=NULL,C=NULL,model="Gaussian",
joint_prior_lamx_lamz = FALSE,
lamx.fix.val = NULL, sig2x.fix.val = NULL,
m=0,s2=10,alamx=1,blamx=1,alamz=1,blamz=1,
asig=1,bsig=1,atau=1,btau=1,asigx=1,bsigx=1,
mb0=0,s2b0=100,me=0,s2e=100,mx=0, s2x=100,
tau_cand_sd=1, sig2_cand_sd=1,
draws=10000,burn=5000,thin=5, verbose=TRUE){
emp.hpd <- function(x, conf=0.95){
conf <- min(conf, 1-conf)
n <- length(x)
nn <- round( n*conf )
x <- sort(x)
xx <- x[ (n-nn+1):n ] - x[1:nn]
m <- min(xx)
nnn <- which(xx==m)[1]
return( c( x[ nnn ], x[ n-nn+nnn ] ) )
}
cat("A", model, "model is being fit \n")
out <- NULL
nout <- (draws-burn)/thin
nobs <- length(y)
M <- diag(apply(W,1,sum))
R <- M-W
eigendec.R <- eigen(R)
evals <- eigendec.R$values
evecs <- eigendec.R$vectors
ystar <- t(evecs) %*% y
xstar <- t(evecs) %*% x
ncov <- ncol(C)
if(is.null(C)){
ncov <- 0
C <- 0
Cstar <- 0
} else {
Cstar <- t(evecs) %*% as.matrix(C)
}
updateXparms <- FALSE
if(is.null(lamx.fix.val) | is.null(sig2x.fix.val)){
updateXparms <- TRUE
sig2x.fix.val <- 1
lamx.fix.val <- 0.5
}
modelPriors = c(m, s2, alamx, blamx, alamz, blamz, asig, bsig,
atau, btau, asigx, bsigx, mb0, s2b0, me, s2e, mx, s2x)
MHsd <- c(tau_cand_sd, sig2_cand_sd)
beta0 <- beta <- alpha <- tau <- sig2 <- rep(1, nout)
sig2x <- rep(sig2x.fix.val,nout)
lamx <- lamz <- rep(lamx.fix.val, nout)
theta <- nb_r <- matrix(0, nrow=nout, ncol=nobs)
eta <- matrix(0, nrow=nout, ncol=ncov)
if(model=="Gaussian"){
ystar <- ystar - mean(ystar)
xstar <- xstar - mean(xstar)
C.out <- .C("mcmcloop_leroux_gauss",
as.integer(draws), as.integer(burn), as.integer(thin),
as.integer(nobs), as.double(ystar), as.double(xstar),
as.double(evals), as.double(t(Cstar)), as.integer(ncov),
as.double(modelPriors), as.double(MHsd),
as.integer(verbose), as.integer(joint_prior_lamx_lamz),
as.integer(updateXparms),
beta.out=as.double(beta), alpha.out=as.double(alpha),
tau.out=as.double(tau), sig2x.out=as.double(sig2x),
lamx.out=as.double(lamx), lamz.out=as.double(lamz),
sig2.out=as.double(sig2), eta.out=as.double(eta))
}
if(model!="Gaussian"){
if(model == "Poisson") modelnum = 1
if(model == "Binomial") modelnum = 2
if(model == "Negative Binomial") modelnum = 3
C.out <- .C("mcmcloop_leroux_GLM",
as.integer(draws), as.integer(burn), as.integer(thin),
as.integer(nobs), as.double(y), as.double(x), as.double(E),
as.double(evals), as.double(t(evecs)),
as.double(t(W)), as.double(t(C)), as.integer(ncov),
as.integer(modelnum), as.double(modelPriors),
as.double(MHsd), as.integer(verbose),
as.integer(joint_prior_lamx_lamz),
as.integer(updateXparms),
beta.out=as.double(beta), alpha.out=as.double(alpha),
tau.out=as.double(tau), sig2x.out=as.double(sig2x),
lamx.out=as.double(lamx), lamz.out=as.double(lamz),
theta.out=as.double(theta), beta0.out=as.double(beta0),
eta.out=as.double(eta), r.out=as.double(nb_r))
}
out$beta <- matrix(C.out$beta.out, nrow=nout, byrow=TRUE)
out$gamma <- matrix(C.out$alpha.out, nrow=nout, byrow=TRUE)
out$tau <- matrix(C.out$tau.out, nrow=nout, byrow=TRUE)
out$sig2x <- matrix(C.out$sig2x.out, nrow=nout, byrow=TRUE)
out$lamx <- matrix(C.out$lamx.out, nrow=nout, byrow=TRUE)
out$lamz <- matrix(C.out$lamz.out, nrow=nout, byrow=TRUE)
if(model=="Gaussian") out$sig2 <- matrix(C.out$sig2.out, nrow=nout, byrow=TRUE)
out$rho <- matrix((out$gamma*sqrt(out$sig2x))/sqrt(out$tau + out$gamma^2*out$sig2x), nrow=nout, byrow=TRUE)
out$sig2z <- matrix(out$tau + out$gamma^2*out$sig2x, nrow=nout, byrow=TRUE)
if(model!="Gaussian"){
out$theta <- matrix(C.out$theta.out, nrow=nout, byrow=TRUE)
out$beta0 <- matrix(C.out$beta0.out, nrow=nout, byrow=TRUE)
}
if(ncov>0) out$eta <- matrix(C.out$eta.out, nrow=nout, byrow=TRUE)
if(model=="Negative Binomial") out$nb_r = matrix(C.out$r.out, nrow=nout, byrow=TRUE)
Dseq <- seq(min(evals), max(evals), length=1000)
c.beta <- matrix(NA, nrow=nout, ncol=length(Dseq))
for(t in 1:nout){
c.beta[t,] <- out$beta[t] + out$gamma[t]*sqrt((1-out$lamx[t]+out$lamx[t]*Dseq)/(1-out$lamz[t]+out$lamz[t]*Dseq))
}
if(model=="Gaussian"){
beta.mn <- matrix(apply(c.beta,2,function(x) mean(x)),nrow=1000,byrow=TRUE)
beta.q025 <- matrix(apply(c.beta,2,function(x) emp.hpd(x))[1,],nrow=1000,byrow=TRUE)
beta.q975 <- matrix(apply(c.beta,2,function(x) emp.hpd(x))[2,],nrow=1000,byrow=TRUE)
}
if(model!="Gaussian"){
beta.mn <- matrix(apply(exp(c.beta),2,function(x) mean(x)),nrow=1000,byrow=TRUE)
beta.q025 <- matrix(apply(exp(c.beta),2,function(x) emp.hpd(x))[1,],nrow=1000,byrow=TRUE)
beta.q975 <- matrix(apply(exp(c.beta),2,function(x) emp.hpd(x))[2,],nrow=1000,byrow=TRUE)
}
omega <- Dseq
result <- eCAR.out(data_model = model,
beta_omega = cbind(beta.mn, beta.q025, beta.q975, omega),
posterior_draws = out,
DIC=NULL,
regrcoef = NULL)
return(result)
}
|
library(magick)
library(dplyr)
library(ggplot2)
library(camcorder)
gg_record(dir = "genuary/2022/genuary-temp", device = "png", width = 6.5, height = 10, units = "in", dpi = 320)
path <- here::here("mitosis", "original", "georgios.jpg")
img <- image_read(path)
h = image_info(img)$height
w = image_info(img)$width
r = 300
nx = round(w / r)
ny = round(h / r)
blocks <- expand.grid(
x = seq(0, w - 2 * r, length.out = nx),
y = seq(0, h - 2 * r, length.out = ny)
) %>%
rowwise() %>%
mutate(
xy = paste0(x, "+", y),
img = list(image_crop(img, geometry_area(r * 2, r * 2, x, y)))
) %>%
ungroup()
img_list <- image_join(blocks$img)
final <- image_montage(img_list, paste0("x", r, "+0+0"), tile = paste0(nx, "x", ny))
img <- final %>%
image_convert(colorspace = "gray")
img_w <- image_info(img)$width
img_h <- image_info(img)$height
img_ratio <- img_w / img_h
if (img_w >= img_h) {
img <- image_resize(img, "300")
} else {
img <- image_resize(img, ("x300"))
}
img_array <- drop(as.integer(img[[1]]))
rownames(img_array) <- 1:nrow(img_array)
colnames(img_array) <- 1:ncol(img_array)
threshold <- 0.5
img_df <- as.data.frame.table(img_array) %>%
`colnames<-`(c("y", "x", "b")) %>%
mutate(
across(everything(), as.numeric),
bf = 1 - b / 255
) %>%
arrange(y, x) %>%
filter(bf > threshold)
ggplot(img_df) +
geom_point(aes(x, -y, color = bf), size = 0.5) +
scale_color_gradient2() +
coord_cartesian(expand = FALSE) +
theme_void() +
theme(
legend.position = "none",
plot.background = element_rect(fill = "grey97", color = NA)
)
|
library(knotR)
filename <- "k12a_0614.svg"
a <- reader(filename)
xver <- c(10,23)
ouk12 <-
matrix(c(
15,1,
2,14,
21,3,
4,10,
19,5,
6,18,
10,7,
8,22,
23,9,
11,20,
17,12,
13,16
),byrow=TRUE,ncol=2)
symk11 <- symmetry_object(a, Mver=NULL, xver=xver)
a <- symmetrize(as.minobj(a),symk11)
knotplot(a,ouk12)
stop()
jj <- knotoptim(filename,
symobj = symk11,
ou = ouk11,
prob = 0,
iterlim=1000, print.level=2
)
write_svg(jj,filename,safe=FALSE)
dput(jj,file=sub('.svg','.S',filename))
|
pvisual <- function(x, K, m=20, N=10000, type="scenario3", xp=1, target=1, upper.tail=TRUE) {
freq <- get(type)(N=N, K=K, m=m, xp=xp, target=target)
if (upper.tail) {
sim <- vapply(x, function(y) sum(freq[as.numeric(names(freq)) >= y]), numeric(1))
return(cbind(x=x, "simulated"=sim, "binom"=1-pbinom(x-1, size=K, prob=1/m)))
} else {
sim <- vapply(x, function(y) sum(freq[as.numeric(names(freq)) < y]), numeric(1))
return(cbind(x=x, "simulated"=sim, "binom"= pbinom(x-1, size=K, prob=1/m)))
}
}
pickData <- function(m, xp=1, dataprob=NULL, nulls=NULL) {
probs <- runif(m)
n.targets = length(dataprob)
if (!is.null(dataprob)) {
probs[seq_len(n.targets)] <- dataprob
}
if (!is.null(nulls)) probs[(n.targets+1):m] <- nulls
ps <- (1-probs)^xp
if (all (ps==0)) ps <- rep(1, length(probs))
rbinom(1, size=1, prob=sum(ps[seq_len(n.targets)])/sum(ps))
}
scenario1 <- function(N, K, m = 20, xp=1, target=1) {
table(replicate(N, {
individual <- sum(replicate(K, pickData(m, dataprob=NULL, xp=xp)) %in% target)
individual
}))/N
}
scenario2 <- function(N, K, m = 20, xp=1, target=1) {
table(replicate(N, {
n.targets = length(target)
dataprob <- runif(n.targets)
individual <- sum(replicate(K, pickData(m, dataprob=dataprob, xp=xp) %in% target))
individual
}))/N
}
scenario3 <- function(N, K, m=20, xp=1, target=1) {
table(replicate(N/100,
replicate(100, {
n.targets = length(target)
dataprob <- runif(n.targets)
nulls <- runif(m-n.targets)
individual <- sum(replicate(K, pickData(m, dataprob=dataprob, nulls=nulls, xp=xp)) %in% target)
individual
})))/N
}
scenario4 <- function(N, K, m=20, xp=1, target=1) {
res <- replicate(N, {
n.targets = length(target)
dataprob <- runif(n.targets)
individual <- vapply(seq_along(K),
function(i) sum(replicate(K[i], pickData(m, dataprob=dataprob, nulls=runif(m-n.targets), xp=xp)) %in% target),
numeric(1))
sum(individual)
})
table(res)/N
}
|
"simndecay_gen" <-
function (kinpar, tmax, deltat, specpar=vector(), lmin, lmax, deltal,
sigma, irf = FALSE, irfpar = vector(), seqmod = FALSE, dispmu
= FALSE, nocolsums=FALSE,
disptau = FALSE, parmu = list(), partau = vector(), lambdac = 0,
fullk = FALSE, kmat = matrix(), jvec = vector(), specfun = "gaus",
nupow = 1, irffun = "gaus", kinscal = vector(),
lightregimespec = list(),
specdisp = FALSE, specdisppar=list(), parmufunc = "exp",
specdispindex = list(), amplitudes = vector(),specref=0,
fixedkmat=FALSE)
{
x <- seq(0, tmax, deltat)
nt <- length(x)
ncomp <- length(kinpar)
x2 <- seq(lmin, lmax, deltal)
nl <- length(x2)
if(specdisp){
EList <- list()
for (i in 1:nt) {
sp <- specparF(specpar = specpar,
xi = x[i],
i = i, specref = specref,
specdispindex = specdispindex,
specdisppar = specdisppar,
parmufunc = parmufunc)
EList[[i]] <- calcEhiergaus(sp, x2, nupow)
}
}
else
E2 <- calcEhiergaus(specpar, x2, nupow)
if (!(dispmu || disptau)) {
C2 <- compModel(k = kinpar, x = x, irfpar = irfpar, irf = irf,
seqmod = seqmod, fullk = fullk, kmat = kmat,
jvec = jvec,amplitudes = amplitudes,
lightregimespec = lightregimespec,
nocolsums= nocolsums, kinscal = kinscal,
fixedkmat=fixedkmat)
if(specdisp){
psisim <- matrix(nrow = nt, ncol = nl)
E2 <- EList[[1]]
for (i in 1:nt) {
psisim[i,] <- t(as.matrix(C2[i, ])) %*% t(EList[[i]])
}
}
else
psisim <- C2 %*% t(E2)
}
else {
psisim <- matrix(nrow = nt, ncol = nl)
for (i in 1:nl) {
irfvec <- irfparF(irfpar, lambdac, x2[i], i, dispmu,
parmu, disptau, partau, "", "", "gaus")
C2 <- compModel(k = kinpar, x = x, irfpar = irfpar, irf = irf,
seqmod = seqmod, fullk = fullk, kmat = kmat,
jvec = jvec,amplitudes = amplitudes,
lightregimespec = lightregimespec,
nocolsums= nocolsums, kinscal = kinscal,
fixedkmat=fixedkmat)
psisim[, i] <- C2 %*% cbind(E2[i, ])
}
}
dim(psisim) <- c(nt * nl, 1)
psi.df <- psisim + sigma * rnorm(nt * nl)
dim(psi.df) <- c(nt, nl)
kin(psi.df = psi.df, x = x, nt = nt, x2 = x2, nl = nl, C2 = C2,
E2 = E2, kinpar = kinpar, specpar = specpar,
seqmod = seqmod, irf = irf, irfpar = irfpar,
dispmu = dispmu, disptau = disptau, parmu = parmu, partau = partau,
lambdac = lambdac, simdata = TRUE, fullk = fullk, kmat = kmat,
jvec = jvec, fixedkmat=fixedkmat)
}
|
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(3.14159265358979, class = structure(\"3.14159265358979\", class = \"testit\")))"));
do.call(`is.logical`, argv);
}, o=expected);
|
afc.mm = function(obsv,fcst,mv=3,mf=3){
if (mf == 0) mf=mv
n.matrix = array(0,dim=c(mv,mf))
for (nn in 1:mv) for (mm in 1:mf){
n.matrix[nn,mm] = sum((obsv == nn) & (fcst == mm))
}
numer = 0
denom = 0
for (k in 1:(mv-1)) for (l in (k+1):mv){
term1 = 0
term2 = 0
for (i in 1:(mf-1)) for (j in (i+1):mf){
term1 = term1 + n.matrix[k,i]*n.matrix[l,j]
}
for (i in 1:mf){
term2 = term2 + n.matrix[k,i]*n.matrix[l,i]
}
numer = numer + term1 + 0.5*term2
denom = denom + sum(n.matrix[k,])*sum(n.matrix[l,])
}
p.afc = numer/denom
type.flag = 1
return(p.afc)
}
|
BiCopSelect <- function(u1, u2, familyset = NA, selectioncrit = "AIC",
indeptest = FALSE, level = 0.05, weights = NA,
rotations = TRUE, se = FALSE, presel = TRUE,
method = "mle") {
if (!(selectioncrit %in% c("AIC", "BIC", "logLik")))
stop("Selection criterion not implemented.")
if (presel)
todo_fams <- todo_fams_presel
args <- preproc(c(as.list(environment()), call = match.call()),
check_u,
remove_nas,
check_nobs,
check_if_01,
prep_familyset,
check_twoparams,
check_est_pars,
check_fam_tau,
todo_fams,
na.txt = " Only complete observations are used.")
list2env(args, environment())
p.value.indeptest <- BiCopIndTest(u1, u2)$p.value
if (indeptest & (p.value.indeptest >= level)) {
obj <- BiCop(0)
} else {
optiout <- list()
lls <- rep(Inf, length(familyset))
AICs <- rep(Inf, length(familyset))
BICs <- rep(Inf, length(familyset))
for (i in seq_along(familyset)) {
optiout[[i]] <- BiCopEst.intern(u1, u2,
family = familyset[i],
method = method,
se = se,
weights = weights,
as.BiCop = FALSE)
if (any(is.na(weights))) {
lls[i] <- sum(log(BiCopPDF(u1,
u2,
familyset[i],
optiout[[i]]$par,
optiout[[i]]$par2,
check.pars = FALSE)))
} else {
lls[i] <- sum(log(BiCopPDF(u1,
u2,
familyset[i],
optiout[[i]]$par,
optiout[[i]]$par2,
check.pars = FALSE)) %*% weights)
}
npars <- ifelse(familyset[i] %in% allfams[onepar], 1, 2)
if (familyset[i] == 0)
npars <- 0
AICs[i] <- -2 * lls[i] + 2 * npars
BICs[i] <- -2 * lls[i] + log(length(u1)) * npars
}
sel <- switch(selectioncrit,
"logLik" = which.max(lls),
"AIC" = which.min(AICs),
"BIC" = which.min(BICs))
obj <- BiCop(optiout[[sel]]$family,
optiout[[sel]]$par,
optiout[[sel]]$par2,
check.pars = FALSE)
}
if (obj$family == 0) {
if (se)
obj$se <- NA
obj$nobs <- length(u1)
obj$logLik <- 0
obj$AIC <- 0
obj$BIC <- 0
} else {
if (se) {
obj$se <- optiout[[sel]]$se
if (obj$family %in% allfams[twopar])
obj$se2 <- optiout[[sel]]$se2
}
obj$nobs <- length(u1)
obj$logLik <- lls[sel]
obj$AIC <- AICs[sel]
obj$BIC <- BICs[sel]
}
obj$emptau <- args$emp_tau
obj$p.value.indeptest <- p.value.indeptest
obj$call <- match.call()
obj
}
with_rotations <- function(nums) {
unique(unlist(lapply(nums, get_rotations)))
}
get_rotations <- function(fam) {
sgn <- sign(fam)
fam <- sgn * fam
if (fam %in% c(0, 1, 2, 5)) {
out <- fam
} else if (fam %in% c(3, 13, 23, 33)) {
out <- c(3, 13, 23, 33)
} else if(fam %in% c(4, 14, 24, 34)) {
out <- c(4, 14, 24, 34)
} else if(fam %in% c(6, 16, 26, 36)) {
out <- c(6, 16, 26, 36)
} else if(fam %in% c(7, 17, 27, 37)) {
out <- c(7, 17, 27, 37)
} else if(fam %in% c(8, 18, 28, 38)) {
out <- c(8, 18, 28, 38)
} else if(fam %in% c(9, 19, 29, 39)) {
out <- c(9, 19, 29, 39)
} else if(fam %in% c(10, 20, 30, 40)) {
out <- c(10, 20, 30, 40)
} else if(fam %in% c(104, 114, 124, 134)) {
out <- c(104, 114, 124, 134)
} else if(fam %in% c(204, 214, 224, 234)) {
out <- c(204, 214, 224, 234)
}
sgn * out
}
|
hedCreateTrans <- function(trans_df,
prop_id,
trans_id,
price,
date=NULL,
periodicity=NULL,
...){
if (!'hpidata' %in% class(trans_df)){
if (is.null(date)){
message('You must provide the name of a field with date of transaction (date=)')
stop()
}
if (is.null(periodicity)){
message('No periodicity (periodicity=) provided, defaulting to annual')
periodicity <- 'yearly'
}
trans_df <- dateToPeriod(trans_df=trans_df,
date=date,
periodicity=periodicity,
...)
}
if (!prop_id %in% names(trans_df)){
message('"prop_id" field not found')
stop()
}
if (!trans_id %in% names(trans_df)){
message('"trans_id" field not found')
stop()
}
if (!price %in% names(trans_df)){
message('"price" field not found')
stop()
}
hed_df <- trans_df %>%
dplyr::rename('prop_id' = prop_id,
'trans_id' = trans_id,
'price' = price) %>%
dplyr::arrange(prop_id, .data$trans_period, dplyr::desc(price)) %>%
dplyr::filter(!duplicated(paste0(prop_id, '_', .data$trans_period)))
attr(hed_df, 'period_table') <- attr(trans_df, 'period_table')
if (is.null(hed_df) | nrow(hed_df) == 0){
message('No Hedonic Sales Created\n')
return(NULL)
} else {
class(hed_df) <- c('heddata', 'hpidata', class(hed_df))
}
hed_df
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.