code
stringlengths 1
13.8M
|
---|
compareCluster <- function(geneClusters,
fun="enrichGO", data='',
source_from=NULL, ...) {
if(is.character(fun)){
if(fun %in% c("groupGO", "enrichGO", "enrichKEGG")){
fun <- utils::getFromNamespace(fun, "clusterProfiler")
} else if(fun %in% c("enrichDO", "enrichPathway")){
fun <- utils::getFromNamespace(fun , "DOSE")
} else {
source_env <- .GlobalEnv
if(!is.null(source_from)){
source_env <- loadNamespace(source_from)
}
fun <- get(fun, envir = source_env)
}
}
if (typeof(geneClusters) == 'language') {
if (!is.data.frame(data)) {
stop ('no data provided with formula for compareCluster')
} else {
genes.var = all.vars(geneClusters)[1]
n.var = length(all.vars(geneClusters))
grouping.formula = gsub('^.*~', '~',
as.character(as.expression(geneClusters)))
n.group.var = length(all.vars(formula(grouping.formula)))
geneClusters = dlply(.data=data, formula(grouping.formula),
.fun=function(x) {
if ( (n.var - n.group.var) == 1 ) {
as.character(x[[genes.var]])
} else if ( (n.var - n.group.var) == 2 ) {
fc.var = all.vars(geneClusters)[2]
geneList = structure(x[[fc.var]], names = x[[genes.var]])
sort(geneList, decreasing=TRUE)
} else {
stop('only Entrez~group or Entrez|logFC~group type formula is supported')
}
})
}
}
clProf <- llply(geneClusters,
.fun=function(i) {
x=suppressMessages(fun(i, ...))
if (inherits(x, c("enrichResult",
"groupGOResult", "gseaResult"))){
as.data.frame(x)
}
}
)
clusters.levels = names(geneClusters)
clProf.df <- ldply(clProf, rbind)
if (nrow(clProf.df) == 0) {
warning("No enrichment found in any of gene cluster, please check your input...")
return(NULL)
}
clProf.df <- plyr::rename(clProf.df, c(.id="Cluster"))
clProf.df$Cluster = factor(clProf.df$Cluster, levels=clusters.levels)
if (is.data.frame(data) && grepl('+', grouping.formula)) {
groupVarName <- strsplit(grouping.formula, split="\\+") %>% unlist %>%
gsub("~", "", .) %>% gsub("^\\s*", "", .) %>% gsub("\\s*$", "", .)
groupVars <- sapply(as.character(clProf.df$Cluster),
strsplit, split="\\.") %>% do.call(rbind, .)
for (i in seq_along(groupVarName)) {
clProf.df[, groupVarName[i]] <- groupVars[,i]
}
i <- which(colnames(clProf.df) %in% groupVarName)
j <- (1:ncol(clProf.df))[-c(1, i)]
clProf.df <- clProf.df[, c(1, i, j)]
}
res <- new("compareClusterResult",
compareClusterResult = clProf.df,
geneClusters = geneClusters,
.call = match.call(expand.dots=TRUE)
)
params <- modifyList(extract_params(args(fun)),
extract_params([email protected]))
keytype <- params[['keyType']]
if (is.null(keytype)) keytype <- "UNKNOWN"
readable <- params[['readable']]
if (length(readable) == 0) readable <- FALSE
res@keytype <- keytype
res@readable <- as.logical(readable)
res@fun <- params[['fun']] %||% 'enrichGO'
return(res)
}
extract_params <- function(x) {
y <- rlang::quo_text(x)
if (is.function(x)) y <- sub('\nNULL$', '', y)
y <- gsub('"', '', y) %>%
sub("[^\\(]+\\(", "", .) %>%
sub("\\)$", "", .) %>%
gsub("\\s+", "", .)
y <- strsplit(y, ",")[[1]]
params <- sub("=.*", "", y)
vals <- sub(".*=", "", y)
i <- params != vals
params <- params[i]
vals <- vals[i]
names(vals) <- params
return(as.list(vals))
}
setMethod("show", signature(object="compareClusterResult"),
function (object){
cmsg <- paste("T Wu, E Hu, S Xu, M Chen, P Guo, Z Dai, T Feng, L Zhou, ",
"W Tang, L Zhan, X Fu, S Liu, X Bo, and G Yu. ",
"clusterProfiler 4.0: A universal enrichment tool for interpreting omics data. ",
"The Innovation. 2021, 2(3):100141",
sep="\n", collapse="\n")
geneClusterLen <- length(object@geneClusters)
fun <- object@fun
result <- object@compareClusterResult
clusts <- split(result, result$Cluster)
nterms <- sapply(clusts, nrow)
cat("
cat("
cat("
str(object@geneClusters)
cat("
str(result)
cat("
for (i in seq_along(clusts)) {
cat("
}
cat("
citation_msg <- NULL
if (fun == "enrichDO" || fun == "enrichNCG") {
citation_msg <- paste(" Guangchuang Yu, Li-Gen Wang, Guang-Rong Yan, Qing-Yu He. DOSE: an",
" R/Bioconductor package for Disease Ontology Semantic and Enrichment",
" analysis. Bioinformatics 2015 31(4):608-609",
sep="\n", collapse="\n")
} else if (fun == "enrichPathway") {
citation_msg <- paste(" Guangchuang Yu, Qing-Yu He. ReactomePA: an R/Bioconductor package for",
" reactome pathway analysis and visualization. Molecular BioSystems",
" 2016, 12(2):477-479", sep="\n", collapse="\n")
}
if (!is.null(citation_msg)) {
cat(paste0("1.", citation_msg), "\n\n")
cat(paste0("2.", cmsg), "\n\n")
} else {
cat(cmsg, "\n\n")
}
})
setMethod("summary", signature(object="compareClusterResult"),
function(object, ...) {
warning("summary method to convert the object to data.frame is deprecated, please use as.data.frame instead.")
return(as.data.frame(object, ...))
}
)
merge_result <- function(enrichResultList) {
if ( !is(enrichResultList, "list")) {
stop("input should be a name list...")
}
if ( is.null(names(enrichResultList))) {
stop("input should be a name list...")
}
x <- lapply(enrichResultList, as.data.frame)
names(x) <- names(enrichResultList)
y <- ldply(x, "rbind")
y <- plyr::rename(y, c(.id="Cluster"))
y$Cluster = factor(y$Cluster, levels=names(enrichResultList))
new("compareClusterResult",
compareClusterResult = y)
} |
group.test <- function(Teste){
n <- nrow(Teste)
letras <- c(1:1000000)
w <- Teste[order(Teste[, 1], decreasing = TRUE), ]
M <- rep("", n)
k <- 1
aux <- cbind(w[, -1])
x <- apply(aux, 1, sum)
if (dim(aux)[2] == 1 & sum(aux) == n) {
aux3 <- aux
M <- rep("g1", n)
} else {
if (any(x == 0)) {
for (z in 1:n) {
s <- rep(0, n)
if (x[z] == 0) {
s[z] <- 1
aux <- cbind(aux, s)
}
}
}
pos1 <- aux[1, ] == 1
poscol1 <- which(pos1 == T)
aux1 <- cbind(aux[ , -poscol1])
numcol <- ncol(aux1)
ncont <- -1
for (j in 1:numcol) {
k <- 0
for (i in 1:n) {
if (aux1[i, j] ==0 ) {
k <- k + 1
}
if (aux1[i+1, j] == 1) break
}
ncont <- cbind(ncont,k)
}
aux2 <- aux1[, order(ncont[-1])]
aux3 <- cbind(aux[, poscol1], aux2)
a <- aux3[, 1]
for (i in 1:n) {
if (a[i] == 1) {
M[i] <- paste("g", letras[1], sep="")
} else {
M[i] <- M[i]
}
}
for (j in 2:(numcol+1)) {
for (i in 1:n) {
if (aux3[i, j] == 1) {
M[i] <- paste(M[i], letras[j], sep = "g")
} else {
M[i] <- M[i]
}
}
}
}
return(data.frame(Means = w[, 1], Groups = M))
}
group.test2 <- function(Teste) {
n <- nrow(Teste)
ordertest <- Teste[order(Teste[, 1], decreasing = TRUE), ]
letras <- c(1:1000000)
M <- rep("", n)
if (all(ordertest[, 2] == 1)) {
M <- rep("g1", n)
} else {
M[1] <- "g1"
j <- 2
for (i in 2:n) {
if (ordertest[i, 2] == ordertest[i-1, 2]) {
M[i] <- M[i-1]
} else {
M[i] <- paste(M[i], letras[j], sep = "g")
j <- j + 1
}
}
}
return(data.frame(Means = ordertest[, 1], Groups = M))
} |
magrittr::`%>%`
NULL
utils::globalVariables(c(
".",
"inner_join",
"mutate",
"select",
"rename",
"quo",
"UQ",
"quo_name",
"from_row",
"from_col",
"to_row",
"to_col",
"type",
"value",
"everything",
"data_type",
"is_na",
".value",
".data_type",
"n",
":=",
".partition",
"ns_env",
"corner_row",
"corner_col",
".boundary"
))
concatenate <- function(..., combine_factors = TRUE, fill_factor_na = TRUE) {
c.POSIXct <- function(..., recursive = FALSE) {
.POSIXct(c(unlist(lapply(list(...), unclass))), tz = "UTC")
}
dots <- (...)
dots_is_null <- purrr::map_lgl(dots, rlang::is_null)
if (all(dots_is_null)) {
return(dots)
}
dots_is_scalar_vector <- purrr::map_lgl(dots, rlang::is_scalar_vector)
if (any(!dots_is_scalar_vector[!dots_is_null])) {
return(dots)
}
classes <- purrr::map(dots, class)
if (length(unique(classes[!dots_is_null])) == 1L) {
all_classes <- classes[!dots_is_null][[1]]
first_class <- all_classes[1]
if (first_class %in% c("factor", "ordered")) {
if (combine_factors || fill_factor_na) {
dots[dots_is_null] <- list(factor(NA_character_))
}
if (combine_factors) {
return(forcats::fct_c(rlang::splice(dots)))
}
else {
return(dots)
}
} else {
NA_class_ <- NA
if (is.list(dots)) {
class(NA_class_) <- all_classes
dots[dots_is_null] <- list(NA_class_)
} else {
dots[dots_is_null] <- NA_class_
}
dots <- do.call(c, c(dots, use.names = FALSE))
class(dots) <- all_classes
return(dots)
}
}
dots[dots_is_null] <- NA
factors <- purrr::map_lgl(classes, ~ .[1] %in% c("factor", "ordered"))
dots[factors] <- purrr::map(dots[factors], as.character)
dates <- purrr::map_lgl(classes, ~ .[1] %in% c("Date", "POSIXct", "POSIXlt"))
dots[dates] <- purrr::map(dots[dates], format, justify = "none", trim = TRUE)
do.call(c, c(dots, use.names = FALSE))
}
na_types <- list(
logical = NA,
integer = NA_integer_,
double = NA_real_,
character = NA_character_,
complex = NA_complex_
)
na_of_type <- function(x) structure(na_types[[typeof(x)]], class = class(x))
maybe_format_list_element <- function(x, name, functions) {
func <- functions[[name]]
if (is.null(func)) func <- identity
func(x)
}
standardise_direction <- function(direction) {
stopifnot(length(direction) == 1L)
dictionary <-
c(`up-left` = "up-left", `up` = "up", `up-right` = "up-right",
`right-up` = "right-up", `right` = "right", `right-down` = "right-down",
`down-right` = "down-right", `down` = "down", `down-left` = "down-left",
`left-down` = "left-down", `left` = "left", `left-up` = "left-up",
`up-ish` = "up-ish", `right-ish` = "right-ish",
`down-ish` = "down-ish", `left-ish` = "left-ish",
NNW = "up-left", N = "up", NNE = "up-right",
ENE = "right-up", E = "right", ESE = "right-down",
SSE = "down-right", S = "down", SSW = "down-left",
WSW = "left-down", W = "left", WNW = "left-up",
ABOVE = "up-ish", RIGHT = "right-ish",
BELOW = "down-ish", LEFT = "left-ish")
if (direction %in% names(dictionary)) return(unname(dictionary[direction]))
stop("The direction \"", direction, "\" is not recognised. See ?directions.")
} |
multilocusTypes <- function(adata) {
checkForValidPPEDataset(adata)
numLoci <- attr(adata,"numLoci")
ploidy <- attr(adata,"ploidy")
dioecious <- attr(adata,"dioecious")
selfCompatible <- attr(adata,"selfCompatible")
progeny <- with(adata,id[!is.na(mother)])
allAdults <- with(adata,id[is.na(mother)])
progenyTypes <- list(); adultTypes <- list()
uniqueProgenyTypes <- list() ; uniqueAdultTypes <- list()
for (locus in 1:numLoci) {
affectedLocus <- paste("Locus",locus,sep="")
locusRange <- (3 + dioecious) + (locus-1)*ploidy + 1:ploidy
sTypes <- apply(adata[progeny,locusRange],
1,
function(vv) {
paste(stripNAs(vv),collapse=" ")})
aTypes <- apply(adata[allAdults,locusRange],
1,
function(vv) {
paste(stripNAs(vv),collapse=" ")})
progenyTypes[[affectedLocus]] <- sTypes
adultTypes[[affectedLocus]] <- aTypes
uniqueProgenyTypes[[affectedLocus]] <- table(sTypes[sTypes!=""])
uniqueAdultTypes[[affectedLocus]] <- table(aTypes[aTypes!=""])
}
numUniqueProgenyTypes <- sapply(uniqueProgenyTypes,length)
numUniqueAdultTypes <- sapply(uniqueAdultTypes,length)
progenyMLTypes <- do.call("paste",c(progenyTypes,sep=" | "))
names(progenyMLTypes) <- progeny
adultMLTypes <- do.call("paste",c(adultTypes,sep=" | "))
names(adultMLTypes) <- allAdults
uniqueProgenyMLTypes <- table(progenyMLTypes)
uniqueAdultMLTypes <- table(adultMLTypes)
numUniqueProgenyMLTypes <- length(uniqueProgenyMLTypes)
numUniqueAdultMLTypes <- length(uniqueAdultMLTypes)
cc <- utils::stack(lapply(uniqueProgenyTypes,as.vector))
nn <- utils::stack(lapply(uniqueProgenyTypes,names))
rm(uniqueProgenyTypes)
uniqueProgenyTypes <- data.frame(Locus=cc$ind,
progenyType=nn$values,
nIndividuals=cc$values)
cc <- utils::stack(lapply(uniqueAdultTypes,as.vector))
nn <- utils::stack(lapply(uniqueAdultTypes,names))
rm(uniqueAdultTypes)
uniqueAdultTypes <- data.frame(Locus=cc$ind,
adultType=nn$values,
nIndividuals=cc$values)
tt <- strsplit(names(uniqueProgenyMLTypes),split=" | ",fixed=TRUE)
tt <- lapply(tt,
function(vv){
if (length(vv) < numLoci) {
return(c(vv,""))
} else {
return(vv)
}
})
tt <- as.data.frame(do.call(rbind,tt))
uniqueProgenyMLTypes <- cbind(tt,uniqueProgenyMLTypes)
names(uniqueProgenyMLTypes) <- c(paste("Locus",1:numLoci,sep=""),
"progenyMLType","Freq")
tt <- strsplit(names(uniqueAdultMLTypes),split=" | ",fixed=TRUE)
tt <- lapply(tt,
function(vv){
if (length(vv) < numLoci) {
return(c(vv,""))
} else {
return(vv)
}
})
tt <- as.data.frame(do.call(rbind,tt))
uniqueAdultMLTypes <- cbind(tt,uniqueAdultMLTypes)
names(uniqueAdultMLTypes) <- c(paste("Locus",1:numLoci,sep=""),
"adultMLType","Freq")
alleleSets <- data.frame(row.names=rownames(adata))
for (locus in 1:numLoci) {
locusRange <- (3 + dioecious) + (locus-1)*ploidy + 1:ploidy
alleleSets[[locus]] <- apply(adata[,locusRange],
1,
function(vv) {
paste(stripNAs(vv),collapse=" ")})
}
names(alleleSets) <- c(paste("Locus",1:numLoci,sep=""))
alleleSets$allMLTypes <- apply(alleleSets,1,
function(vv){
paste(
paste(
paste("Locus",1:numLoci,sep=""),
vv),
collapse=" - ")
})
alleleSets <- cbind(adata[,1:(3+dioecious)],alleleSets)
return(list(uniqueProgenyTypes=uniqueProgenyTypes,
numUniqueProgenyTypes=numUniqueProgenyTypes,
uniqueAdultTypes=uniqueAdultTypes,
numUniqueAdultTypes=numUniqueAdultTypes,
uniqueProgenyMLTypes=uniqueProgenyMLTypes,
numUniqueProgenyMLTypes=numUniqueProgenyMLTypes,
uniqueAdultMLTypes=uniqueAdultMLTypes,
numUniqueAdultMLTypes=numUniqueAdultMLTypes))
} |
raptor = function(stop_times,
transfers,
stop_ids,
arrival = FALSE,
time_range = 3600,
max_transfers = NULL,
keep = "all") {
from_stop_id <- departure_time_num <- marked <- journey_departure_time <- from_stop_id <- NULL
wait_time_to_departure <- marked_departure_time_num <- arrival_time_num <- min_transfer_time <- NULL
to_stop_id <- travel_time <- journey_arrival_time <- trnsfrs_from_stop_id <- NULL
if(!is.character(stop_ids) && !is.null(stop_ids)) {
stop("stop_ids must be a character vector (or NULL)")
}
stop_times_dt <- as.data.table(stop_times)
stop_times_dt <- setup_stop_times(stop_times_dt, reverse = arrival)
transfers_dt <- as.data.table(transfers)
transfers_dt <- setup_transfers(transfers_dt)
from_stop_ids = stop_ids
nonexistent_stop_ids = setdiff(from_stop_ids, c(stop_times_dt$to_stop_id,
transfers_dt$trnsfrs_from_stop_id, transfers_dt$trnsfrs_to_stop_id))
if(length(nonexistent_stop_ids) > 0) {
from_stop_ids <- setdiff(from_stop_ids, nonexistent_stop_ids)
if(length(from_stop_ids) == 0) {
warning("Stop not found in stop_times or transfers: ", paste(nonexistent_stop_ids, collapse = ", "))
empty_dt = data.table(from_stop_id = character(0), to_stop_id = character(0), travel_time = numeric(0),
journey_departure_time = numeric(0), journey_arrival_time = character(0), transfers = numeric(0))
return(empty_dt)
}
}
if(is.null(keep) ||
!(keep %in% c("shortest", "earliest", "all", "latest"))) {
stop(paste0(keep, " is not a supported optimization type, use one of: all, shortest, earliest, latest"))
}
if(!is.numeric(time_range)) {
stop("time_range is not numeric. Needs to be the time range in seconds after the first departure of stop_times")
}
if(time_range < 1) {
stop("time_range is less than 1")
}
min_departure_time = min(stop_times_dt$departure_time_num)
max_departure_time = min_departure_time + time_range
if(is.null(max_transfers)) {
max_transfers <- 999999
} else if(max_transfers < 0) {
stop("max_transfers is less than 0")
}
transfer_stops = data.frame()
if(!is.null(transfers_dt) && max_transfers > 0) {
transfer_stops <- transfers_dt[trnsfrs_from_stop_id %in% from_stop_ids]
}
rptr_colnames = c("to_stop_id", "marked", "journey_arrival_time", "journey_departure_time", "from_stop_id", "transfers")
init_stops = data.table(
to_stop_id = c(from_stop_ids, transfer_stops$trnsfrs_to_stop_id),
marked = F,
journey_arrival_time = c(rep(min_departure_time, length(from_stop_ids)),
min_departure_time+transfer_stops$min_transfer_time),
journey_departure_time = rep(min_departure_time,
length(from_stop_ids)+nrow(transfer_stops)),
from_stop_id = c(from_stop_ids, transfer_stops$trnsfrs_from_stop_id),
transfers = c(rep(0, length(from_stop_ids)), rep(1, nrow(transfer_stops)))
)
init_departures = stop_times_dt[init_stops, on = "to_stop_id"]
init_departures[, journey_departure_time := departure_time_num]
init_departures <- init_departures[!is.na(journey_departure_time)]
init_departures[, journey_arrival_time := journey_departure_time ]
init_departures[, from_stop_id := to_stop_id]
init_departures[, marked := TRUE]
init_departures[, transfers := 0]
init_departures <- init_departures[, rptr_colnames, with = F]
rptr <- rbind(init_stops, init_departures)
rptr <- rptr[, rptr_colnames, with = F]
rptr <- distinct(rptr)
rptr[, journey_arrival_time := journey_arrival_time-1]
rptr <- rptr[journey_departure_time <= max_departure_time]
k = 0
while(any(rptr$marked)) {
rptr_marked <- rptr[marked == TRUE]
rptr[,marked := FALSE]
setkey(rptr_marked, to_stop_id)
departures_marked = stop_times_dt[rptr_marked, on = "to_stop_id", allow.cartesian = TRUE]
departures_marked <- departures_marked[departure_time_num > journey_arrival_time,]
departures_marked[,wait_time_to_departure := departure_time_num - journey_departure_time]
setorder(departures_marked, wait_time_to_departure)
departures_marked <- departures_marked[, .SD[1], by=c("to_stop_id", "trip_id")]
setorder(departures_marked, departure_time_num)
trips_marked <- departures_marked[, .SD[1], by=c("trip_id", "journey_departure_time")]
trips_marked <- trips_marked[, c("trip_id", "to_stop_id", "departure_time_num", "journey_departure_time", "from_stop_id")]
setnames(trips_marked, c("trip_id", "departure_time_num"), c("trip_id", "marked_departure_time_num"))
setkey(trips_marked, trip_id)
arrival_candidates = stop_times_dt[trips_marked, on = "trip_id", allow.cartesian = TRUE]
arrival_candidates[, transfers := k]
arrival_candidates <- arrival_candidates[departure_time_num > marked_departure_time_num]
setkey(arrival_candidates, to_stop_id)
if(nrow(arrival_candidates) == 0) { break }
arrival_candidates[,marked := TRUE]
arrival_candidates[,journey_arrival_time := arrival_time_num]
arrival_candidates <- arrival_candidates[, rptr_colnames, with = F]
if(!is.null(transfers_dt) && (k+1) <= max_transfers) {
transfer_candidates = merge(
arrival_candidates,
transfers_dt,
by.x = "to_stop_id",
by.y = "trnsfrs_from_stop_id",
allow.cartesian = TRUE
)
transfer_candidates[, to_stop_id := NULL]
setnames(transfer_candidates, old = "trnsfrs_to_stop_id", new = "to_stop_id")
transfer_candidates[,journey_arrival_time := (journey_arrival_time + min_transfer_time)]
transfer_candidates[,transfers := k+1]
transfer_candidates <- transfer_candidates[, rptr_colnames, with = F]
arrival_candidates <- rbindlist(list(arrival_candidates, transfer_candidates), use.names = F)
}
rptr <- rbindlist(list(rptr, arrival_candidates), use.names = F)
setorder(rptr, journey_arrival_time)
rptr <- rptr[, .SD[1], by = c("to_stop_id", "journey_departure_time")]
rptr <- rptr[, rptr_colnames, with = F]
k <- k+1
if(k > max_transfers) { break }
}
rptr[to_stop_id %in% init_stops$to_stop_id, journey_arrival_time := journey_arrival_time + 1]
rptr <- rptr[!to_stop_id %in% init_stops$to_stop_id]
rptr <- rbind(init_stops, rptr)
rptr[,travel_time := journey_arrival_time - journey_departure_time]
if(arrival) {
max_time = 604800
arrival_tmp = max_time - rptr$journey_arrival_time
rptr[,journey_arrival_time := (max_time - journey_departure_time)]
rptr[,journey_departure_time := arrival_tmp]
stop_tmp = rptr$to_stop_id
rptr[,to_stop_id := from_stop_id]
rptr[,from_stop_id := stop_tmp]
}
keep_by = ifelse(arrival, "from_stop_id", "to_stop_id")
if(keep == "shortest") {
setorder(rptr, travel_time, journey_arrival_time)
rptr <- rptr[, .SD[1], by = keep_by]
} else if(keep == "earliest") {
setorder(rptr, journey_arrival_time, travel_time)
rptr <- rptr[, .SD[1], by = keep_by]
} else if(keep == "latest") {
setorder(rptr, -journey_arrival_time, travel_time)
rptr <- rptr[, .SD[1], by = keep_by]
}
rptr <- rptr[, c("from_stop_id", "to_stop_id", "travel_time",
"journey_departure_time", "journey_arrival_time", "transfers")]
return(rptr)
}
travel_times = function(filtered_stop_times,
stop_name,
time_range = 3600,
arrival = FALSE,
max_transfers = NULL,
max_departure_time = NULL,
return_coords = FALSE,
return_DT = FALSE,
stop_dist_check = 300) {
travel_time <- journey_arrival_time <- journey_departure_time <- NULL
stop_names = stop_name; rm(stop_name)
if("tidygtfs" %in% class(filtered_stop_times)) {
gtfs_obj = filtered_stop_times
if(is.null(attributes(gtfs_obj$stop_times)$extract_date)) {
stop("Travel times cannot be calculated on an unfiltered tidygtfs object. Use filter_feed_by_date().")
}
filtered_stop_times <- gtfs_obj$stop_times
transfers = gtfs_obj$transfers
stops = stops_as_dt(gtfs_obj$stops)
} else {
if(!all(c("stops", "transfers") %in% names(attributes(filtered_stop_times)))) {
stop("Stops and transfers not found in filtered_stop_times attributes. Use filter_stop_times() to prepare data or use raptor() for lower level access.")
}
transfers = attributes(filtered_stop_times)$transfers
stops = attributes(filtered_stop_times)$stops
}
if(!is.null(max_departure_time) && !arrival) {
if(!missing(time_range)) {
stop("time_range and max_departure_time are set. Only one of them is allowed.")
}
if(is.character(max_departure_time)) {
max_departure_time <- hhmmss_to_seconds(max_departure_time)
}
min_departure_time = min(filtered_stop_times$departure_time_num)
stopifnot(max_departure_time > min_departure_time)
time_range <- max_departure_time - min_departure_time
}
stop_ids = stops$stop_id[which(stops$stop_name %in% stop_names)]
if(length(stop_ids) == 0) {
stop(paste0("Stop name '", stop_names, "' not found in stops table"))
}
if(length(stop_ids) > 1 & !is.null(stop_dist_check) & !isFALSE(stop_dist_check)) {
stop_dists = stop_group_distances(stops, "stop_name")
if(max(stop_dists$dist_max) > stop_dist_check) {
stop("Some stops with the same name are more than ", stop_dist_check, " meters apart, see stop_group_distances().\n",
"Using travel_times() might lead to unexpected results. Set stop_dist_check=FALSE to ignore this error.")
}
}
rptr = raptor(stop_times = filtered_stop_times,
transfers = transfers,
stop_ids = stop_ids,
max_transfers = max_transfers,
arrival = arrival,
time_range = time_range,
keep = "shortest")
.select_stops = function(prefix) {
x = stops[,paste0("stop_", c("name", "id", "lon", "lat"))[1:data.table::fifelse(return_coords, 4, 2)], with=FALSE]
colnames(x) <- paste0(prefix, colnames(x))
return(x)
}
rptr_names = merge(.select_stops("from_"), rptr, by = "from_stop_id")
rptr_names <- merge(.select_stops("to_"), rptr_names, by = "to_stop_id")
keep_by = ifelse(arrival, "from_stop_name", "to_stop_name")
setorder(rptr_names, travel_time)
rptr_names <- rptr_names[, .SD[1], by = keep_by]
rptr_names[,journey_arrival_time := hms::hms(journey_arrival_time)]
rptr_names[,journey_departure_time := hms::hms(journey_departure_time)]
rptr_names <- rptr_names[,c("from_stop_name", "to_stop_name",
"travel_time", "journey_departure_time",
"journey_arrival_time", "transfers",
"from_stop_id", "to_stop_id",
"from_stop_lon", "from_stop_lat",
"to_stop_lon", "to_stop_lat")[1:data.table::fifelse(return_coords,12,8)],
with = FALSE]
if(!return_DT) {
rptr_names <- dplyr::as_tibble(rptr_names)
}
return(rptr_names)
}
filter_stop_times = function(gtfs_obj,
extract_date,
min_departure_time,
max_arrival_time) {
departure_time_num <- arrival_time_num <- NULL
if(is.character(extract_date)) {
extract_date <- as.Date(extract_date)
}
if(missing(min_departure_time)) {
min_departure_time <- 0
} else if(is.character(min_departure_time)) {
min_departure_time <- hhmmss_to_seconds(min_departure_time)
}
if(missing(max_arrival_time)) {
max_arrival_time <- max(gtfs_obj$stop_times$arrival_time)+1
} else if(is.character(max_arrival_time)) {
max_arrival_time <- hhmmss_to_seconds(max_arrival_time)
}
min_departure_time <- as.numeric(min_departure_time)
max_arrival_time <- as.numeric(max_arrival_time)
if(max_arrival_time <= min_departure_time) {
stop("max_arrival_time is before min_departure_time")
}
service_ids = filter(gtfs_obj$.$dates_services, date == extract_date)
if(nrow(service_ids) == 0) {
stop(paste0("No stop_times on ", extract_date))
}
trip_ids = inner_join(gtfs_obj$trips, service_ids, by = "service_id")
trip_ids <- unique(trip_ids$trip_id)
stop_times_dt <- as.data.table(gtfs_obj$stop_times)
setkey(stop_times_dt, trip_id)
set_num_times(stop_times_dt)
stop_times_dt <- stop_times_dt[trip_id %in% trip_ids,]
stop_times_dt <- stop_times_dt[departure_time_num >= min_departure_time &
arrival_time_num <= max_arrival_time,]
setindex(stop_times_dt, "stop_id")
if(nrow(stop_times_dt) == 0) {
stop("No stop times between min_departure_time and max_arrival_time")
}
attributes(stop_times_dt)$stops <- stops_as_dt(gtfs_obj$stops)
attributes(stop_times_dt)$transfers <- gtfs_obj$transfers
attributes(stop_times_dt)$extract_date <- extract_date
attributes(stop_times_dt)$min_departure_time <- min_departure_time
attributes(stop_times_dt)$max_arrival_time <- max_arrival_time
return(stop_times_dt)
}
stops_as_dt = function(gtfs_stops) {
stops_dt = as.data.table(gtfs_stops)
stops_dt <- stops_dt[,c("stop_id", "stop_name", "stop_lon", "stop_lat")]
setkey(stops_dt, "stop_id")
setindex(stops_dt, "stop_name")
stops_dt
}
setup_stop_times = function(stop_times, reverse = FALSE) {
arrival_time_num <- departure_time_num <- NULL
stopifnot(is.data.table(stop_times))
set_num_times(stop_times)
setnames(x = stop_times, new = "to_stop_id", old = "stop_id")
if(reverse) {
max_time = 604800
arrival_time_tmp = stop_times$arrival_time_num
stop_times[, arrival_time_num := (max_time - departure_time_num)]
stop_times[, departure_time_num := (max_time - arrival_time_tmp)]
}
if(is.null(key(stop_times)) || "trip_id" != key(stop_times)) {
setkeyv(stop_times, "trip_id")
}
if(is.null(indices(stop_times)) || !("stop_id" %in% indices(stop_times))) {
setindex(stop_times, "to_stop_id")
}
return(stop_times)
}
setup_transfers = function(transfers) {
stopifnot(is.data.table(transfers))
transfer_type <- min_transfer_time <- trnsfrs_from_stop_id <- trnsfrs_to_stop_id <- NULL
if(is.null(transfers) || nrow(transfers) == 0) {
return(NULL)
}
if(!"trnsfrs_from_stop_id" %in% colnames(transfers)) {
setnames(x = transfers, new = "trnsfrs_from_stop_id", old = "from_stop_id")
}
if(!"trnsfrs_to_stop_id" %in% colnames(transfers)) {
setnames(x = transfers, new = "trnsfrs_to_stop_id", old = "to_stop_id")
}
transfers <- transfers[transfer_type != "3"]
transfers[is.na(min_transfer_time), min_transfer_time := 0]
setkey(transfers, "trnsfrs_from_stop_id")
return(transfers)
}
set_num_times = function(stop_times_dt) {
arrival_time <- arrival_time_num <- departure_time <- departure_time_num <- NULL
stopifnot(is.data.table(stop_times_dt))
if(all(c("arrival_time_num", "departure_time_num") %in% colnames(stop_times_dt))) {
return(invisible(stop_times_dt))
}
stop_times_dt[,arrival_time_num := as.numeric(arrival_time)]
stop_times_dt[,departure_time_num := as.numeric(departure_time)]
invisible(stop_times_dt)
} |
set_couleur_saphirs <-
function(map,colEntree="
{
msg_error1<-msg_error2<-msg_error3<-msg_error4<-msg_error5 <- NULL
if(any(!any(class(map) %in% "leaflet"), !any(class(map) %in% "htmlwidget"))) if(!any(class(map) %in% "leaflet_proxy")) msg_error1 <- "La carte doit etre un objet leaflet ou leaflet_proxy / "
if(any(class(colEntree)!="character")) msg_error2 <- "La couleur doit etre de type caractere (nommee ou hexadecimal) / "
if(any(class(colSortie)!="character")) msg_error3 <- "La couleur doit etre de type caractere (nommee ou hexadecimal) / "
if(any(class(colBorder)!="character")) msg_error4 <- "La couleur de la bordure doit etre de type caractere (nommee ou hexadecimal) / "
if(!is.null(map_leaflet)) if (any(!any(class(map_leaflet) %in% "leaflet"), !any(class(map_leaflet) %in% "htmlwidget"))) msg_error5 <- "La carte doit etre un objet leaflet / "
if(any(!is.null(msg_error1),!is.null(msg_error2),!is.null(msg_error3),!is.null(msg_error4),!is.null(msg_error5)))
{
stop(simpleError(paste0(msg_error1,msg_error2,msg_error3,msg_error4,msg_error5)))
}
if(!is.null(map_leaflet))
{
map_proxy <- map
map <- map_leaflet
}
idx_fleche <- NULL
idx_legende <- NULL
for(i in 1:length(map$x$calls))
{
if(map$x$calls[[i]]$method %in% "addPolygons")
{
if(map$x$calls[[i]]$args[[2]]$nom_fond=="fond_flux") idx_fleche <- i
if(map$x$calls[[i]]$args[[2]]$nom_fond=="fond_flux_leg") idx_legende <- i
}
}
if(is.null(map_leaflet))
{
val_ent <- which(as.numeric(str_replace_all(substring(map$x$calls[[idx_fleche]]$args[[5]],str_locate(map$x$calls[[idx_fleche]]$args[[5]],":")[[1]]+2,nchar(map$x$calls[[idx_fleche]]$args[[5]])-11)," ",""))>=0)
if(length(val_ent)>0)
{
map$x$calls[[idx_fleche]]$args[[4]]$fillColor[1:length(val_ent)] <- colEntree
}
val_sor <- which(as.numeric(str_replace_all(substring(map$x$calls[[idx_fleche]]$args[[5]],str_locate(map$x$calls[[idx_fleche]]$args[[5]],":")[[1]]+2,nchar(map$x$calls[[idx_fleche]]$args[[5]])-11)," ",""))<0)
if(length(val_sor)>0)
{
map$x$calls[[idx_fleche]]$args[[4]]$fillColor[length(val_ent)+1:length(val_sor)] <- colSortie
}
map$x$calls[[idx_fleche]]$args[[4]]$color <- colBorder
if(!is.null(idx_legende))
{
if(length(val_ent)>0 & length(val_sor)==0)
{
map$x$calls[[idx_legende]]$args[[4]]$fillColor <- colEntree
}else if(length(val_ent)==0 & length(val_sor)>0)
{
map$x$calls[[idx_legende]]$args[[4]]$fillColor <- colSortie
}else
{
map$x$calls[[idx_legende]]$args[[4]]$fillColor <- "transparent"
}
map$x$calls[[idx_legende]]$args[[4]]$color <- colBorder
}
}else
{
map_leaflet <- map
map <- map_proxy
clearGroup(map, group = "carte_saphirs")
analyse_WGS84 <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$analyse_WGS84
donnees <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$donnees
code_epsg <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$code_epsg
emprise <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$emprise
varFlux <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$var_flux
max_var <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$max_var
largeurFlecheMax <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$largeur
large_pl <- map_leaflet$x$calls[[idx_fleche]]$args[[2]]$distance
map <- addPolygons(map = map,
data = analyse_WGS84,
stroke = TRUE, color = colBorder,
opacity = 1,
weight = 1,
options = pathOptions(pane = "fond_saphirs", clickable = T),
popup = paste0("<b><font color=
fill = T, fillColor = sapply(donnees[,varFlux], function(x) if(x>0){colEntree}else{colSortie}), fillOpacity = 1,
group = "carte_saphirs",
layerId = list(analyse_WGS84=analyse_WGS84,donnees=donnees,colEntree=colEntree,colSortie=colSortie,code_epsg=code_epsg,emprise=emprise,nom_fond="fond_flux",var_flux=varFlux,max_var=max(abs(donnees[,varFlux])),largeur=largeurFlecheMax,distance=large_pl)
)
if(!is.null(idx_legende))
{
if(max(as.data.frame(donnees)[,varFlux])<0)
{
map_leaflet$x$calls[[idx_fleche]]$args[[2]]$colEntree <- NULL
map_leaflet$x$calls[[idx_fleche]]$args[[2]]$colSortie <- colSortie
}else if(min(as.data.frame(donnees)[,varFlux])>=0)
{
map_leaflet$x$calls[[idx_fleche]]$args[[2]]$colEntree <- colEntree
map_leaflet$x$calls[[idx_fleche]]$args[[2]]$colSortie <- NULL
}else
{
map_leaflet$x$calls[[idx_fleche]]$args[[2]]$colEntree <- NULL
map_leaflet$x$calls[[idx_fleche]]$args[[2]]$colSortie <- NULL
}
map_leaflet$x$calls[[idx_fleche]]$args[[4]]$color <- colBorder
titre <- map_leaflet$x$calls[[idx_legende]]$args[[2]]$titre
lng <- map_leaflet$x$calls[[idx_legende]]$args[[2]]$lng
lat <- map_leaflet$x$calls[[idx_legende]]$args[[2]]$lat
zoom <- map_leaflet$x$calls[[idx_legende]]$args[[2]]$zoom
map <- add_legende_saphirs(map, titre = titre, lng = lng, lat = lat, zoom = zoom, map_leaflet = map_leaflet)
}
}
return(map)
} |
run_engine_tte <- function(
param_files,
n_sims = 1L,
mode = c("s", "r", "p"),
seed = NULL,
analysis_data = NULL,
analysis_mode = NULL,
arm_selection = NULL,
armsdropped = NULL,
complete_data_analysis = NULL,
current_week = NULL,
execdata = NULL,
final = NULL,
fsimdata = NULL,
fsimexp = NULL,
fsimparam = NULL,
interim = NULL,
keepfiles = NULL,
mcmc_num = NULL,
noadapt = NULL,
s2_aux_paramfile = NULL,
stage = NULL,
verbose = FALSE,
version = NULL
) {
run_engine_common_impl(
param_files = param_files,
n_sims = n_sims,
mode = match.arg(mode),
seed = seed,
analysis_data = analysis_data,
analysis_mode = analysis_mode,
arm_selection = arm_selection,
armsdropped = armsdropped,
complete_data_analysis = complete_data_analysis,
current_week = current_week,
execdata = execdata,
final = final,
fsimdata = fsimdata,
fsimexp = fsimexp,
fsimparam = fsimparam,
interim = interim,
keepfiles = keepfiles,
mcmc_num = mcmc_num,
noadapt = noadapt,
s2_aux_paramfile = s2_aux_paramfile,
stage = stage,
verbose = verbose,
set = "TTEDesignParameterSet",
type = "3",
version = version
)
} |
ts_vva_plot <- function(.data, .date_col, .value_col){
date_col_var_expr <- rlang::enquo(.date_col)
value_col_var_expr <- rlang::enquo(.value_col)
if(!is.data.frame(.data)){
stop(call. = FALSE, ".data is not a data.frame/tibble, please supply.")
}
if(rlang::quo_is_missing(date_col_var_expr) | rlang::quo_is_missing(value_col_var_expr)){
stop(call. = FALSE, "Both .date_col and .value_col must be supplied.")
}
data_tbl <- tibble::as_tibble(.data) %>%
dplyr::select({{date_col_var_expr}},{{value_col_var_expr}})
data_diff_tbl <- data_tbl %>%
timetk::tk_augment_differences(.value = {{value_col_var_expr}}, .differences = 1) %>%
timetk::tk_augment_differences(.value = {{value_col_var_expr}}, .differences = 2) %>%
dplyr::rename(velocity = dplyr::contains("_diff1")) %>%
dplyr::rename(acceleration = dplyr::contains("_diff2")) %>%
tidyr::pivot_longer(-{{date_col_var_expr}}) %>%
dplyr::mutate(name = stringr::str_to_title(name)) %>%
dplyr::mutate(name = forcats::as_factor(name))
g <- ggplot2::ggplot(
data = data_diff_tbl,
ggplot2::aes(
x = {{date_col_var_expr}},
y = value,
group = name,
color = name
)
) +
ggplot2::geom_line() +
ggplot2::facet_wrap(name ~ ., ncol = 1, scale = "free") +
ggplot2::theme_minimal() +
ggplot2::labs(
x = "Date",
y = "",
color = ""
)
p <- plotly::ggplotly(g)
output_list <- list(
data = list(
augmented_data_tbl = data_diff_tbl
),
plots = list(
static_plot = g,
interactive_plot = p
)
)
return(invisible(output_list))
} |
factor2color <-
function (x, colors = NULL)
{
x <- if (!is.factor(x)){
as.factor(x)
warning("'x' has been coerced to a factor.")
} else x
n <- nlevels(x)
colors <- if (is.null(colors)){
if (requireNamespace("RColorBrewer", quietly = TRUE))
RColorBrewer::brewer.pal(n = max(n, 3L, na.rm = TRUE), name = "Set3")[1L:
n]
else rainbow(n)
} else rep(colors, length.out = n)
vapply(x, function(y) colors[levels(x) == as.character(y)], character(1L))
} |
simulate_trial <- function(n_int = 50, n_fin = 100, cohorts_start = 1, rr_comb, rr_mono, rr_back, rr_plac,
rr_transform, random_type = NULL, trial_struc = "all_plac", random = FALSE,
prob_comb_rr = NULL, prob_mono_rr = NULL, prob_back_rr = NULL,
prob_plac_rr = NULL, prob_rr_transform = prob_rr_transform, stage_data = TRUE,
cohort_random = NULL, cohorts_max = 4, sr_drugs_pos = 1,
sr_pats = cohorts_max * (n_fin + 3 * cohorts_max), sr_first_pos = FALSE,
target_rr = c(0,0,1), cohort_offset = 0, sharing_type = "all", safety_prob = 0, ...) {
sample.vec <- function(x, ...) x[sample(length(x), ...)]
coh_left_check <- function(x) {
if (x$decision[1] %in% c("none", "PROMISING", "CONTINUE") & x$decision[2] == "none") {
ret <- TRUE
} else {
ret <- FALSE
}
return(ret)
}
create_cohort_initial <- function(trial_struc, cohorts_start, n_int, n_fin,
rr_comb_vec, rr_mono_vec, rr_back_vec, rr_plac_vec) {
if (trial_struc == "no_plac") {
res_list <- rep(list(c(list(decision = rep("none", 2), alloc_ratio = NULL, n_thresh = NULL, start_n = 0),
rep(list(list(rr = NULL, resp_bio = NULL, resp_hist = NULL, n = NULL)), 3))),
cohorts_start)
for (i in 1:cohorts_start) {
names(res_list)[i] <- paste0("Cohort", i)
names(res_list[[i]])[5:7] <- c("Comb", "Mono", "Back")
res_list[[i]]$alloc_ratio <- c(1,1,1)
if (n_int == n_fin) {n_thresh_vec <- c(Inf, n_int)}else{n_thresh_vec <- c(n_int, Inf)}
res_list[[i]]$n_thresh <- n_thresh_vec
res_list[[i]][[5]]$rr <- rr_comb_vec[i]
res_list[[i]][[6]]$rr <- rr_mono_vec[i]
res_list[[i]][[7]]$rr <- rr_back_vec[i]
}
} else {
res_list <- rep(list(c(list(decision = rep("none", 2), alloc_ratio = NULL, n_thresh = NULL, start_n = 0),
rep(list(list(rr = NULL, resp_bio = NULL, resp_hist = NULL, n = NULL)), 4))),
cohorts_start)
for (i in 1:cohorts_start) {
names(res_list)[i] <- paste0("Cohort", i)
names(res_list[[i]])[5:8] <- c("Comb", "Mono", "Back", "Plac")
res_list[[i]]$alloc_ratio <- c(1,1,1,1)
if (n_int == n_fin) {n_thresh_vec <- c(Inf, n_int)}else{n_thresh_vec <- c(n_int, Inf)}
res_list[[i]]$n_thresh <- n_thresh_vec
res_list[[i]][[5]]$rr <- rr_comb_vec[i]
res_list[[i]][[6]]$rr <- rr_mono_vec[i]
res_list[[i]][[7]]$rr <- rr_back_vec[i]
res_list[[i]][[8]]$rr <- rr_plac_vec[i]
}
}
if (cohorts_start > 1) {
if (sharing_type != "cohort") {
res_list <- update_alloc_ratio(res_list)
}
}
return(res_list)
}
create_cohort_new <- function(res_list, plac, n_int, n_fin, sharing_type,
rr_comb_vec, rr_mono_vec, rr_back_vec, rr_plac_vec) {
if (n_int == n_fin) {n_thresh_vec <- c(Inf, n_int)}else{n_thresh_vec <- c(n_int, Inf)}
if (plac) {
new_list <- list(c(list(decision = rep("none", 2),
alloc_ratio = c(1,1,1,1),
n_thresh = n_thresh_vec,
start_n = sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
),
rep(list(list(rr = NULL,
resp_bio = rep(NA, length(res_list[[1]][[5]]$n)),
resp_hist = rep(NA, length(res_list[[1]][[5]]$n)),
n = rep(NA, length(res_list[[1]][[5]]$n)))), 4)))
names(new_list)[1] <- paste0("Cohort", length(res_list) + 1)
names(new_list[[1]])[5:8] <- c("Comb", "Mono", "Back", "Plac")
new_list[[1]][[5]]$rr <- rr_comb_vec[length(res_list) + 1]
new_list[[1]][[6]]$rr <- rr_mono_vec[length(res_list) + 1]
new_list[[1]][[7]]$rr <- rr_back_vec[length(res_list) + 1]
new_list[[1]][[8]]$rr <- rr_plac_vec[length(res_list) + 1]
} else {
new_list <- list(c(list(decision = rep("none", 2),
alloc_ratio = c(1,1,1),
n_thresh = n_thresh_vec,
start_n = sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
),
rep(list(list(rr = NULL,
resp_bio = rep(NA, length(res_list[[1]][[5]]$n)),
resp_hist = rep(NA, length(res_list[[1]][[5]]$n)),
n = rep(NA, length(res_list[[1]][[5]]$n)))), 3)))
names(new_list)[1] <- paste0("Cohort", length(res_list) + 1)
names(new_list[[1]])[5:7] <- c("Comb", "Mono", "Back")
new_list[[1]][[5]]$rr <- rr_comb_vec[length(res_list) + 1]
new_list[[1]][[6]]$rr <- rr_mono_vec[length(res_list) + 1]
new_list[[1]][[7]]$rr <- rr_back_vec[length(res_list) + 1]
}
res_list <- c(res_list, new_list)
if (sharing_type != "cohort") {
res_list <- update_alloc_ratio(res_list)
}
return(res_list)
}
final_n_cohort <- function(res_list) {
res <- matrix(nrow = 4, ncol = length(res_list))
for (i in 1:length(res_list)) {
for (j in 1:length(res_list[[i]]$alloc_ratio)) {
res[j, i] <- sum(res_list[[i]][[j+4]]$n, na.rm = T)
}
}
rownames(res) <- c("Combo", "Mono", "Backbone", "Placebo")
colnames(res) <- paste0("Cohort", 1:length(res_list))
return(res)
}
is_sr_reached <- function(res_list, sr_drugs_pos, sr_pats, expected) {
ret <- 0
positives <- sum(substring(sapply(res_list, function(x) x$decision[2]), 1, 2) == "GO")
if (positives >= sr_drugs_pos) {
ret <- 1
}
if (sr_pats < expected) {
if (sum(sapply(res_list, function(x) total_n(x)), na.rm = T) > sr_pats) {
ret <- 1
}
}
return(ret)
}
total_n <- function(x) {
if ("Plac" %in% names(x)) {
sum(sapply(x[c("Comb", "Back", "Mono", "Plac")], function(y) y$n), na.rm = T)
} else {
sum(sapply(x[c("Comb", "Back", "Mono")], function(y) y$n), na.rm = T)
}
}
total_rb <- function(x) {
if ("Plac" %in% names(x)) {
sum(sapply(x[c("Comb", "Back", "Mono", "Plac")], function(y) y$resp_bio), na.rm = T)
} else {
sum(sapply(x[c("Comb", "Back", "Mono")], function(y) y$resp_bio), na.rm = T)
}
}
total_rh <- function(x) {
if ("Plac" %in% names(x)) {
sum(sapply(x[c("Comb", "Back", "Mono", "Plac")], function(y) y$resp_hist), na.rm = T)
} else {
sum(sapply(x[c("Comb", "Back", "Mono")], function(y) y$resp_hist), na.rm = T)
}
}
update_alloc_ratio <- function(res_list) {
cohorts_left <- which(sapply(res_list, function(x) coh_left_check(x)))
comb_numb <- sum(sapply(res_list[cohorts_left], function(x) names(x)[5:8]) == "Comb", na.rm = T)
back_numb <- sum(sapply(res_list[cohorts_left], function(x) names(x)[5:8]) == "Back", na.rm = T)
mono_numb <- sum(sapply(res_list[cohorts_left], function(x) names(x)[5:8]) == "Mono", na.rm = T)
plac_numb <- sum(sapply(res_list[cohorts_left], function(x) names(x)[5:8]) == "Plac", na.rm = T)
for (i in cohorts_left) {
if (length(res_list[[i]]$alloc_ratio) == 3) {
res_list[[i]]$alloc_ratio <- c(comb_numb, mono_numb, 1)
} else {
res_list[[i]]$alloc_ratio <- c(comb_numb, mono_numb, 1, 1)
}
}
return(res_list)
}
if (random) {
if (random_type == "absolute") {
rr_comb_vec <- sample.vec(rr_comb, cohorts_max, prob = prob_comb_rr, replace = TRUE)
rr_back_vec <- sample.vec(rr_back, cohorts_max, prob = prob_back_rr, replace = TRUE)
rr_mono_vec <- sample.vec(rr_mono, cohorts_max, prob = prob_mono_rr, replace = TRUE)
rr_plac_vec <- sample.vec(rr_plac, cohorts_max, prob = prob_plac_rr, replace = TRUE)
}
if (random_type == "risk_difference") {
rr_plac_vec <- sample.vec(rr_plac, cohorts_max, prob = prob_plac_rr, replace = TRUE)
mono_add <- sample.vec(rr_mono, cohorts_max, prob = prob_mono_rr, replace = TRUE)
back_add <- sample.vec(rr_back, cohorts_max, prob = prob_back_rr, replace = TRUE)
rr_mono_vec <- pmin(rr_plac_vec + mono_add, 1)
rr_back_vec <- pmin(rr_plac_vec + back_add, 1)
comb_add <- sample.vec(rr_comb, cohorts_max, prob = prob_comb_rr, replace = TRUE)
rr_comb_vec <- pmin(rr_plac_vec + back_add + mono_add + comb_add, 1)
}
if (random_type == "risk_ratio") {
rr_plac_vec <- sample.vec(rr_plac, cohorts_max, prob = prob_plac_rr, replace = TRUE)
mono_add <- sample.vec(rr_mono, cohorts_max, prob = prob_mono_rr, replace = TRUE)
back_add <- sample.vec(rr_back, cohorts_max, prob = prob_back_rr, replace = TRUE)
rr_mono_vec <- pmin(rr_plac_vec * mono_add, 1)
rr_back_vec <- pmin(rr_plac_vec * back_add, 1)
comb_add <- sample.vec(rr_comb, cohorts_max, prob = prob_comb_rr, replace = TRUE)
rr_comb_vec <- pmin(rr_plac_vec * mono_add * back_add * comb_add, 1)
}
if (random_type == "odds_ratios") {
odds_to_rr <- function(x) {x/(1+x)}
rr_to_odds <- function(x) {x/(1-x)}
rr_plac_vec <- sample.vec(rr_plac, cohorts_max, prob = prob_plac_rr, replace = TRUE)
mono_add_or <- sample.vec(rr_mono, cohorts_max, prob = prob_mono_rr, replace = TRUE)
back_add_or <- sample.vec(rr_back, cohorts_max, prob = prob_back_rr, replace = TRUE)
odds_plac_vec <- rr_to_odds(rr_plac_vec)
odds_mono_vec <- odds_plac_vec * mono_add_or
odds_back_vec <- odds_plac_vec * back_add_or
rr_comb_interaction <- sample.vec(rr_comb, cohorts_max, prob = prob_comb_rr, replace = TRUE)
odds_comb_vec <- odds_plac_vec * mono_add_or * back_add_or * rr_comb_interaction
rr_mono_vec <- odds_to_rr(odds_mono_vec)
rr_back_vec <- odds_to_rr(odds_back_vec)
rr_comb_vec <- odds_to_rr(odds_comb_vec)
}
rr_transform_vec <- rr_transform[sample(1:length(rr_transform), cohorts_max, prob = prob_rr_transform, replace = TRUE)]
} else {
rr_comb_vec <- rep(rr_comb, cohorts_max)
rr_back_vec <- rep(rr_back, cohorts_max)
rr_mono_vec <- rep(rr_mono, cohorts_max)
rr_plac_vec <- rep(rr_plac, cohorts_max)
rr_transform_vec <- rr_transform[sample(1:length(rr_transform), cohorts_max, prob = 1, replace = TRUE)]
}
cohorts_left <- 1:cohorts_start
trial_stop <- 0
first_success <- -1
last_cohort_time <- 0
res_list <- create_cohort_initial(trial_struc, cohorts_start, n_int, n_fin,
rr_comb_vec, rr_mono_vec, rr_back_vec, rr_plac_vec)
Total_N_Vector <- NULL
comb_suc <- 0
mono_suc <- 0
back_suc <- 0
while (!trial_stop) {
if (!identical(cohorts_left, which(sapply(res_list, function(x) coh_left_check(x)))) & sharing_type != "cohort") {
res_list <- update_alloc_ratio(res_list)
}
cohorts_left <- which(sapply(res_list, function(x) coh_left_check(x)))
cohorts_finished <- which(!sapply(res_list, function(x) coh_left_check(x)))
patients_timestamp <- 0
for (i in cohorts_left) {
f <- match.fun(rr_transform_vec[[i]])
if (length(res_list[[i]]$alloc_ratio) == 3) {
for (j in 5:7) {
res_list[[i]][[j]]$n <- c(res_list[[i]][[j]]$n, res_list[[i]]$alloc_ratio[j-4])
patients_timestamp <- patients_timestamp + res_list[[i]]$alloc_ratio[j-4]
new_probs <- f(res_list[[i]][[j]]$rr)
draw <- t(stats::rmultinom(res_list[[i]]$alloc_ratio[j-4], 1, new_probs))
new_resp_bio <- 0
new_resp_hist <- 0
for (k in 1:nrow(draw)) {
if (draw[k,2] == 1) {
new_resp_bio <- new_resp_bio + 1
}
if (draw[k,3] == 1) {
new_resp_hist <- new_resp_hist + 1
}
if (draw[k,4] == 1) {
new_resp_hist <- new_resp_hist + 1
new_resp_bio <- new_resp_bio + 1
}
}
res_list[[i]][[j]]$resp_bio <- c(res_list[[i]][[j]]$resp_bio, new_resp_bio)
res_list[[i]][[j]]$resp_hist <- c(res_list[[i]][[j]]$resp_hist, new_resp_hist)
}
} else {
for (j in 5:8) {
res_list[[i]][[j]]$n <- c(res_list[[i]][[j]]$n, res_list[[i]]$alloc_ratio[j-4])
patients_timestamp <- patients_timestamp + res_list[[i]]$alloc_ratio[j-4]
new_probs <- f(res_list[[i]][[j]]$rr)
draw <- t(stats::rmultinom(res_list[[i]]$alloc_ratio[j-4], 1, new_probs))
new_resp_bio <- 0
new_resp_hist <- 0
for (k in 1:nrow(draw)) {
if (draw[k,2] == 1) {
new_resp_bio <- new_resp_bio + 1
}
if (draw[k,3] == 1) {
new_resp_hist <- new_resp_hist + 1
}
if (draw[k,4] == 1) {
new_resp_hist <- new_resp_hist + 1
new_resp_bio <- new_resp_bio + 1
}
}
res_list[[i]][[j]]$resp_bio <- c(res_list[[i]][[j]]$resp_bio, new_resp_bio)
res_list[[i]][[j]]$resp_hist <- c(res_list[[i]][[j]]$resp_hist, new_resp_hist)
}
}
}
for (i in cohorts_finished) {
if (length(res_list[[i]]$alloc_ratio) == 3) {
for (j in 5:7) {
res_list[[i]][[j]]$n <- c(res_list[[i]][[j]]$n, NA)
res_list[[i]][[j]]$resp_bio <- c(res_list[[i]][[j]]$resp_bio, NA)
res_list[[i]][[j]]$resp_hist <- c(res_list[[i]][[j]]$resp_hist, NA)
}
} else {
for (j in 5:8) {
res_list[[i]][[j]]$n <- c(res_list[[i]][[j]]$n, NA)
res_list[[i]][[j]]$resp_bio <- c(res_list[[i]][[j]]$resp_bio, NA)
res_list[[i]][[j]]$resp_hist <- c(res_list[[i]][[j]]$resp_hist, NA)
}
}
}
last_cohort_time <- last_cohort_time + patients_timestamp
for (i in cohorts_left) {
safety <- stats::rbinom(1, 1, 1 - ((1 - safety_prob) ^ patients_timestamp))
if (safety) {
if (res_list[[i]]$decision[1] == "none") {res_list[[i]]$decision[1] <- "STOP_SAFETY"}
res_list[[i]]$decision[2] <- "STOP_SAFETY"
res_list[[i]]$final_n <- sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
res_list[[i]]$sup_final <- FALSE
res_list[[i]]$final_n_cohort <- total_n(res_list[[i]])
if(is.null(res_list[[i]]$interim_n)) {res_list[[i]]$interim_n <- NA}
if(is.null(res_list[[i]]$interim_n_cohort)) {res_list[[i]]$interim_n_cohort <- NA}
if(is.null(res_list[[i]]$sup_interim)) {res_list[[i]]$sup_interim <- NA}
if(is.null(res_list[[i]]$fut_interim)) {res_list[[i]]$fut_interim <- NA}
}
}
if (sum(sapply(res_list, function(x) total_n(x)), na.rm = T) > (cohorts_max * (n_fin + 3 * cohorts_max))) {
stop("Total Sample Size is greater than should be possible with settings")
}
ind_int <- intersect(
which(sapply(res_list, function(x) total_n(x)) >= sapply(res_list, function(x) x$n_thresh[1])),
which(sapply(res_list, function(x) x$decision[1]) %in% c("none"))
)
if (length(ind_int) > 0) {
for (i in ind_int) {
res_list <- make_decision_trial(res_list, which_cohort = i, interim = TRUE, sharing_type = sharing_type, ...)
res_list[[i]]$interim_n <- sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
res_list[[i]]$interim_n_cohort <- sum(total_n(res_list[[i]]), na.rm = T)
if (res_list[[i]]$decision[1] == "GO_SUP") {
res_list[[i]]$decision[2] <- "GO_SUP"
res_list[[i]]$n_thresh <- c(Inf, Inf)
if (first_success == -1) {
first_success <- length(res_list[[i]][[7]]$n)
}
}
if (res_list[[i]]$decision[1] == "STOP_FUT") {
res_list[[i]]$decision[2] <- "STOP_FUT"
res_list[[i]]$n_thresh <- c(Inf, Inf)
}
if (res_list[[i]]$decision[1] == "PROMISING") {
res_list[[i]]$n_thresh <- c(Inf, n_fin)
}
if (res_list[[i]]$decision[1] == "CONTINUE") {
res_list[[i]]$n_thresh <- c(Inf, n_fin)
}
}
}
ind_fin <- intersect(
which(sapply(res_list, function(x) total_n(x)) >= sapply(res_list, function(x) x$n_thresh[2])),
which(sapply(res_list, function(x) x$decision[2]) %in% c("none", "PROMISING", "CONTINUE"))
)
if (length(ind_fin) > 0) {
for (i in ind_fin) {
res_list <- make_decision_trial(res_list, which_cohort = i, interim = FALSE, sharing_type = sharing_type, ...)
res_list[[i]]$final_n <- sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
res_list[[i]]$final_n_cohort <- total_n(res_list[[i]])
res_list[[i]]$n_thresh <- c(Inf, Inf)
}
if (res_list[[i]]$decision[2] == "GO_SUP") {
if (first_success == -1) {
first_success <- length(res_list[[i]][[7]]$n)
}
}
}
if (is_sr_reached(res_list, sr_drugs_pos, sr_pats, cohorts_max * (n_fin + 3 * cohorts_max))) {
trial_stop <- 1
ind_stop_sup <- which(sapply(res_list, function(x) x$decision[2]) %in% c("none", "PROMISING", "CONTINUE"))
for (j in ind_stop_sup) {
res_list[[j]]$decision[2] <- "STOP_SR"
res_list[[j]]$final_n <- sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
res_list[[j]]$final_n_cohort <- total_n(res_list[[j]])
res_list[[j]]$sup_final <- FALSE
if (is.null(res_list[[j]]$interim_n)) {
res_list[[j]]$interim_n <- NA
res_list[[j]]$interim_n_cohort <- NA
res_list[[j]]$sup_interim <- NA
res_list[[j]]$fut_interim <- NA
}
}
ind_stop_prior <- which(!sapply(res_list, function(x) x$decision[2]) %in% c("none", "PROMISING", "CONTINUE"))
for (j in ind_stop_prior) {
if (is.null(res_list[[j]]$interim_n)) {
res_list[[j]]$interim_n <- NA
res_list[[j]]$interim_n_cohort <- NA
res_list[[j]]$sup_interim <- NA
res_list[[j]]$fut_interim <- NA
}
}
}
if (first_success == -1 | !sr_first_pos) {
if (length(res_list) < cohorts_max) {
if (!trial_stop) {
if(!is.null(cohort_random)) {
if (last_cohort_time >= cohort_offset) {
prob_new <- 1 - ((1 - cohort_random) ^ patients_timestamp)
new_cohort <- stats::rbinom(1, 1, prob_new)
if (new_cohort) {
if (trial_struc == "all_plac") {
plac <- TRUE
}
if (trial_struc == "no_plac") {
plac <- FALSE
}
if (trial_struc == "stop_post_mono") {
if (mono_suc == 0) {
if (any(!(sapply(res_list, function(x) x$decision[2]) %in% c("none", "STOP_SAFETY")))) {
cohorts_outcome <- which(!(sapply(res_list, function(x) (x$decision[2] %in% c("none", "STOP_SAFETY")))))
for (i in cohorts_outcome) {
if (!is.null(res_list[[i]]$sup_final_list)) {
mat_result <- res_list[[i]]$sup_final_list[[1]]
} else {
mat_result <- res_list[[i]]$sup_interim_list[[1]]
}
success_mono <- apply(mat_result, MARGIN = 2, function(x) all(x, na.rm = T))[3:4]
if (any(success_mono)) {
mono_suc <- 1
}
}
if (mono_suc) {
plac <- FALSE
} else {
plac <- TRUE
}
} else {
plac <- TRUE
}
} else {
plac <- FALSE
}
}
if (trial_struc == "stop_post_back") {
if (back_suc == 0) {
if (any(!(sapply(res_list, function(x) x$decision[2]) %in% c("none", "STOP_SAFETY")))) {
cohorts_outcome <- which(!(sapply(res_list, function(x) (x$decision[2] %in% c("none", "STOP_SAFETY")))))
for (i in cohorts_outcome) {
if (!is.null(res_list[[i]]$sup_final_list)) {
mat_result <- res_list[[i]]$sup_final_list[[1]]
} else {
mat_result <- res_list[[i]]$sup_interim_list[[1]]
}
success_back <- apply(mat_result, MARGIN = 2, function(x) all(x, na.rm = T))[3]
if (success_back) {
back_suc <- 1
}
}
if (back_suc) {
plac <- FALSE
} else {
plac <- TRUE
}
} else {
plac <- TRUE
}
} else {
plac <- FALSE
}
}
comb_suc <- any(substring(sapply(res_list, function(x) x$decision[2]), 1, 2) == "GO")
if (!comb_suc) {
res_list <- create_cohort_new(res_list, plac, n_int, n_fin, sharing_type,
rr_comb_vec, rr_mono_vec, rr_back_vec, rr_plac_vec)
}
}
}
}
}
}
}
if (!any(sapply(res_list, function(x) x$decision[2]) %in% c("none", "PROMISING", "CONTINUE"))) {
trial_stop <- 1
}
Total_N_Vector <- c(Total_N_Vector, sum(sapply(res_list, function(x) total_n(x)), na.rm = T))
}
for (i in 1:length(res_list)) {
if (is.null(res_list[[i]]$final_n)) {
res_list[[i]]$final_n <- NA
res_list[[i]]$final_n_cohort <- NA
res_list[[i]]$sup_final <- NA
res_list[[i]]$fut_final <- NA
}
if (is.null(res_list[[i]]$interim_n) & is.null(res_list[[i]]$final_n)) {
res_list[[i]]$interim_n <- NA
res_list[[i]]$interim_n_cohort <- NA
res_list[[i]]$sup_interim <- NA
res_list[[i]]$fut_interim <- NA
res_list[[i]]$final_n <- sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
res_list[[i]]$final_n_cohort <- NA
res_list[[i]]$sup_final <- NA
res_list[[i]]$fut_final <- NA
}
}
if (n_int == n_fin) {
for (i in 1:length(res_list)) {
res_list[[i]]$interim_n <- NA
res_list[[i]]$interim_n_cohort <- NA
res_list[[i]]$sup_interim <- NA
res_list[[i]]$fut_interim <- NA
}
}
truth <- rep(NA, length(res_list))
if (target_rr[3] == 1) {
for (i in 1:length(res_list)) {
if (length(res_list[[i]]$alloc_ratio) == 3) {
truth[i] <-
(res_list[[i]][["Comb"]]$rr > res_list[[i]][["Mono"]]$rr + target_rr[1]) &
(res_list[[i]][["Comb"]]$rr > res_list[[i]][["Back"]]$rr + target_rr[1])
} else {
truth[i] <-
(res_list[[i]][["Comb"]]$rr > res_list[[i]][["Mono"]]$rr + target_rr[1]) &
(res_list[[i]][["Comb"]]$rr > res_list[[i]][["Back"]]$rr + target_rr[1]) &
(res_list[[i]][["Mono"]]$rr > res_list[[i]][["Plac"]]$rr + target_rr[2]) &
(res_list[[i]][["Back"]]$rr > res_list[[i]][["Plac"]]$rr + target_rr[2])
}
}
}
if (target_rr[3] == 2) {
for (i in 1:length(res_list)) {
if (length(res_list[[i]]$alloc_ratio) == 3) {
truth[i] <-
(res_list[[i]][["Comb"]]$rr / res_list[[i]][["Mono"]]$rr > target_rr[1]) &
(res_list[[i]][["Comb"]]$rr / res_list[[i]][["Back"]]$rr > target_rr[1])
} else {
truth[i] <-
(res_list[[i]][["Comb"]]$rr / res_list[[i]][["Mono"]]$rr > target_rr[1]) &
(res_list[[i]][["Comb"]]$rr / res_list[[i]][["Back"]]$rr > target_rr[1]) &
(res_list[[i]][["Mono"]]$rr / res_list[[i]][["Plac"]]$rr > target_rr[2]) &
(res_list[[i]][["Back"]]$rr / res_list[[i]][["Plac"]]$rr > target_rr[2])
}
}
}
if (target_rr[3] == 3) {
odds <- function(x) {x/(1-x)}
for (i in 1:length(res_list)) {
if (length(res_list[[i]]$alloc_ratio) == 3) {
truth[i] <-
(odds(res_list[[i]][["Comb"]]$rr) / odds(res_list[[i]][["Mono"]]$rr) > target_rr[1]) &
(odds(res_list[[i]][["Comb"]]$rr) / odds(res_list[[i]][["Back"]]$rr) > target_rr[1])
} else {
truth[i] <-
(odds(res_list[[i]][["Comb"]]$rr) / odds(res_list[[i]][["Mono"]]$rr) > target_rr[1]) &
(odds(res_list[[i]][["Comb"]]$rr) / odds(res_list[[i]][["Back"]]$rr) > target_rr[1]) &
(odds(res_list[[i]][["Mono"]]$rr) / odds(res_list[[i]][["Plac"]]$rr) > target_rr[2]) &
(odds(res_list[[i]][["Back"]]$rr) / odds(res_list[[i]][["Plac"]]$rr) > target_rr[2])
}
}
}
rr_comb_final <- sapply(res_list, function(x) x$Comb$rr)
rr_mono_final <- sapply(res_list, function(x) x$Mono$rr)
rr_back_final <- sapply(res_list, function(x) x$Back$rr)
rr_plac_final <- unlist(sapply(res_list, function(x) x$Plac$rr))
c <- rr_comb_vec[1:length(res_list)]
m <- rr_mono_vec[1:length(res_list)]
b <- rr_back_vec[1:length(res_list)]
p <- rr_plac_vec[1:length(res_list)]
p_real <- unlist(sapply(res_list, function(x) x$Plac$rr))
comb_pats <- sapply(res_list, function(x) x$Comb$n)
if (length(comb_pats) == 1) {comb_pats <- as.matrix(comb_pats)}
comb_pat_sup_th <- sum(comb_pats[, which(c > p)], na.rm = T)
comb_pat_sup_real <- sum(comb_pats[, which(c[1:length(p_real)] > p_real)], na.rm = T)
mono_pats <- sapply(res_list, function(x) x$Mono$n)
if (length(mono_pats) == 1) {mono_pats <- as.matrix(mono_pats)}
mono_pat_sup_th <- sum(mono_pats[, which(m > p)], na.rm = T)
mono_pat_sup_real <- sum(mono_pats[, which(m[1:length(p_real)] > p_real)], na.rm = T)
back_pats <- sapply(res_list, function(x) x$Back$n)
if (length(back_pats) == 1) {back_pats <- as.matrix(back_pats)}
back_pat_sup_th <- sum(back_pats[, which(b > p)], na.rm = T)
back_pat_sup_real <- sum(back_pats[, which(b[1:length(p_real)] > p_real)], na.rm = T)
perc_n_sup_th <- (comb_pat_sup_th + mono_pat_sup_th + back_pat_sup_th) / sum(sapply(res_list, function(x) total_n(x)), na.rm = T)
if (trial_struc != "no_plac") {
could_have_been_randomised <-
sum(sapply(res_list[1:length(p_real)], function(x) x$Plac$n), na.rm = T) +
sum(sapply(res_list[1:length(p_real)], function(x) x$Comb$n), na.rm = T) +
sum(sapply(res_list[1:length(p_real)], function(x) x$Mono$n), na.rm = T) +
sum(sapply(res_list[1:length(p_real)], function(x) x$Back$n), na.rm = T)
perc_n_sup_real <- (comb_pat_sup_real + mono_pat_sup_real + back_pat_sup_real) / could_have_been_randomised
} else {
could_have_been_randomised <- 0
perc_n_sup_real <- NA
}
if (first_success > 0) {
comb_pats_to_first_success <- sum(sapply(res_list, function(x) sum(x$Comb$n[1:first_success], na.rm = T)), na.rm = T)
mono_pats_to_first_success <- sum(sapply(res_list, function(x) sum(x$Mono$n[1:first_success], na.rm = T)), na.rm = T)
back_pats_to_first_success <- sum(sapply(res_list, function(x) sum(x$Back$n[1:first_success], na.rm = T)), na.rm = T)
plac_pats_to_first_success <- sum(sapply(res_list, function(x) sum(x$Plac$n[1:first_success], na.rm = T)), na.rm = T)
df <- sapply(res_list, function(x) x$Comb$n[1:first_success])
if (!is.null(ncol(df))) {
cohorts_to_first_success <- ncol(df) - length(which(colSums(df, na.rm = T) == 0))
} else {
cohorts_to_first_success <- 1
}
} else {
comb_pats_to_first_success <- NA
mono_pats_to_first_success <- NA
back_pats_to_first_success <- NA
plac_pats_to_first_success <- NA
cohorts_to_first_success <- NA
}
cp <- sum(substring(sapply(res_list, function(x) x$decision[2]), 1, 2) == "GO" & truth)
fp <- sum(substring(sapply(res_list, function(x) x$decision[2]), 1, 2) == "GO" & !truth)
cn <- sum(substring(sapply(res_list, function(x) x$decision[2]), 1, 2) == "ST" & !truth)
fn <- sum(substring(sapply(res_list, function(x) x$decision[2]), 1, 2) == "ST" & truth)
ret <- list(
Decision = sapply(res_list, function(x) x$decision),
RR_Comb = rr_comb_final,
RR_Mono = rr_mono_final,
RR_Back = rr_back_final,
RR_Plac = rr_plac_final,
RR_Target = target_rr,
N_Cohorts = length(res_list),
N_Cohorts_First_Suc = cohorts_to_first_success,
Total_N_Vector = Total_N_Vector,
Final_N_Cohort = final_n_cohort(res_list),
Total_N = sum(sapply(res_list, function(x) total_n(x)), na.rm = T),
Total_N_First_Suc = comb_pats_to_first_success + back_pats_to_first_success + mono_pats_to_first_success + plac_pats_to_first_success,
Perc_N_Sup_Plac_Th = perc_n_sup_th,
Perc_N_Sup_Plac_Real = perc_n_sup_real,
Total_N_Comb = sum(sapply(res_list, function(x) sum(x$Comb$n, na.rm = T)), na.rm = T),
Total_N_Mono = sum(sapply(res_list, function(x) sum(x$Mono$n, na.rm = T)), na.rm = T),
Total_N_Back = sum(sapply(res_list, function(x) sum(x$Back$n, na.rm = T)), na.rm = T),
Total_N_Plac = sum(sapply(res_list, function(x) sum(x$Plac$n, na.rm = T)), na.rm = T),
Total_N_Plac_First_Suc = plac_pats_to_first_success,
Total_N_Plac_Pool = could_have_been_randomised,
Successes_Hist = sum(sapply(res_list, function(x) total_rh(x)), na.rm = T),
Successes_Hist_Comb = sum(sapply(res_list, function(x) sum(x$Comb$resp_hist, na.rm = T)), na.rm = T),
Successes_Hist_Mono = sum(sapply(res_list, function(x) sum(x$Mono$resp_hist, na.rm = T)), na.rm = T),
Successes_Hist_Back = sum(sapply(res_list, function(x) sum(x$Back$resp_hist, na.rm = T)), na.rm = T),
Successes_Hist_Plac = sum(sapply(res_list, function(x) sum(x$Plac$resp_hist, na.rm = T)), na.rm = T),
Successes_Bio = sum(sapply(res_list, function(x) total_rb(x)), na.rm = T),
Successes_Bio_Comb = sum(sapply(res_list, function(x) sum(x$Comb$resp_bio, na.rm = T)), na.rm = T),
Successes_Bio_Mono = sum(sapply(res_list, function(x) sum(x$Mono$resp_bio, na.rm = T)), na.rm = T),
Successes_Bio_Back = sum(sapply(res_list, function(x) sum(x$Back$resp_bio, na.rm = T)), na.rm = T),
Successes_Bio_Plac = sum(sapply(res_list, function(x) sum(x$Plac$resp_bio, na.rm = T)), na.rm = T),
TP = cp,
FP = fp,
TN = cn,
FN = fn,
FDR_Trial = ifelse(!is.na(fp/(cp + fp)), fp/(cp + fp), NA),
PTP_Trial = ifelse(!is.na(cp/(cp + fn)), cp/(cp + fn), NA),
PTT1ER_Trial = ifelse(!is.na(fp/(fp + cn)), fp/(fp + cn), NA),
any_P = as.numeric((cp + fp) > 0),
Int_GO = sum(sapply(res_list, function(x) x$sup_interim), na.rm = TRUE),
Int_STOP = sum(sapply(res_list, function(x) x$fut_interim), na.rm = TRUE),
Safety_STOP = sum(sapply(res_list, function(x) (x$decision[2] == "STOP_SAFETY")), na.rm = TRUE),
Int_GO_Trial = sum(sapply(res_list, function(x) x$sup_interim), na.rm = TRUE) / length(res_list),
Int_STOP_Trial = sum(sapply(res_list, function(x) x$fut_interim), na.rm = TRUE) / length(res_list),
Safety_STOP_Trial = sum(sapply(res_list, function(x) (x$decision[2] == "STOP_SAFETY")), na.rm = TRUE) / length(res_list)
)
if (stage_data) {
ret <- list(Trial_Overview = ret, Stage_Data = res_list)
}
return(ret)
} |
ani_plot <- function(outmo,nfrs=25,moname="mymovie",labs,att=TRUE,pca=TRUE,contrib,zoom,movie_format="gif",binary){
oopt <- animation::ani.options(interval = 0.1)
if(att==TRUE){
if(zoom==FALSE){
xr=range(unlist(lapply(1:outmo$nchunk,function(jj) {outmo[[jj]]$xr })))
yr=range(unlist(lapply(1:outmo$nchunk,function(jj) {outmo[[jj]]$yr })))
}else{xyr=active_zoom(outmo,nframes=nfrs,att=T)}
}else{
if(zoom==FALSE){
xr=range(unlist(lapply(1:outmo$nchunk,function(jj) {outmo[[jj]]$uxr })))
yr=range(unlist(lapply(1:outmo$nchunk,function(jj) {outmo[[jj]]$uyr })))
}else{xyr=active_zoom(outmo,nframes=nfrs,att=F)}
}
FUN2 <- function(nfrs,nchunk,xr,yr,contrib) {
for (chu in 1:nchunk){
if(zoom==FALSE){
lapply(seq(1,nfrs, by = 1), function(i) {
plot_fun(outmo,chu,i,xr,yr,lab=labs,att=att,pca=pca,contrib=contrib,binary)
animation::ani.pause()})
}else{
lapply(seq(1,nfrs, by = 1), function(i) {
plot_fun(outmo,chu,i,xyr[[chu]]$xr[i,],xyr[[chu]]$yr[i,],lab=labs,att=att,pca=pca,contrib=contrib,binary)
animation::ani.pause()})
}
}
}
if (file.exists(moname)) file.remove(moname)
if(movie_format=="gif"){
saveGIF(FUN2(nfrs,outmo$nchunk,xr,yr,contrib), interval = 0.1,movie.name=paste(moname,".",movie_format,sep=""))
}else{
if(att==TRUE){
frame_name="att_frame"
}else{
frame_name="obs_frame"
}
nmax = nfrs*outmo$nchunk
saveLatex(FUN2(nfrs,outmo$nchunk,xr,yr,contrib), img.name = frame_name, ani.opts = "controls,width=0.95\\textwidth",
latex.filename = ifelse(interactive(), paste(moname,".tex",sep=""), ""),
interval = 0.1, nmax = nmax, ani.dev = "pdf", ani.type = "pdf", ani.width = 7,
ani.height = 7,documentclass = paste("\\documentclass{article}",
"\\usepackage[papersize={7in,7in},margin=0.3in]{geometry}",
sep = "\n"))
}
} |
library(tensorflow)
model_dir <- tempfile()
sess <- tf$Session()
input1 <- tf$placeholder(tf$string)
input2 <- tf$placeholder(tf$string)
output1 <- tf$string_join(inputs = c("Input1: ", input1, "!"))
output2 <- tf$string_join(inputs = c("Input2: ", input2, "!"))
export_savedmodel(
sess,
"tensorflow-multiple",
inputs = list(i1 = input1, i2 = input2),
outputs = list(o1 = output1, o2 = output2),
as_text = TRUE) |
ICcforest <- function(formula, data, mtry = NULL, ntree = 100L, applyfun = NULL,
cores = NULL, na.action = na.pass, suppress = TRUE, trace = TRUE,
perturb = list(replace = FALSE, fraction = 0.632),
control = partykit::ctree_control(teststat = "quad", testtype = "Univ",
mincriterion = 0, saveinfo = FALSE,
minsplit = nrow(data) * 0.15,
minbucket = nrow(data) * 0.06), ...){
if (packageVersion("partykit") < "1.2.2") {
stop("partykit >= 1.2.2 needed for this function.", call. = FALSE)
}
if (packageVersion("icenReg") < "2.0.8") {
stop("icenReg >= 2.0.8 needed for this function.", call. = FALSE)
}
requireNamespace("inum")
if (!requireNamespace("partykit", quietly = TRUE)) {
stop("Package \"pkg\" needed for this function to work. Please install it.",
call. = FALSE)
}
X <- data[,as.character(formula[[2]][[2]])]
Y <- data[,as.character(formula[[2]][[3]])]
if(sum(X==Y)){
epsilon <- min(diff(sort(unique(c(X,Y)))))/20
ID <- which(X==Y)
data[ID,as.character(formula[[2]][[3]])] <- epsilon + data[ID,as.character(formula[[2]][[3]])]
}
.logrank_trafo <- function(x2){
if(!(is.Surv(x2) && isTRUE(attr(x2, "type") == "interval"))){
stop("Response must be a 'Survival' object with Surv(time1,time2,event) format")
}
Curve <- ic_np(x2[, 1:2])
Left <- 1 - getFitEsts(Curve, q = x2[, 1])
Right <- 1 - getFitEsts(Curve, q = x2[, 2])
Log_Left <- ifelse(Left<=0,0,Left*log(Left))
Log_Right<- ifelse(Right<=0,0,Right*log(Right))
result <- (Log_Left-Log_Right)/(Left-Right)
return(matrix(as.double(result),ncol=1))
}
h2 <-function(y, x, start = NULL, weights, offset, estfun = TRUE, object = FALSE, ...) {
if (all(is.na(weights))==1) weights <- rep(1, NROW(y))
s <- .logrank_trafo(y[weights > 0,,drop = FALSE])
r <- rep(0, length(weights))
r[weights > 0] <- s
list(estfun = matrix(as.double(r), ncol = 1), converged = TRUE)
}
if (is.null(mtry))
mtry <- tuneICRF(formula, data, control = control, suppress = suppress, trace = trace)
if (suppress == TRUE){
invisible(capture.output(res <- partykit::cforest(formula, data, control = control, na.action = na.action, ytrafo = h2,
mtry = mtry, ntree = ntree, applyfun = applyfun, cores = cores,
perturb = perturb, ...)))
} else {
res <- partykit::cforest(formula, data, control = control, na.action = na.action, ytrafo = h2,
mtry = mtry, ntree = ntree, applyfun = applyfun, cores = cores,
perturb = perturb, ...)
}
class(res) <- c("ICcforest", class(res))
return(res)
} |
filter_period <- function(.data, ..., .date_var, .period = "1 day") {
if (rlang::quo_is_missing(rlang::enquo(.date_var))) {
message(".date_var is missing. Using: ", tk_get_timeseries_variables(.data)[1])
}
UseMethod("filter_period")
}
filter_period.default <- function(.data, ..., .date_var, .period = "1 day") {
stop("Object is not of class `data.frame`.", call. = FALSE)
}
filter_period.data.frame <- function(.data, ..., .date_var, .period = "1 day") {
data_groups_expr <- rlang::syms(dplyr::group_vars(.data))
date_var_expr <- rlang::enquo(.date_var)
if (rlang::quo_is_missing(date_var_expr)) {
date_var_text <- tk_get_timeseries_variables(.data)[1]
date_var_expr <- rlang::sym(date_var_text)
}
date_var_text <- rlang::quo_name(date_var_expr)
if (!date_var_text %in% names(.data)) {
rlang::abort(stringr::str_glue("Attempting to use .date_var = {date_var_text}. Column does not exist in .data. Please specify a date or date-time column."))
}
ret_tbl <- .data %>%
dplyr::mutate(..date_agg = lubridate::floor_date(!! date_var_expr, unit = .period)) %>%
dplyr::group_by(!!! data_groups_expr, ..date_agg) %>%
dplyr::filter(...) %>%
dplyr::ungroup() %>%
dplyr::select(-..date_agg) %>%
dplyr::group_by(!!! data_groups_expr)
return(ret_tbl)
} |
testname <- function(test) paste0(test$layer, "_", unname(unlist(test$args))[1])
run_facet_test <- function(test) {
library(sf)
library(grid)
library(raster)
data(NLD_prov)
NLD_prov <- st_sf(name = as.character(NLD_prov$name), geometry=NLD_prov$geometry, stringsAsFactors = FALSE)
NLD_prov$by <- factor(rep(c(NA,2,3, 4), each = 3), levels=1:4, labels = letters[1:4])
NLD_prov$v1 <- c(9, 8, 3, 7, 8, NA, NA, NA, NA, 3, 5, NA)
NLD_prov$v2 <- c("x", "y", NA, NA, NA, NA, "x", "y", "x", "y", NA, NA)
NLD_prov$name2 <- NLD_prov$name
NLD_prov$name[c(5, 7, 8, 9)] <- NA
filter <- c(TRUE, TRUE)
shp <- NLD_prov
if (test$layer == "lines") {
shp$geometry <- sf::st_cast(shp$geometry, "MULTILINESTRING", group_or_split = FALSE)
}
dir.create("output", showWarnings = FALSE)
filename <- paste0("output/test_", test$layer, "_", unname(unlist(test$args))[1], ".pdf")
fun <- paste0("tm_", test$layer)
pdf(filename, width = 7, height = 7)
settings <- list(drop.units = c(TRUE, FALSE),
free.coords = c(TRUE, FALSE),
free.scales = c(TRUE, FALSE),
drop.empty.facets = c(TRUE, FALSE),
showNA = c(TRUE, FALSE),
drop.NA.facets = c(TRUE, FALSE))
shortcuts <- c("du", "fc", "fs", "de", "dn", "sn")
comb <- do.call(expand.grid, c(settings, list(KEEP.OUT.ATTRS = FALSE)))
cat("\ntest:", testname(test), "\n")
pb <- txtProgressBar(min = 1, max = nrow(comb), initial = 1)
errs <- data.frame(i = 1:nrow(comb),
err = character(nrow(comb)),
stringsAsFactors = FALSE)
for (i in 1:nrow(comb)) {
setTxtProgressBar(pb, i)
cb <- as.list(comb[i,])
name <- paste(mapply(paste0, shortcuts, c("F", "T")[as.numeric(unlist(cb)) + 1]), collapse = "_")
errs[i, 2] <- tryCatch({
tm <- tm_shape(shp, filter = filter)
if (fun == "tm_symbols") tm <- tm + tm_borders()
print(tm +
do.call(fun, test$args) +
do.call(tm_facets, c(list(by="by"), cb)) +
tm_layout(title=name)
)
""
}, error=function(e) {
grid::upViewport(0)
grid.text(y = .8, label = name)
grid.text(y = .2, label = e)
as.character(e)
}, warning = function(w) {
as.character(w)
})
}
dev.off()
errs <- errs[errs$err != "", ]
name <- testname(test)
filename <- paste0("output/results_", name, ".rds")
saveRDS(errs, file = filename)
nr <- nrow(errs)
if (nr!=0) {
cat(name, paste(errs$i, collapse =", "), "\n")
}
nr
} |
spm12_contrast = function(
name,
weights,
replicate =
c("none", "repl", "replsc",
"sess", "both", "bothsc")) {
replicate = match.arg(replicate)
replicate = convert_to_matlab(replicate)
name = convert_to_matlab(name)
if (is.matrix(weights)) {
weights = rmat_to_matlab_mat(weights)
} else {
class(weights) = "rowvec"
weights = convert_to_matlab(weights)
}
L = list(
name = name,
weights = weights,
sessrep = replicate
)
return(L)
}
spm12_contrast_list = function(
cons,
type = "T") {
n_cond = names(cons)
extractor = function(ind) {
lapply(cons, `[[`, ind)
}
n_cond2 = extractor("name")
n_cond2 = unlist(n_cond2)
if (!is.null(n_cond2)) {
n_cond = n_cond2
}
l_cond = length(cons)
msg = "Contrasts must be named and not NA!"
if (is.null(n_cond)) {
stop(msg)
}
if (any(n_cond %in% "" | is.na(n_cond))) {
stop(msg)
}
if (length(n_cond) != l_cond) {
stop("Conditions not the same as the number of names")
}
type2 = extractor("type")
type2 = unlist(type2)
if (!is.null(type2)) {
type = type2
}
type = match.arg(
type, choices = c("T", "F"),
several.ok = TRUE)
type = rep_len(type, length.out = l_cond)
cons = mapply(function(x, y) {
x$name = y
x$type = NULL
x
}, cons, n_cond, SIMPLIFY = FALSE)
cons = lapply(cons, function(x) {
r = do.call("spm12_contrast", x)
return(r)
})
names(cons) = paste0(
"{", seq(cons), "}.",
paste0(tolower(type), "con")
)
return(cons)
} |
context("AKS interface with managed identity/private cluster")
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("Tests skipped: ARM credentials not set")
rgname <- make_name(10)
rg <- AzureRMR::az_rm$
new(tenant=tenant, app=app, password=password)$
get_subscription(subscription)$
create_resource_group(rgname, location="australiaeast")
echo <- getOption("azure_containers_tool_echo")
options(azure_containers_tool_echo=FALSE)
test_that("AKS works with private cluster",
{
aksname <- make_name(10)
expect_true(is_aks(rg$create_aks(aksname, agent_pools=agent_pool("pool1", 1),
managed_identity=TRUE, private_cluster=TRUE)))
aks <- rg$get_aks(aksname)
expect_true(is_aks(aks))
expect_error(aks$update_service_password())
pool1 <- aks$get_agent_pool("pool1")
expect_is(pool1, "az_agent_pool")
pools <- aks$list_agent_pools()
expect_true(is.list(pools) && length(pools) == 1 && all(sapply(pools, inherits, "az_agent_pool")))
clus <- aks$get_cluster()
expect_true(is_kubernetes_cluster(clus))
})
teardown({
options(azure_containers_tool_echo=echo)
suppressMessages(rg$delete(confirm=FALSE))
}) |
decorate_code <- function(text, ...) {
text <- str_trim(text)
my_opts <- knitr::opts_chunk$merge(list(...))
is_live <- !isTRUE(getOption('knitr.in.progress'))
if (my_opts$eval & is_live) {
scope_and_run(text)
print(eval(parse(text = text)))
}
if (!is.null(my_opts$flair) && !my_opts$flair) {
placeholder <- list(NULL)
attr(placeholder, "class") = "decorated"
return(placeholder)
} else {
my_code_fenced <- paste0("```{r}\n", text, "\n```")
if (is_live) {
knitted <- knitr::knit(text = my_code_fenced,
quiet = TRUE)
} else {
knitted <- knitr::knit_child(text = my_code_fenced,
options = my_opts,
quiet = TRUE)
}
knitted <- knitted %>% src_to_list()
attr(knitted, "class") <- "decorated"
attr(knitted, "orig_code_text") <- text
attr(knitted, "chunk_name") <- NA
return(knitted)
}
} |
plot_contour <- function(dat, covari.sel, trt.sel, resp.sel, outcome.type,
setup.ss, n.grid = c(41, 41),
brk.es = c(0, 1, 2, 3),
n.brk.axis = 7,
para.plot = c(0.35, 2, 20),
font.size = c(1.5, 1.2, 1, 0.85, 0.8),
title = NULL, subtitle = "default",
effect = "HR", point.size = 1.2, filled = FALSE,
strip = NULL, show.overall = FALSE,
palette = "divergent", col.power = 0.5,
show.points = FALSE,
new.layout = TRUE){
if(new.layout) old.par <- par(no.readonly=T)
if (missing(dat)) stop("Data have not been inputed!")
if (!(is.data.frame(dat))) stop("The data set is not with a data frame!")
if (missing(covari.sel)) stop("The variables for defining subgroups have not been specified!")
if (!(is.numeric(covari.sel))) stop("The variables for defining subgroups are not numeric!")
if (length(covari.sel) > 2) stop("This function only considers 2 covariates at most for defining subgroups!")
if (missing(trt.sel)) stop("The variable specifying the treatment code (for treatment / control groups) has not been specified!")
if (!(length(trt.sel) == 1)) stop("The variable specifying the treatment code can not have more than one component!")
if (!(is.factor(dat[, trt.sel]))) stop("The variable specifying the treatment code is not categorical!")
if (length(names(table(dat[, trt.sel]))) > 2) stop("The variable specifying the treatment code is not binary!")
if (sum(is.element(names(table(dat[, trt.sel])), c("0","1"))) != 2) stop("The treatment code is not 0 or 1!")
type.all = c("continuous", "binary", "survival")
if (is.null(outcome.type)) stop("The type of the response variable has not been specified!")
if (!(is.element(outcome.type, type.all)) == TRUE) stop("A unrecognized type has been inputed!")
if (outcome.type == "continuous"){
if (missing(resp.sel)) stop("The response variable has not been specified!")
if (!(length(resp.sel) == 1)) stop("The response variable has more than one component!")
if (!(is.numeric(dat[, resp.sel]))) stop("The response variable is not numeric!")
}else if (outcome.type == "binary"){
if (missing(resp.sel)) stop("The response variable has not been specified!")
if (!(length(resp.sel) == 1)) stop("The response variable has more than one component!")
if (!(is.factor(dat[, resp.sel]) || is.numeric(dat[, resp.sel]) )) stop("The response variable is not categorical or numerical!")
if (length(names(table(dat[, resp.sel]))) > 2) stop("The response variable is not binary!")
if (sum(is.element(names(table(dat[, resp.sel])), c("0","1"))) != 2) stop(" The response variable is not coded as 0 and 1!")
}else if (outcome.type == "survival"){
if (missing(resp.sel)) stop("The response variablehas not been specified!")
if (!(length(resp.sel) == 2)) stop("The response variable for analysing survival data should have two components!")
if (!(is.numeric(dat[, resp.sel[1]]))) stop("The response variable specifying survival time is not numeric!")
if (!(is.numeric(dat[, resp.sel[2]]) || is.logical(dat[, resp.sel[2]]) ) ) stop("The response variable specifying indicators of right censoring should be numerical or logical!")
if (length(names(table(dat[, resp.sel[2]]))) > 2) stop("The response variable specifying indicators of right censoring is not binary!")
if (sum(is.element(names(table(dat[, resp.sel[2]])), c("0","1"))) != 2) stop("The response variable specifying indicators of right censoring is not coded as 0 and 1!")
}
if (missing(setup.ss)) stop("The setting for subgroup sample size and overlap have not been specified!")
if (!(is.numeric(setup.ss))) stop("The setting for subgroup sample size and overlap are not numeric!")
if (length(setup.ss) != 4) stop("The setting for subgroup smaple size and overlap does not have four elements!")
if ((setup.ss[1] > setup.ss[2]) || (setup.ss[3] > setup.ss[4]) || (setup.ss[4] > setup.ss[2])){
stop("subgroup overlap sample sizes is larger than subgroup sample size! Or subgroup sample sizes over the first covariate are not
larger than their further divided subgroup sample sizes over the second covariate!")
}
if (missing(n.grid)) stop("The vector specifying the numbers of the grid points has not been specified!")
if (!(length(n.grid) == 2)) stop("The vector specifying the numbers of the grid points does not have two components only!")
if (!(is.numeric(n.grid)) || (sum(n.grid < 2) != 0 )) stop("The vector specifying the numbers of the grid points is not numeric or has
a value less than 2!")
if (missing(brk.es)) stop("The vector specifying the numbers of break points for effect sizes has not been specified!")
if (!(is.numeric(brk.es))) stop("The vector specifying the numbers of break points for effect sizes is not numeric!")
if (missing(para.plot)) stop("The vector specifying the parameters of the contour plot has not been specified!")
if (!(length(para.plot) == 3)) stop("The vector specifying the parameters of the contour plot should have 3 components only!")
if (!(is.numeric(para.plot)) || (sum(para.plot < 0) != 0 )) stop("The vector specifying the parameters of the contour plot is not numeric or has
a negative element!")
if (!(para.plot[2] %in% c(0, 1, 2)) ) stop("The second plot parameter is given with a unallowable value!")
if (!(para.plot[3]%%1==0) || (para.plot[3] < 0) ) stop("The third plot parameter should be a positive integer!")
if (!(is.numeric(font.size))) stop("The argument about the font sizes of the label and text is not numeric!")
if (!(length(font.size) == 5)) stop("The length of the font size settings is not 5!!")
names(dat)[trt.sel] = "trt"
if (outcome.type == "continuous"){
names(dat)[resp.sel] = "resp"
}else if (outcome.type == "binary"){
names(dat)[resp.sel] = "resp"
}else if (outcome.type == "survival"){
names(dat)[resp.sel[1]] = "time"
names(dat)[resp.sel[2]] = "status"
}
if (outcome.type == "continuous"){
model.int = lm(resp ~ trt, data = dat)
model.sum = summary(model.int)
overall.treatment.mean = model.sum$coefficients[2, 1]
overall.treatment.upper = 0
overall.treatment.lower = 0
}else if (outcome.type == "binary"){
model.int = glm(resp ~ trt, family = "binomial", data = dat)
model.sum = summary(model.int)
overall.treatment.mean = model.sum$coefficients[2, 1]
overall.treatment.upper = 0
overall.treatment.lower = 0
}else if (outcome.type == "survival"){
if (effect == "HR"){
model.int = survival::coxph(survival::Surv(time, status) ~ trt, data = dat)
model.sum = summary(model.int)
overall.treatment.mean = model.sum$coef[1, 1]
overall.treatment.upper = log(model.sum$conf.int[1, 4])
overall.treatment.lower = log(model.sum$conf.int[1, 3])
}
if (effect == "RMST"){
dat.subgr.i = dat
rmst = survRM2::rmst2(time = dat.subgr.i$time, status = dat.subgr.i$status,
arm = dat.subgr.i$trt, tau = time)
overall.treatment.mean = rmst$unadjusted.result[1,1]
overall.treatment.upper = 0
overall.treatment.lower = 0
}
}
covari1.table = round(sort(dat[, covari.sel[1]]), 4)
lab.vars = names(dat)[covari.sel]
N1 = setup.ss[1]; N2 = setup.ss[2]
cutpoint.covar1 = list()
cutpoint.covar1[[1]] = vector()
cutpoint.covar1[[2]] = vector()
low.bd.covar1.idx = 1
upp.bd.covar1.idx = N2
ss.full = dim(dat)[1]
i = 0
while (upp.bd.covar1.idx < ss.full){
i = i + 1
low.bd.covar1.idx = 1 + (i-1) * (N2 - N1)
upp.bd.covar1.idx = min(N2 + (i-1) * (N2 - N1), nrow(dat))
cutpoint.covar1[[1]][i] = covari1.table[low.bd.covar1.idx]
cutpoint.covar1[[2]][i] = covari1.table[upp.bd.covar1.idx]
}
idx.covar1 = list()
n.subgrp.covar1 = length(cutpoint.covar1[[1]])
ss.subgrp.covar1 = vector()
for (i in 1 : n.subgrp.covar1 ){
idx.covar1[[i]] = which((dat[, covari.sel[1]] >= cutpoint.covar1[[1]][i] &
dat[, covari.sel[1]] <= cutpoint.covar1[[2]][i] ) == T )
ss.subgrp.covar1[i] = length(idx.covar1[[i]])
}
N3 = setup.ss[3]; N4 = setup.ss[4]
cutpoint.covar2 = list()
for (i in 1 : n.subgrp.covar1){
covari2.table = round(sort(dat[idx.covar1[[i]], covari.sel[2]]), 4)
cutpoint.covar2[[i]] = list()
cutpoint.covar2[[i]][[1]] = vector()
cutpoint.covar2[[i]][[2]] = vector()
low.bd.covar2.idx = 1
upp.bd.covar2.idx = N4
j = 0
stop = 0
while (stop == 0){
j = j + 1
low.bd.covar2.idx = 1 + (j - 1) * (N4 - N3)
upp.bd.covar2.idx = min(N4 + (j - 1) * (N4 - N3), length(covari2.table))
upp.bd.covar2.idx.stop = N4 + (j - 1) * (N4 - N3)
cutpoint.covar2[[i]][[1]][j] = covari2.table[low.bd.covar2.idx]
cutpoint.covar2[[i]][[2]][j] = covari2.table[upp.bd.covar2.idx]
if (upp.bd.covar2.idx >= length(covari2.table)) {cutpoint.covar2[[i]][[2]][j] = max(covari2.table)}
if (upp.bd.covar2.idx.stop > length(covari2.table)) {stop=1}
}
}
idx.covar2 = list()
n.subgrp.covar2 = vector()
ss.subgrp.covar2 = list()
for (i in 1 : n.subgrp.covar1){
idx.covar2[[i]] = list()
ss.subgrp.covar2[[i]] = list()
for (j in 1 : length(cutpoint.covar2[[i]][[1]]) ){
idx.covar2[[i]][[j]] = vector()
ss.subgrp.covar2[[i]][[j]] = vector()
idx.replace= which((dat[idx.covar1[[i]], covari.sel[2]] >= cutpoint.covar2[[i]][[1]][j] &
dat[idx.covar1[[i]], covari.sel[2]] <= cutpoint.covar2[[i]][[2]][j] ) == T )
idx.covar2[[i]][[j]] = idx.covar1[[i]][idx.replace]
ss.subgrp.covar2[[i]][[j]] = length(idx.covar2[[i]][[j]])
}
n.subgrp.covar2[i] = length(idx.covar2[[i]])
}
x.raw = dat[covari.sel[1]]
y.raw = dat[covari.sel[2]]
all.dat = NULL
treatment.mean = vector()
ss.subgrp = vector()
x = vector()
y = vector()
k = 0
for (i in 1 : n.subgrp.covar1 ){
for (j in 1 : length(cutpoint.covar2[[i]][[1]])){
k = k + 1
cond1 = sum(dat[idx.covar2[[i]][[j]],]$trt == "0") == 0
cond2 = sum(dat[idx.covar2[[i]][[j]],]$trt == "1") == 0
if (cond1 | cond2 ){
treatment.mean[i] = NA
}else{
if (outcome.type == "continuous"){
model.int = lm(resp ~ trt, data = dat[idx.covar2[[i]][[j]],])
model.sum = summary(model.int)
treatment.mean[k] = model.sum$coefficients[2, 1]
}else if (outcome.type == "binary"){
model.int = glm(resp ~ trt, family = "binomial", data = dat[idx.covar2[[i]][[j]],])
model.sum = summary(model.int)
treatment.mean[k] = model.sum$coefficients[2, 1]
}else if (outcome.type == "survival"){
model.int = survival::coxph(survival::Surv(time, status) ~ trt, data = dat[idx.covar2[[i]][[j]],])
model.sum = summary(model.int)
treatment.mean[k] = model.sum$coef[1, 1]
}
}
all.dat = rbind(all.dat, cbind(dat[idx.covar2[[i]][[j]], covari.sel], treatment.mean[k]))
x[k] = (cutpoint.covar1[[2]][i] + cutpoint.covar1[[1]][i])/2
y[k] = (cutpoint.covar2[[i]][[2]][j] + cutpoint.covar2[[i]][[1]][j])/2
ss.subgrp[k] = dim(dat[idx.covar2[[i]][[j]],] )[1]
}
}
colnames(all.dat) = c("x", "y", "treatment.mean")
cat("The number of subgroups over the first covariate is", n.subgrp.covar1, "\n")
cat("The subgroup sample sizes over the first covariate are actually", ss.subgrp.covar1, "\n")
cat("The number of further divided subgroups over the second covariate is", n.subgrp.covar2, "\n")
if (subtitle == "default"){
subtitle = bquote(N[11] %~~% .(setup.ss[2]) ~", "~
N[12] %~~% .(setup.ss[1]) ~", "~
N[21] %~~% .(setup.ss[4]) ~", "~
N[22] %~~% .(setup.ss[3]))
}
treatment.df = data.frame(x, y, treatment.mean)
treatment.df.model = loess(treatment.mean ~ x*y, data = treatment.df,
span = para.plot[1], degree = para.plot[2])
head(all.dat)
treatment.df.model = loess(treatment.mean ~ x*y, data = all.dat,
span = para.plot[1], degree = para.plot[2])
min.x = min(dat[,covari.sel[1]]);max.x = max(dat[,covari.sel[1]])
min.y = min(dat[,covari.sel[2]]);max.y = max(dat[,covari.sel[2]])
xy.fit.pt = expand.grid(list(x = seq(min.x, max.x, len = n.grid[1]),
y = seq(min.y, max.y, len = n.grid[2])))
treatment.df.model.fit = predict(treatment.df.model, newdata = xy.fit.pt)
x.range = seq(min.x, max.x, len = n.grid[1])
y.range = seq(min.y, max.y, len = n.grid[2])
if(!filled){
if (new.layout) graphics::layout(matrix(c(1,2), ncol = 1), heights = c(9,1))
graphics::par(mar=c(4, 4, 3, 2) + 0.1)
graphics::plot(x, y,
xlim = range(x.range), ylim = range(y.range),
xlab = lab.vars[1], ylab = lab.vars[2],
main = title,
col = "gray80",
cex.main = font.size[1],
cex.lab = font.size[2],
cex.axis = font.size[2],
cex.sub = font.size[3])
graphics::mtext(subtitle, cex = font.size[3])
cutoff.es = rev(c(-Inf, brk.es, Inf))
if (palette == "divergent"){
pal.2 = colorRampPalette(c("
pal.YlRd = colorRampPalette(c("
pal.WhBl = colorRampPalette(c("
col.vec.div.pos = pal.WhBl((length(brk.es)+1)/2)
col.vec.div.neg = pal.YlRd((length(brk.es)+1)/2)
col.vec = c(rev(col.vec.div.neg), col.vec.div.pos)
if (!(outcome.type == "survival" & effect == "HR")) col.vec = rev(col.vec)
col.point = col.vec
}
if (palette == "continuous"){
colors = c('
pal.all = colorRampPalette(colors, space = "rgb")
col.vec = pal.all((length(brk.es)+1))
if (!(outcome.type == "survival" & effect == "HR")) col.vec = rev(col.vec)
col.point = col.vec
}
if (palette == "hcl"){
col.vec = rev(colorspace::diverge_hcl(n = length(brk.es)-1,
c = 100, l = c(50,90),
power = col.power))
if (!(outcome.type == "survival" & effect == "HR")) col.vec = rev(col.vec)
col.point = col.vec
}
for (i in 1:(length(cutoff.es) - 1)){
graphics::points(x[setdiff(which((treatment.mean > cutoff.es[i + 1])), which((treatment.mean > cutoff.es[i]) ))],
y[setdiff(which((treatment.mean > cutoff.es[i + 1])), which((treatment.mean > cutoff.es[i]) ))],
col = col.point[i], pch = 16, cex = point.size)
}
breaks = pretty(c(-3,3), length(col.vec))
graphics::contour(x.range, y.range, treatment.df.model.fit,
levels = breaks,
vfont = c("sans serif", "plain"),
labcex = font.size[5],
col = "darkgreen",
lty = "solid",
add = TRUE)
lab0.es = paste("ES >", brk.es[length(brk.es)])
lab1.es = vector()
for (i in length(brk.es) : 2){
lab.es.temp = paste(brk.es[i - 1], "< ES <", brk.es[i])
lab1.es = c(lab1.es, lab.es.temp)
}
lab2.es =paste("ES <", brk.es[1])
lab.es = c(lab0.es, lab1.es, lab2.es)
graphics::par(mar=c(0,0,0,0))
graphics::plot(0,0, xaxt = "n", yaxt = "n", type ="n", frame.plot = FALSE)
graphics::legend("bottom",
rev(lab.es),
horiz = T,
cex = font.size[4],
col = rev(col.point),
pch = 16,
bg = "white")
}
if(filled){
if (palette == "divergent"){
cols = c('
pal.YlRd = colorRampPalette(c("
pal.WhBl = colorRampPalette(c("
col.vec.div.pos = pal.WhBl((length(brk.es)-1)/2)
col.vec.div.neg = pal.YlRd((length(brk.es)-1)/2)
col.vec = c(rev(col.vec.div.neg), col.vec.div.pos)
if (!(outcome.type == "survival" & effect == "HR")) col.vec = rev(col.vec)
cols = col.vec
}
if (palette == "continuous"){
cols = c('
pal.all = colorRampPalette(cols, space = "rgb")
col.vec = pal.all((length(brk.es)-1))
if (!(outcome.type == "survival" & effect == "HR")) col.vec = rev(col.vec)
cols = col.vec
}
if (palette == "hcl"){
col.vec = rev(colorspace::diverge_hcl(n = length(brk.es)-1,
c = 100, l = c(50,90),
power = col.power))
if (!(outcome.type == "survival" & effect == "HR")) col.vec = rev(col.vec)
cols = col.vec
}
if (new.layout) graphics::layout(matrix(c(1, 2), nrow=1, ncol=2), widths=c(4,1))
if (is.null(title)){
graphics::par(mar=c(3,3,2,1), mgp = c(2,1,0))
} else{
graphics::par(mar=c(3,3,4,1), mgp = c(2,1,0))
}
axis.sep = 0
graphics::plot(x.range, y.range, type = "n",
xlim = c(min.x-axis.sep, max.x+axis.sep),
ylim = c(min.y-axis.sep, max.y+axis.sep),
xlab = lab.vars[1], ylab = lab.vars[2],
main = title,
col = "gray80",
cex.main = font.size[1],
cex.lab = font.size[2],
cex.axis = font.size[2],
cex.sub = font.size[3])
graphics::mtext(subtitle,
cex = font.size[3])
breaks = seq(min(brk.es),max(brk.es), length.out = length(cols)+1)
breaks.axis = seq(min(brk.es),max(brk.es), length.out = n.brk.axis)
graphics::.filled.contour(x.range, y.range, treatment.df.model.fit,
levels = breaks,
col = rev(cols))
if(show.points) graphics::points(dat[, covari.sel], cex = 0.5, lwd = 0.1)
if (is.null(title)){
par(mar=c(3,2,2,1.5), mgp = c(0,1,0))
} else{
par(mar=c(3,2,4,1.5), mgp = c(0,1,0))
}
image.scale(brk.es,
col= rev(cols),
breaks = breaks,
axis.pos = 4, add.axis = FALSE)
graphics::axis(2, at = breaks.axis, labels = round(breaks.axis, 3), las = 0, cex.axis = font.size[5])
graphics::mtext(strip, side=4, line=0, cex = .75*font.size[5])
if(show.overall){
cat(sprintf("Overall Treatment effect is: %.4f, with confidence interval: (%.4f;%.4f)\n",
overall.treatment.mean, overall.treatment.lower, overall.treatment.upper))
graphics::points(x = 0.5,
(overall.treatment.mean), pch = 20)
graphics::points(x = 0.5, overall.treatment.lower, pch = "-")
graphics::points(x = 0.5, overall.treatment.upper, pch = "-")
graphics::segments(x0 = 0.5, x1 = 0.5,
y0 = overall.treatment.lower,
y1 = overall.treatment.upper)
}
if(new.layout) graphics::par(old.par)
}
} |
"generate.1d.observations" <-
function (D1, subsets, basis.fun, hpa, betas = NULL, export.truth=FALSE)
{
if(is.null(betas)){
betas <-
rbind(c(1, 2),
c(1, 1),
c(1, 3))
colnames(betas) <- c("const", "x")
rownames(betas) <- paste("level", 1:3, sep = "")
}
if(export.truth){
return(list(
hpa=hpa,
betas=betas
)
)
}
sigma_squareds <- hpa$sigma_squareds
B <- hpa$B
rhos <- hpa$rhos
delta <- function(i) {
out <- rmvnorm(n = 1,
mean = basis.fun(D1[subsets[[i]], , drop =
FALSE]) %*% betas[i, ],
sigma = sigma_squareds[i] * corr.matrix(xold = D1[subsets[[i]], , drop = FALSE], pos.def.matrix = B[[i]])
)
out <- drop(out)
names(out) <- rownames(D1[subsets[[i]], , drop = FALSE])
return(out)
}
use.clever.but.untested.method <- FALSE
if(use.clever.but.untested.method){
z1 <- delta(1)
z2 <- delta(2) + rhos[1] * z1[match(subsets[[2]], subsets[[1]])]
z3 <- delta(3) + rhos[2] * z2[match(subsets[[3]], subsets[[2]])]
return(list(z1 = z1, z2 = z2, z3 = z3))
} else {
out <- NULL
out[[1]] <- delta(1)
for(i in 2:length(subsets)){
out[[i]] <- delta(i) + rhos[i-1] *
out[[i-1]][match(subsets[[i]], subsets[[i-1]])]
}
return(out)
}
} |
NULL
xp.akaike.plot <-
function(gamobj=NULL,
title = "Default",
xlb = "Akaike value",
ylb="Models",
...) {
if(is.null(gamobj)){
gamobj <- check.gamobj()
if(is.null(gamobj)){
return()
} else {
}
} else {
c1 <- call("assign",pos=1, "current.gam", gamobj,immediate=T)
eval(c1)
}
if(is.null(eval(parse(text=paste("current.gam","$steppit",sep=""))))) {
cat("This plot is not applicable without stepwise covariate selection.\n")
return()
}
keep <- eval(parse(text=paste("current.gam","$keep",sep="")))
aic <- apply(keep, 2, function(x)
return(x$AIC))
df.resid <- apply(keep, 2, function(x)
return(x$df.resid))
term <- apply(keep, 2, function(x)
return(x$term))
pdata <- data.frame(aic, df.resid, term)
aic.ord <- order(pdata$aic)
pdata <- pdata[aic.ord, ]
if(dim(pdata)[1] > 30){
pdata1 <- pdata[1:30, ]
pdata2 <- pdata[1:30, ]
} else {
pdata1 <- pdata
pdata2 <- pdata
}
pdata1$term <- unclass(pdata1$term)
pdata1$term <- reorder(as.factor(pdata1$term), pdata1$aic)
names(pdata1$term) <- pdata2$term
if(!is.null(title) && title == "Default") {
title <- paste("AIC values from stepwise GAM search on ",
eval(parse(text=paste("current.gam","$pars",sep=""))),
" (Run ",
eval(parse(text=paste("current.gam","$runno",sep=""))),
")",sep="")
}
xplot <- dotplot(term~aic,
pdata1,
main=title,
xlab=xlb,
ylab=ylb,
scales=list(cex=0.7,
tck=-0.01,
y=list(labels=pdata2$term,cex=0.6 )
),
...
)
return(xplot)
} |
plotSel <- function(model, together=FALSE, series=NULL, sex=NULL, axes=TRUE,
legend="bottom", main="", xlab="", ylab="", cex.main=1.2,
cex.legend=1, cex.lab=1, cex.axis=0.8, cex.strip=0.8,
col.strip="gray95", strip=strip.custom(bg=col.strip), las=1,
tck=0, tick.number=5, lty.grid=3, col.grid="gray", pch="m",
cex.points=1, col.points="black", lty.lines=1, lwd.lines=4,
col.lines=c("red","blue"), plot=TRUE, ...)
{
panel.each <- function(x, y, subscripts, maturity, col.lines.vector, ...)
{
panel.grid(h=-1, v=-1, lty=lty.grid, col=col.grid)
panel.points(maturity$Age, maturity$P, col=col.points, ...)
panel.lines(x, y, col=col.lines.vector[subscripts], ...)
}
panel.together <- function(x, y, subscripts, maturity, ...)
{
panel.grid(h=-1, v=-1, lty=lty.grid, col=col.grid)
panel.points(maturity$Age, maturity$P, col=col.points, ...)
panel.superpose(x, y, type="l", subscripts=subscripts, col=col.lines, ...)
}
x <- if(class(model)=="scape") model$Sel else model
if(is.null(series))
series <- unique(x$Series)
if(is.null(sex))
sex <- unique(x$Sex)
ok.series <- x$Series %in% series
if(!any(ok.series)) stop("please check if the 'series' argument is correct")
ok.sex <- x$Sex %in% sex
if(!any(ok.sex)) stop("please check if the 'sex' argument is correct")
x <- x[ok.series & ok.sex,]
if(is.numeric(x$Series))
x$Series <- factor(paste("Series", x$Series))
mat <- x[x$Series=="Maturity",]
sel <- x[x$Series!="Maturity",]
sel$Series <- factor(as.character(sel$Series))
nseries <- length(unique(sel$Series))
lty.lines <- rep(lty.lines, length.out=max(2,nseries))
lwd.lines <- rep(lwd.lines, length.out=max(2,nseries))
col.lines <- rep(col.lines, length.out=max(2,nseries))
mymain <- list(label=main, cex=cex.main)
myxlab <- list(label=xlab, cex=cex.lab)
myylab <- list(label=ylab, cex=cex.lab)
myrot <- switch(as.character(las),
"0"=list(x=list(rot=0),y=list(rot=90)),
"1"=list(x=list(rot=0),y=list(rot=0)),
"2"=list(x=list(rot=90),y=list(rot=0)),
"3"=list(x=list(rot=90),y=list(rot=90)))
myscales <- c(list(draw=axes,cex=cex.axis,tck=tck,
tick.number=tick.number), myrot)
mystrip <- strip.custom(bg=col.strip)
mytext <- list(cex=cex.strip)
mykey <- list(space=legend, text=list(lab=levels(sel$Series),cex=cex.legend),
lines=list(lty=lty.lines,lwd=lwd.lines,col=col.lines))
if(!together)
{
graph <- xyplot(P~Age|Series*Sex, data=sel, panel=panel.each, maturity=mat,
as.table=TRUE, main=mymain, xlab=myxlab, ylab=myylab,
scales=myscales, strip=strip, par.strip.text=mytext,
pch=pch, cex=cex.points, col.points=col.points,
lty=lty.lines, lwd=lwd.lines,
col.lines.vector=col.lines[factor(x$Sex)], ...)
}
else
{
graph <- xyplot(P~Age|Sex, data=sel, groups=sel$Series,
panel=panel.together, maturity=mat, main=mymain,
xlab=myxlab, ylab=myylab, scales=myscales, strip=strip,
par.strip.text=mytext, key=mykey, pch=pch, cex=cex.points,
col.points=col.points, lty=lty.lines, lwd=lwd.lines,
col.line=col.lines, ...)
}
if(is.list(graph$x.limits))
{
graph$x.limits <- lapply(graph$x.limits, function(x) c(0, max(x$Age)))
graph$y.limits <- lapply(graph$y.limits, function(y) c(-0.005, 1.005))
}
else
{
graph$x.limits <- c(0, max(x$Age))
graph$y.limits <- c(-0.005, 1.005)
}
if(plot)
{
print(graph)
invisible(x)
}
else
{
invisible(graph)
}
} |
dat <- readr::read_csv("cas500.csv", show_col_types = FALSE)
filtered.1LVL <- filterLevels(dat, "cellsource", c("job"))
filtered.3LVL <- filterLevels(dat, "getlunch", c("home", "tuckshop", "friend"))
test_that("Result is only those with the filtered variable remains", {
expect_true(all(levels(filtered.1LVL$cellsource) == c("job")))
expect_true(all(levels(filtered.3LVL$getlunch) == c("home", "tuckshop", "friend")))
})
test_that("Result is the other categorical variables remain", {
expect_true(all(levels(filtered.1LVL$travel) == levels(dat$travel)))
expect_true(all(levels(filtered.1LVL$getlunch) == levels(dat$getlunch)))
expect_true(all(levels(filtered.1LVL$gender) == levels(dat$gender)))
expect_true(all(levels(filtered.3LVL$cellsource) == levels(dat$cellsource)))
expect_true(all(levels(filtered.3LVL$travel) == levels(dat$travel)))
expect_true(all(levels(filtered.3LVL$gender) == levels(dat$gender)))
})
require(survey)
data(api)
svy <- svydesign(~dnum+snum, weights = ~pw, fpc = ~fpc1+fpc2, data = apiclus2)
test_that("Filtering survey design works", {
expect_silent(
svy_filtered <- filterLevels(svy, "stype", "E")
)
svy_filtered_proper <- subset(svy, stype == "E")
expect_equal(
svymean(~api00, svy_filtered),
svymean(~api00, svy_filtered_proper)
)
expect_equal(
svy_filtered,
eval(parse(text = code(svy_filtered))),
ignore_attr = TRUE
)
}) |
library(jug)
context("testing Request class")
jug_req<-Request$new(RawTestRequest$new()$req)
test_that("A variable is correctly attached to a request",{
jug_req$attach("testkey", "test")
expect_equal(jug_req$params$testkey, "test")
}) |
prices <- 1:10
ans1 <- btest(prices, function() 1)
expect_true(inherits(ans1, "btest")) |
validate <- function(conn, index, type = NULL, ...) {
is_conn(conn)
Search(conn, index, type, search_path = "_validate/query",
track_total_hits = NULL, ...)
} |
NULL
boundGrade <- function(current_grade, grade_of_record, route_limit_below, route_limit_above) {
delta <- getRelativeGrade(current_grade, grade_of_record)
if (delta < -route_limit_below) {
g <- changeGrade(grade_of_record, -route_limit_below)
return(g)
}
if (delta > route_limit_above) {
g <- changeGrade(grade_of_record, route_limit_above)
return(g)
}
return(current_grade)
}
updateThetaUsingCombined <- function(examinee_object, current_module_position, config) {
if (current_module_position %% 2 == 0) {
item_data <-
examinee_object@item_data[(current_module_position - 1):current_module_position]
combined_response <-
examinee_object@response[(current_module_position - 1):current_module_position]
item_data[[1]]@raw$ID <- paste0("temp1", 1:length(item_data[[1]]@id))
item_data[[2]]@raw$ID <- paste0("temp2", 1:length(item_data[[2]]@id))
combined_item_data <- item_data[[1]] + item_data[[2]]
combined_response <- unlist(combined_response)
if (config@final_theta$method == "MLEF") {
res_tmp <- mlef(
object = combined_item_data,
resp = combined_response,
fence_slope = config@final_theta$fence_slope,
fence_difficulty = config@final_theta$fence_difficulty,
max_iter = config@final_theta$max_iter,
crit = config@final_theta$crit,
theta_range = config@final_theta$bound_ML,
truncate = config@final_theta$truncate_ML,
max_change = config@final_theta$max_change,
do_Fisher = config@final_theta$do_Fisher
)
}
if (config@final_theta$method == "MLE") {
res_tmp <- mle(
object = combined_item_data,
resp = combined_response,
max_iter = config@final_theta$max_iter,
crit = config@final_theta$crit,
theta_range = config@final_theta$bound_ML,
truncate = config@final_theta$truncate_ML,
max_change = config@final_theta$max_change,
do_Fisher = config@final_theta$do_Fisher
)
}
if (config@final_theta$method == "EAP") {
prior_par <- examinee_object@prior_par_by_module[[current_module_position -1]]
prior_dist <- genPriorDist(
dist_type = "normal",
prior_par = prior_par,
theta_grid = config@theta_grid,
nj = 1)
res_tmp <- eap(
object = combined_item_data,
resp = combined_response,
theta_grid = config@theta_grid,
prior = prior_dist
)
}
o <- list()
o$theta <- res_tmp$th
o$theta_se <- res_tmp$se
examinee_object@estimated_theta_by_test[[current_module_position - 1]] <- o
examinee_object@estimated_theta_by_test[[current_module_position ]] <- o
return(examinee_object)
} else {
return(examinee_object)
}
}
updateThetaForRouting <- function(examinee_object, current_module_position, combine_policy) {
if (current_module_position %% 2 == 1) {
examinee_object@routing_based_on[current_module_position] <- "estimated_theta_by_phase"
examinee_object@estimated_theta_for_routing[[current_module_position]] <-
examinee_object@estimated_theta_by_phase[[current_module_position]]
return(examinee_object)
}
if (current_module_position %% 2 == 0) {
if (combine_policy == "always") {
examinee_object@routing_based_on[current_module_position] <- "estimated_theta_by_test"
examinee_object@estimated_theta_for_routing[[current_module_position]] <-
examinee_object@estimated_theta_by_test[[current_module_position]]
return(examinee_object)
}
if (combine_policy == "never") {
examinee_object@routing_based_on[current_module_position] <- "estimated_theta_by_phase"
examinee_object@estimated_theta_for_routing[[current_module_position]] <-
examinee_object@estimated_theta_by_phase[[current_module_position]]
return(examinee_object)
}
if (combine_policy == "conditional") {
grade_is_same <- getRelativeGrade(
examinee_object@grade_log[current_module_position],
examinee_object@grade_log[current_module_position - 1]
) == 0
if (grade_is_same) {
examinee_object@routing_based_on[current_module_position] <- "estimated_theta_by_test"
examinee_object@estimated_theta_for_routing[[current_module_position]] <-
examinee_object@estimated_theta_by_test[[current_module_position]]
return(examinee_object)
} else {
examinee_object@routing_based_on[current_module_position] <- "estimated_theta_by_phase"
examinee_object@estimated_theta_for_routing[[current_module_position]] <-
examinee_object@estimated_theta_by_phase[[current_module_position]]
return(examinee_object)
}
}
stop(sprintf("unexpected combine_policy: '%s'", combine_policy))
}
}
updateGrade <- function(
examinee_object, assessment_structure, module_position, cut_scores, transition_policy = "CI",
transition_CI_alpha,
transition_percentile_lower,
transition_percentile_upper,
item_pool) {
theta <- examinee_object@estimated_theta_for_routing[[module_position]]$theta
theta_se <- examinee_object@estimated_theta_for_routing[[module_position]]$theta_se
if (tolower(transition_policy) %in% c(
"pool_difficulty_percentile",
"pool_difficulty_percentile_exclude_administered",
"ci")
) {
if (tolower(transition_policy) == "pool_difficulty_percentile") {
theta_L <- theta
theta_U <- theta
item_b <- na.omit(as.vector(item_pool@ipar))
lower_b <- quantile(item_b, transition_percentile_lower)
upper_b <- quantile(item_b, transition_percentile_upper)
cut_scores_thisgrade <- c(lower_b, 0, upper_b)
} else if (tolower(transition_policy) == "pool_difficulty_percentile_exclude_administered") {
theta_L <- theta
theta_U <- theta
administered_item_pool <- suppressWarnings(do.call(c, examinee_object@item_data))
pool <- item_pool - administered_item_pool
item_b <- na.omit(as.vector(pool@ipar))
lower_b <- quantile(item_b, transition_percentile_lower)
upper_b <- quantile(item_b, transition_percentile_upper)
cut_scores_thisgrade <- c(lower_b, 0, upper_b)
} else if (tolower(transition_policy) == "ci") {
theta_L <- theta - qnorm((1 - transition_CI_alpha / 2)) * theta_se
theta_U <- theta + qnorm((1 - transition_CI_alpha / 2)) * theta_se
cut_scores_thisgrade <- cut_scores[[examinee_object@current_grade]]
}
if (length(cut_scores_thisgrade) > 2) {
cut_scores_thisgrade <- c(
head(cut_scores_thisgrade, 1),
tail(cut_scores_thisgrade, 1)
)
}
relative_grade <- getRelativeGrade(
examinee_object@current_grade,
examinee_object@grade_log[1]
)
if (module_position %% assessment_structure@n_phase == 0) {
if (
relative_grade == -1 &&
"R1" %in% assessment_structure@test_routing_restrictions
) {
examinee_object@current_grade <- changeGrade(examinee_object@current_grade, 1)
examinee_object@current_grade <- boundGrade(
examinee_object@current_grade,
examinee_object@grade_log[1],
assessment_structure@route_limit_below,
assessment_structure@route_limit_above
)
return(examinee_object)
}
}
if (theta_U < cut_scores_thisgrade[1]) {
if (module_position %% assessment_structure@n_phase == 0) {
if (
relative_grade == 0 &&
"R2" %in% assessment_structure@test_routing_restrictions
) {
examinee_object@current_grade <- changeGrade(examinee_object@current_grade, 0)
return(examinee_object)
}
}
examinee_object@current_grade <- changeGrade(examinee_object@current_grade, -1)
examinee_object@current_grade <- boundGrade(
examinee_object@current_grade,
examinee_object@grade_log[1],
assessment_structure@route_limit_below,
assessment_structure@route_limit_above
)
return(examinee_object)
} else if (theta_L > cut_scores_thisgrade[2]) {
test_position <- module_position %/% assessment_structure@n_phase + 1
if (module_position %% assessment_structure@n_phase == 0) {
if (
relative_grade >= (test_position - 1) &&
"R3" %in% assessment_structure@test_routing_restrictions
) {
examinee_object@current_grade <- changeGrade(examinee_object@current_grade, 0)
return(examinee_object)
}
}
examinee_object@current_grade <- changeGrade(examinee_object@current_grade, 1)
examinee_object@current_grade <- boundGrade(
examinee_object@current_grade,
examinee_object@grade_log[1],
assessment_structure@route_limit_below,
assessment_structure@route_limit_above
)
return(examinee_object)
} else {
return(examinee_object)
}
} else if (tolower(transition_policy) == "on_grade") {
return(examinee_object)
}
stop(sprintf(
"module position %s: cannot route module for examinee '%s' with relative grade: %s, estimated theta = %s (%s), cut scores = %s, transition policy = %s",
module_position,
examinee_object@examinee_id,
relative_grade,
examinee_object@estimated_theta_for_routing[[module_position]]$theta,
examinee_object@estimated_theta_for_routing[[module_position]]$theta_se,
paste0(cut_scores_thisgrade, collapse = " "),
transition_policy
))
} |
quantile.nifti = function(x, ..., mask) {
if (missing(mask)) {
x = img_data(x)
x = c(x)
} else {
x = mask_vals(object = x, mask)
}
quantile(x, ...)
}
quantile.anlz = function(x, ..., mask) {
quantile.nifti(x = x, ..., mask = mask)
} |
get_edges <- function(format = 'short', collapse = 'none', ...) {
if (!collapse %in% c('none', 'all', 'direction')) {
stop('Collapse must be either "none", "all" or "direction"')
}
function(layout) {
edges <- collect_edges(layout)
edges <- switch(
collapse,
none = edges,
all = collapse_all_edges(edges),
direction = collapse_dir_edges(edges)
)
edges <- switch(
format,
short = format_short_edges(edges, layout),
long = format_long_edges(edges, layout),
stop('Unknown format. Use either "short" or "long"')
)
edges <- do.call(
cbind,
c(
list(edges),
lapply(list(...), rep, length.out = nrow(edges)),
list(stringsAsFactors = FALSE)
)
)
attr(edges, 'type_ggraph') <- 'edge_ggraph'
edges
}
}
collect_edges <- function(layout) {
UseMethod('collect_edges', layout)
}
collect_edges.default <- function(layout) {
attr(layout, 'edges')
}
check_short_edges <- function(edges) {
if (!inherits(edges, 'data.frame')) {
stop('edges must by of class data.frame', call. = FALSE)
}
if (!all(c('from', 'to', 'x', 'y', 'xend', 'yend', 'circular', 'edge.id') %in% names(edges))) {
stop('edges must contain the columns from, to, x, y, xend, yend, circular, and edge.id', call. = FALSE)
}
if (!is.logical(edges$circular)) {
stop('circular column must be logical', call. = FALSE)
}
edges
}
check_long_edges <- function(edges) {
if (!inherits(edges, 'data.frame')) {
stop('edges must by of class data.frame', call. = FALSE)
}
if (!all(c('edge.id', 'node', 'x', 'y', 'circular') %in% names(edges))) {
stop('edges must contain the columns edge.id, node, x, y and circular', call. = FALSE)
}
if (!all(range(table(edges$edge.id)) == 2)) {
stop('Each edge must consist of two rows')
}
if (!is.logical(edges$circular)) {
stop('circular column must be logical', call. = FALSE)
}
edges
}
add_edge_coordinates <- function(edges, layout) {
edges$x <- layout$x[edges$from]
edges$y <- layout$y[edges$from]
edges$xend <- layout$x[edges$to]
edges$yend <- layout$y[edges$to]
edges
}
format_short_edges <- function(edges, layout) {
edges <- add_edge_coordinates(edges, layout)
nodes1 <- layout[edges$from, , drop = FALSE]
names(nodes1) <- paste0('node1.', names(nodes1))
nodes2 <- layout[edges$to, , drop = FALSE]
names(nodes2) <- paste0('node2.', names(nodes2))
edges <- cbind(edges, nodes1, nodes2)
rownames(edges) <- NULL
edges$edge.id <- seq_len(nrow(edges))
check_short_edges(edges)
}
format_long_edges <- function(edges, layout) {
from <- cbind(
edge.id = seq_len(nrow(edges)),
node = edges$from,
layout[edges$from, c('x', 'y')],
edges
)
to <- cbind(
edge.id = seq_len(nrow(edges)),
node = edges$to,
layout[edges$to, c('x', 'y')],
edges
)
edges <- rbind_dfs(list(from, to))
node <- layout[edges$node, , drop = FALSE]
names(node) <- paste0('node.', names(node))
edges <- cbind(edges, node)
rownames(edges) <- NULL
check_long_edges(edges[order(edges$edge.id), ])
}
complete_edge_aes <- function(aesthetics) {
if (is.null(aesthetics)) {
return(aesthetics)
}
if (any(names(aesthetics) == 'color')) {
names(aesthetics)[names(aesthetics) == 'color'] <- 'colour'
}
expand_edge_aes(aesthetics)
}
expand_edge_aes <- function(x) {
short_names <- names(x) %in% c(
'colour', 'color', 'fill', 'linetype', 'shape', 'size', 'width', 'alpha'
)
names(x)[short_names] <- paste0('edge_', names(x)[short_names])
x
}
collapse_all_edges <- function(edges) {
from <- pmin(edges$from, edges$to)
to <- pmax(edges$to, edges$from)
id <- paste(from, to, sep = '-')
if (anyDuplicated(id)) {
edges$.id <- id
edges <- edges %>%
group_by(.data$.id) %>%
top_n(1) %>%
ungroup()
}
as.data.frame(edges, stringsAsFactors = FALSE)
}
collapse_dir_edges <- function(edges) {
id <- paste(edges$from, edges$to, sep = '-')
if (anyDuplicated(id)) {
edges$.id <- id
edges <- edges %>%
group_by(.data$.id) %>%
top_n(1) %>%
ungroup()
}
as.data.frame(edges, stringsAsFactors = FALSE)
} |
summary.phenology <- function(object,
resultmcmc = NULL,
chain = 1,
series = "all",
replicate.CI.mcmc = "all",
replicate.CI = 10000,
level= 0.95,
print = TRUE,
...) {
formatpar <- getFromNamespace(".format_par", ns="phenology")
dailycount <- getFromNamespace(".daily_count", ns="phenology")
if (print) {
cat(paste("Number of timeseries: ", length(object$data), "\n", sep=""))
for (i in 1:length(object$data)) {
cat(paste(names(object$data[i]), "\n", sep=""))
}
cat(paste("Date uncertainty management: ", object$method_incertitude, "\n", sep=""))
cat(paste("Managment of zero counts: ", object$zero_counts, "\n", sep=""))
cat("Fitted parameters:\n")
for (i in 1:length(object$par)) {
cat(paste(names(object$par[i]), "=", object$par[i], " SE ", object$se[i], "\n", sep=""))
}
if (length(object$fixed.parameters)>0) {
cat("Fixed parameters:\n")
for (i in 1:length(object$fixed.parameters)) {
cat(paste(names(object$fixed.parameters[i]), "=", object$fixed.parameters[i], "\n", sep=""))
}
}
cat(paste("Ln L: ", object$value, "\n", sep=""))
cat(paste("Parameter number: ", length(object$par), "\n", sep=""))
cat(paste("AIC: ", 2*object$value+2*length(object$par), "\n", sep=""))
}
if (is.numeric(series)) series <- names(object$data)[series]
if (any(series == "all")) series <- names(object$data)
nseries <- length(series)
rna <- rep(NA, nseries)
probs <- c((1-level)/2, 0.5, 1-(1-level)/2)
retdf <- data.frame(series=series,
"without_obs_Mean"=rna,
"with_obs_Mean"=rna,
"without_obs_Low_ML"=rna,
"without_obs_Median_ML"=rna,
"without_obs_High_ML"=rna,
"without_obs_Mean_ML"=rna,
"without_obs_Var_ML"=rna,
"with_obs_Low_ML"=rna,
"with_obs_Median_ML"=rna,
"with_obs_High_ML"=rna,
"with_obs_Mean_ML"=rna,
"with_obs_Var_ML"=rna,
"without_obs_Low_MCMC"=rna,
"without_obs_Median_MCMC"=rna,
"without_obs_High_MCMC"=rna,
"without_obs_Mean_MCMC"=rna,
"without_obs_Var_MCMC"=rna,
"with_obs_Low_MCMC"=rna,
"with_obs_Median_MCMC"=rna,
"with_obs_High_MCMC"=rna,
"with_obs_Mean_MCMC"=rna,
"with_obs_Var_MCMC"=rna,
"NbObservations"=rna,
"NbMonitoredDays"=rna,
stringsAsFactors = FALSE)
rownames(retdf) <- series
klist_mcmc <- list()
klist_ML <- list()
klist_Mean <- list()
for (nmser in series) {
if (print) {
tx <- paste0("Timeseries: ", nmser)
cat(paste0(rep("-", nchar(tx)), collapse=""), "\n")
cat(tx, "\n")
cat(paste0(rep("-", nchar(tx)), collapse=""), "\n")
}
dref <- object$Dates[[nmser]]["reference"]
nday <- ifelse(as.POSIXlt(dref+365)$mday==as.POSIXlt(dref)$mday, 365, 366)
observedPontes <- data.frame(ordinal=object$data[[nmser]][, "ordinal"],
observed=object$data[[nmser]][, "nombre"])
if (any(!is.na(object$data[[nmser]][, "ordinal2"]))) {
for (i in which(!is.na(object$data[[nmser]][, "ordinal2"]))) {
rnge <- (object$data[[nmser]][i, "ordinal"]+1):(object$data[[nmser]][i, "ordinal2"])
observedPontes <- rbind(observedPontes,
data.frame(ordinal= rnge,
observed=rep(0, length(rnge))))
}
}
parg <- formatpar(c(object$par, object$fixed.parameters), nmser)
cof <- NULL
if ((!is.null(object$add.cofactors)) & (!is.null(object$cofactors))) {
j <- 0:(nday-1)
cof <- object$cofactors[object$cofactors$Date %in% (dref+j), ]
cof <- cof[, -1, drop=FALSE]
cof <- as.data.frame(cbind(Date=j, cof))
}
dc_mean <- dailycount(d=0:(nday-1), xpar=parg,
cofactors=cof,
add.cofactors=object$add.cofactors,
print=FALSE, zero=1E-9)
retdf[nmser, "without_obs_Mean"] <- sum(dc_mean)
retdf[nmser, "NbObservations"] <- sum(observedPontes$observed)
retdf[nmser, "NbMonitoredDays"] <- nrow(observedPontes)
if (print) {
cat("Total estimate not taking into account the observations: ")
cat(paste0("Mean=", retdf[nmser, "without_obs_Mean"], "\n"))
}
SDMin <- NULL
SDMax <- NULL
for (mu in dc_mean) {
qnb <- qnbinom(p = c(probs[1], probs[3]),
size=c(object$par, object$fixed.parameters)["Theta"],
mu=mu)
SDMin <- c(SDMin, qnb[1])
SDMax <- c(SDMax, qnb[2])
}
dc_mean <- data.frame(Date=dref+(0:(nday-1)), Ordinal = 0:(nday-1), Mean=NA, SD.Low=SDMin, SD.High=SDMax, Observed=NA, Modelled=dc_mean)
dc_mean[match(observedPontes[, "ordinal"], dc_mean[, "Ordinal"]), "Observed"] <- observedPontes[, "observed"]
dc_mean[, "Mean"] <- ifelse(is.na(dc_mean[, "Observed"]), dc_mean[, "Modelled"], dc_mean[, "Observed"])
if (!is.null(cof)) {
dc_mean <- cbind(dc_mean, cof[, -1, drop=FALSE])
}
rownames(dc_mean) <- dc_mean[, "Ordinal"]
k <- list(dc_mean)
names(k) <- nmser
klist_Mean <- c(klist_Mean, k)
retdf[nmser, "with_obs_Mean"] <- sum(dc_mean[, "Mean"])
if (print) {
cat("Total estimate taking into account the observations: ")
cat(paste0("Mean=", retdf[nmser, "with_obs_Mean"], "\n"))
}
pfixed <- object$fixed.parameters
sepfixed <- pfixed[strtrim(names(pfixed), 3)=="se
pfixed <- pfixed[strtrim(names(pfixed), 3) != "se
if (!is.null(sepfixed)) names(sepfixed) <- substring(names(sepfixed), 4)
pfixed.df <- data.frame()
pfixed.df.mcmc <- data.frame()
replicate.CI.mcmc.x <- NULL
if (!is.null(resultmcmc)) {
if (replicate.CI.mcmc == "all") {
replicate.CI.mcmc.x <- nrow(resultmcmc$resultMCMC[[chain]])
} else {
replicate.CI.mcmc.x <- replicate.CI.mcmc
}
}
if (!is.null(pfixed)) {
for (i in seq_along(pfixed)) {
dfadd <- data.frame()
dfadd.mcmc <- data.frame()
if (!is.na(sepfixed[names(pfixed[i])])) {
if (!is.null(replicate.CI)) {
dfadd <- data.frame(rnorm(n=replicate.CI, mean=unname(pfixed[i]), sd=sepfixed[names(pfixed[i])]))
colnames(dfadd) <- names(pfixed[i])
}
if (!is.null(replicate.CI.mcmc.x)) {
dfadd.mcmc <- data.frame(rnorm(n=replicate.CI.mcmc.x, mean=unname(pfixed[i]), sd=sepfixed[names(pfixed[i])]))
colnames(dfadd.mcmc) <- names(pfixed[i])
}
} else {
if (!is.null(replicate.CI)) {
dfadd <- data.frame(rep(unname(pfixed[i]), replicate.CI))
colnames(dfadd) <- names(pfixed[i])
}
if (!is.null(replicate.CI.mcmc.x)) {
dfadd.mcmc <- data.frame(rep(unname(pfixed[i]), replicate.CI.mcmc.x))
colnames(dfadd.mcmc) <- names(pfixed[i])
}
}
if (ncol(pfixed.df.mcmc) ==0 ) {
pfixed.df.mcmc <- dfadd.mcmc
} else {
pfixed.df.mcmc <- cbind(pfixed.df.mcmc, dfadd.mcmc)
}
if (ncol(pfixed.df) ==0 ) {
pfixed.df <- dfadd
} else {
pfixed.df <- cbind(pfixed.df, dfadd)
}
}
}
pfixed.df <- as.matrix(pfixed.df)
pfixed.df.mcmc <- as.matrix(pfixed.df.mcmc)
lnday <- 0:(nday-1)
opord <- observedPontes[, "ordinal"]+1
opnumb <- observedPontes[, "observed"]
if (!is.null(resultmcmc)) {
lmcmc <- nrow(resultmcmc$resultMCMC[[chain]])
mcmctobeused <- 1:lmcmc
if (replicate.CI.mcmc != "all") {
repl <- ifelse(nrow(resultmcmc$resultMCMC[[chain]]) <= replicate.CI.mcmc, TRUE, FALSE)
mcmctobeused <- sample(x=mcmctobeused,
size=replicate.CI.mcmc,
replace = repl)
} else {
replicate.CI.mcmc <- nrow(resultmcmc$resultMCMC[[chain]])
}
if (ncol(pfixed.df.mcmc) != 0) {
dailydata <- sapply(X = 1:replicate.CI.mcmc, FUN=function(xxx) {
px <- c(resultmcmc$resultMCMC[[chain]][mcmctobeused[xxx], ], pfixed.df.mcmc[xxx, ])
xparec <- formatpar(px, nmser)
dailycount(lnday, xparec, print=FALSE, cofactors=cof,
add.cofactors=object$add.cofactors)
})
} else {
dailydata <- sapply(X = 1:replicate.CI.mcmc, FUN=function(xxx) {
px <- c(resultmcmc$resultMCMC[[chain]][mcmctobeused[xxx], ])
xparec <- formatpar(px, nmser)
dailycount(lnday, xparec, print=FALSE, cofactors=cof,
add.cofactors=object$add.cofactors)
})
}
synthesisPontes <- apply(X = dailydata, MARGIN = 2, FUN=sum)
synthesisPontes_withObs <- apply(X = dailydata, MARGIN = 2, FUN=function(xxx) {
xxx[opord] <- opnumb
sum(xxx)
})
k <-as.data.frame(t(apply(X = dailydata, MARGIN=1,
FUN = function(x) {quantile(x, probs=probs)})))
k <- list(cbind(Ordinal=lnday, k))
names(k) <- nmser
klist_mcmc <- c(klist_mcmc, k)
k <- unname(quantile(synthesisPontes, probs=probs))
retdf[nmser, c("without_obs_Low_MCMC", "without_obs_Median_MCMC", "without_obs_High_MCMC")] <- k
retdf[nmser, c("without_obs_Mean_MCMC", "without_obs_Var_MCMC")] <- c(mean(synthesisPontes), var(synthesisPontes))
if (print) {
cat("Total estimate not taking into account the observations MCMC-based:\n")
cat(paste0("Low=", k[1], " Median=", k[2], " High=", k[3], "\n"))
}
k <- unname(quantile(synthesisPontes_withObs, probs=probs))
retdf[nmser, c("with_obs_Low_MCMC", "with_obs_Median_MCMC", "with_obs_High_MCMC")] <- k
retdf[nmser, c("with_obs_Mean_MCMC", "with_obs_Var_MCMC")] <- c(mean(synthesisPontes_withObs), var(synthesisPontes_withObs))
if (print) {
cat("Total estimate taking into account the observations MCMC-based:\n")
cat(paste0("Low=", k[1], " Median=", k[2], " High=", k[3], "\n"))
}
} else {
k <- list(NA)
names(k) <- nmser
klist_mcmc <- c(klist_mcmc, k)
}
if (!is.null(object$hessian)) {
if (all(names(object$par) %in% colnames(object$hessian))) {
par2 <- RandomFromHessianOrMCMC(
Hessian = object$hessian,
fitted.parameters = object$par,
fixed.parameters = object$fixed.parameters,
probs = c(0.025, 0.5, 0.975),
replicates = replicate.CI, silent=TRUE)
par2 <- par2$random
dailydata <- sapply(1:replicate.CI, FUN=function(xxx) {
dailycount(lnday, formatpar(c(par2[xxx, ]), nmser), print=FALSE, cofactors=cof,
add.cofactors=object$add.cofactors)
})
k <- as.data.frame(t(apply(X = dailydata, MARGIN=1,
FUN = function(x) {quantile(x, probs=probs)})))
k <- list(cbind(Ordinal=lnday, k))
names(k) <- nmser
klist_ML <- c(klist_ML, k)
synthesisPontes <- apply(X = dailydata, MARGIN = 2, FUN=sum)
synthesisPontes_withObs <- apply(X = dailydata, MARGIN = 2, FUN=function(xxx) {
xxx[opord] <- opnumb
sum(xxx)
})
k <- unname(quantile(synthesisPontes, probs=probs))
retdf[nmser, c("without_obs_Low_ML", "without_obs_Median_ML", "without_obs_High_ML")] <- k
retdf[nmser, c("without_obs_Mean_ML", "without_obs_Var_ML")] <- c(mean(synthesisPontes), var(synthesisPontes))
if (print) {
cat("Total estimate not taking into account the observations ML-based:\n")
cat(paste0("Low=", k[1], " Median=", k[2], " High=", k[3], "\n"))
}
k <- unname(quantile(synthesisPontes_withObs, probs=probs))
retdf[nmser, c("with_obs_Low_ML", "with_obs_Median_ML", "with_obs_High_ML")] <- k
retdf[nmser, c("with_obs_Mean_ML", "with_obs_Var_ML")] <- c(mean(synthesisPontes_withObs), var(synthesisPontes_withObs))
if (print) {
cat("Total estimate taking into account the observations ML-based:\n")
cat(paste0("Low=", k[1], " Median=", k[2], " High=", k[3], "\n"))
}
} else {
k <- list(NA)
names(k) <- nmser
klist_ML <- c(klist_ML, k)
}
} else {
k <- list(NA)
names(k) <- nmser
klist_ML <- c(klist_ML, k)
}
}
rout <- list(synthesis=retdf, details_mcmc=klist_mcmc,
details_ML=klist_ML, details_Mean=klist_Mean)
class(rout) <- "phenologyout"
return(invisible(rout))
} |
tokens_segment <- function(x, pattern,
valuetype = c("glob", "regex", "fixed"),
case_insensitive = TRUE,
extract_pattern = FALSE,
pattern_position = c("before", "after"),
use_docvars = TRUE) {
UseMethod("tokens_segment")
}
tokens_segment.tokens <- function(x, pattern,
valuetype = c("glob", "regex", "fixed"),
case_insensitive = TRUE,
extract_pattern = FALSE,
pattern_position = c("before", "after"),
use_docvars = TRUE) {
x <- as.tokens(x)
valuetype <- match.arg(valuetype)
extract_pattern <- check_logical(extract_pattern)
pattern_position <- match.arg(pattern_position)
use_docvars <- check_logical(use_docvars)
if (!use_docvars)
docvars(x) <- NULL
attrs <- attributes(x)
type <- types(x)
ids <- object2id(pattern, type, valuetype, case_insensitive,
field_object(attrs, "concatenator"))
if ("" %in% pattern) ids <- c(ids, list(0))
if (pattern_position == "before") {
result <- qatd_cpp_tokens_segment(x, type, ids, extract_pattern, 1)
} else {
result <- qatd_cpp_tokens_segment(x, type, ids, extract_pattern, 2)
}
attrs[["docvars"]] <- reshape_docvars(attrs[["docvars"]], attr(result, "docnum"))
field_object(attrs, "unit") <- "segments"
if (extract_pattern)
attrs[["docvars"]][["pattern"]] <- attr(result, "pattern")
rebuild_tokens(result, attrs)
} |
NULL
makeModelComponentsMF <- function(formula, data, weights=NULL, offset=NULL, subset=NULL,
na.action=getOption("na.action"),
drop.unused.levels=FALSE, xlev=NULL, sparse=FALSE, ...)
{
cl <- match.call(expand.dots=FALSE)
cl$sparse <- cl$`...` <- NULL
cl[[1]] <- quote(stats::model.frame)
mf <- eval.parent(cl)
x <- if(!is.null(sparse) && sparse)
Matrix::sparse.model.matrix(attr(mf, "terms"), mf)[, -1, drop=FALSE]
else model.matrix(attr(mf, "terms"), mf)[, -1, drop=FALSE]
y <- model.response(mf)
weights <- model.extract(mf, "weights")
offset <- model.extract(mf, "offset")
if(is.null(weights))
weights <- rep(1, nrow(mf))
xlev <- .getXlevels(attr(mf, "terms"), mf)
list(x=x, y=y, weights=weights, offset=offset, terms=terms(mf), xlev=xlev)
}
makeModelComponents <- function(formula, data, weights=NULL, offset=NULL, subset=NULL, na.action=getOption("na.action"),
drop.unused.levels=FALSE, xlev=NULL, sparse=FALSE, ...)
{
if(!is.data.frame(data))
{
data <- as.data.frame(data)
warning("input data was converted to data.frame")
}
rhs <- formula[[length(formula)]]
lhs <- if(length(formula) == 3) formula[[2]] else NULL
lhsVars <- all.vars(lhs)
rhsTerms <- additiveTerms(rhs, base::setdiff(names(data), lhsVars))
rhs <- rebuildRhs(rhsTerms)
rhsVars <- all.vars(rhs)
if(!missing(subset))
{
subset <- substitute(subset)
if(!is.null(subset))
data <- data[eval(subset, data, parent.frame()), , drop=FALSE]
}
offset <- substitute(offset)
offsetVals <- eval(offset, data, parent.frame())
if(!missing(weights) && !is.null(weights <- substitute(weights)))
weightVals <- eval(weights, data, parent.frame())
else weightVals <- rep(1, nrow(data))
if(!is.function(na.action))
na.action <- get(na.action, mode="function")
if(!is.null(offsetVals))
{
data <- na.action(cbind.data.frame(data[c(lhsVars, rhsVars)], offsetVals, weightVals))
offsetVals <- data$offsetVals
}
else
{
data <- na.action(cbind.data.frame(data[c(lhsVars, rhsVars)], weightVals))
offsetVals <- NULL
}
weightVals <- data$weightVals
if(length(xlev) == 0)
xlev <- list(NULL)
else if(is.list(xlev) && !is.list(xlev[[1]]))
xlev <- list(xlev)
matrs <- mapply(function(x, xlev) {
xvars <- all.vars(x)
xnames <- all.names(x)
isExpr <- !identical(xvars, xnames)
anyFactors <- any(sapply(data[xvars], function(x) is.factor(x) || is.character(x)))
if(anyFactors || isExpr || sparse)
{
xlev <- xlev[names(xlev) %in% unique(c(deparse(x), xvars))]
f <- eval(call("~", substitute(0 + .x, list(.x=x))))
mf <- model.frame(f, data, drop.unused.levels=drop.unused.levels, xlev=xlev, na.action=na.action)
out <- if(sparse)
Matrix::sparse.model.matrix(terms(mf), mf, xlev=xlev)
else model.matrix(terms(mf), mf, xlev=xlev)
attr(out, "xlev") <- lapply(mf, function(x)
{
if(is.factor(x)) levels(x) else if(is.character(x)) sort(unique(x)) else NULL
})
}
else if(length(xvars) == 1)
{
out <- na.action(data[[xvars]])
dim(out) <- c(length(out), 1)
colnames(out) <- xvars
}
else out <- as.matrix(na.action(data[xvars]))
out
}, rhsTerms, xlev, SIMPLIFY=FALSE)
terms <- call("~", rhs)
xlev <- lapply(matrs, attr, "xlev")
list(x=do.call(cbind, matrs), y=eval(lhs, data), weights=weightVals, offset=offsetVals, terms=terms, xlev=xlev)
}
additiveTerms <- function(f, vars)
{
plus <- quote(`+`)
minus <- quote(`-`)
dot <- quote(.)
tilde <- quote(`~`)
rhs <- if(!is.symbol(f) && identical(f[[1]], tilde)) f[[length(f)]] else f
l <- list()
term <- function(x)
{
if(identical(x, dot))
rev(lapply(vars, as.name))
else x
}
repeat
{
if(is.call(rhs) && (identical(rhs[[1]], plus) || identical(rhs[[1]], minus)))
{
if(identical(rhs[[1]], plus))
l <- c(l, term(rhs[[3]]))
else if(identical(rhs[[1]], minus))
vars <- base::setdiff(vars, deparse(rhs[[length(rhs)]]))
rhs <- rhs[[2]]
}
else
{
l <- c(l, term(rhs))
break
}
}
rev(l)
}
rebuildRhs <- function(rhs)
{
expr <- rhs[[1]]
if(length(rhs) > 1) for(i in 2:length(rhs))
{
expr <- substitute(a + b, list(a=expr, b=rhs[[i]]))
}
expr
} |
test_that("plotBiomassObservedVsModel works", {
local_edition(3)
params <- NS_params
expect_error(plotBiomassObservedVsModel(params))
species_params(params)$biomass_observed <-
c(0.8, 61, 12, 35, 1.6, 20, 10, 7.6, 135, 60, 30, 78)
species_params(params)$biomass_cutoff <- 10
params <- calibrateBiomass(params)
dummy <- plotBiomassObservedVsModel(params, return_data = T)
expect_equal(dummy$observed, species_params(params)$biomass_observed)
expect_error(plotBiomassObservedVsModel(params, species = rep(F, 12)))
params2 = params
species_params(params2)$biomass_observed[c(1, 7, 10)] = NA
dummy <- plotBiomassObservedVsModel(params2, return_data = T)
expect_equal(as.character(dummy$species),
species_params(params)$species[!is.na(species_params(params2)$biomass_observed)])
expect_equal(dummy$observed,
species_params(params2)$biomass_observed
[!is.na(species_params(params2)$biomass_observed)])
dummy <- plotBiomassObservedVsModel(params2, return_data = T,
show_unobserved = TRUE)
expect_equal(as.character(dummy$species),
species_params(params)$species)
sp_select = c(1, 4, 7, 10, 11, 12)
dummy <- plotBiomassObservedVsModel(params, species = sp_select, return_data = T)
expect_equal(nrow(dummy), length(sp_select))
expect_equal(dummy$observed,
species_params(params)$biomass_observed[sp_select])
dummy <- plotBiomassObservedVsModel(params, return_data = T)
p <- plotBiomassObservedVsModel(params)
expect_true(is.ggplot(p))
expect_identical(p$labels$x, "observed biomass [g]")
expect_identical(p$labels$y, "model biomass [g]")
expect_identical(p$data, dummy)
vdiffr::expect_doppelganger("plotBiomassObservedVsModel", p)
}) |
appendtofolderh <- function(fh, df, key, after = FALSE)
{
name.fh <- deparse(substitute(fh))
name.df <- deparse(substitute(df))
if (!is.folderh(fh))
stop("fh must be an object of class 'folderh'.")
if (!(key %in% colnames(df)))
stop("There is no ", key, " column in ", name.df, " data frame.")
if (!after) {
if (!(key %in% colnames(fh[[1]])))
stop(paste0("There is no ", key, " column in ", paste(names(fh)[1], collapse = ", "),
" data frame of ", name.fh, "."))
fh.ret <- c(list(df), fh)
keys <- c(key, attr(fh, "keys"))
names(fh.ret)[1] <- name.df
} else {
if (!(key %in% colnames(fh[[length(fh)]])))
stop(paste0("There is no ", key, " column in ", paste(names(fh)[length(fh)],
collapse = ", "), " data frame of ", name.fh, "."))
fh.ret <- c(fh, list(df))
keys <- c(attr(fh, "keys"), key)
names(fh.ret)[length(fh)+1] <- name.df
}
class(fh.ret) <- "folderh"
attr(fh.ret, "keys") <- keys
return(invisible(fh.ret))
} |
calc.parameters.monitor.climate <- function(final_values, ranking.values = NULL)
{
outfile_path <- file.path(tempdir(),"mc_parameters.csv")
if(file.exists(outfile_path)){
unlink(outfile_path)
}
utils::write.csv(final_values, file = outfile_path, row.names = FALSE)
if(!(is.null(ranking.values))){
outfile_ranking_path <- file.path(tempdir(),"mc_ranking.csv")
if(file.exists(outfile_ranking_path)){
unlink(outfile_ranking_path)
}
utils::write.csv(ranking.values, file = outfile_ranking_path, row.names = FALSE)
}
} |
drawAxes <- function(x, which = "x", main = TRUE, label = TRUE, opts,
sub = 0, heightOnly = FALSE,
layout.only = FALSE, pos = NULL) {
fun <- ifelse(is.numeric(x), .numericAxis, .categoricalAxis)
fun(x, which, main, label, opts, sub, heightOnly, layout.only, pos)
}
.numericAxis <- function(x, which = "x", main = TRUE, label = TRUE, opts,
sub = 0, heightOnly = FALSE,
layout.only = FALSE, pos = NULL) {
x <- transform_axes(x, which, opts, label)
at <- x$at
labs <- x$labs
if (!is.logical(labs)) labs <- format(labs)
switch(which,
"x" = {
if (main) {
grid.xaxis(
gp = gpar(cex = opts$cex.axis),
main = main,
at = at,
label = labs,
name = paste(
paste0("inz-xaxis-", pos), opts$rowNum, opts$colNum,
sep = "."
)
)
} else {
xlim <- current.viewport()$xscale
pushViewport(viewport(
x = 0.5, y = 1, height = unit(sub, "in"),
just = "bottom", xscale = xlim
))
grid.xaxis(
gp = gpar(cex = opts$cex.axis),
at = at,
label = labs,
main = FALSE,
name = paste("inz-xaxis-top", opts$rowNum, opts$colNum,
sep = ".")
)
upViewport()
}
},
"y" = {
yax <- yaxisGrob(
gp = gpar(cex = opts$cex.axis),
main = main,
at = at,
label = labs,
name = paste(
paste0("inz-yaxis-", pos), opts$rowNum, opts$colNum,
sep = "."
)
)
if (label)
yax <- editGrob(
yax,
edits = gEdit(
"labels",
rot = ifelse(main, 90, 270),
hjust = 0.5,
vjust = ifelse(main, 0, -0.5)
)
)
grid.draw(yax)
}
)
}
.categoricalAxis <- function(x, which = "x", main = TRUE, label = TRUE, opts,
sub = 0, heightOnly = FALSE,
layout.only = FALSE, pos = NULL) {
if (is.null(opts$ZOOM))
x.lev <- levels(x)
else {
ZOOM <- opts$ZOOM
ww <- ZOOM[1]:(sum(ZOOM) - 1)
nl <- length(levels(x))
ww <- ww - nl * (ww > nl)
x.lev <- levels(x)[ww]
}
switch(which,
"x" = {
rot <- opts$rot
labText <- textGrob(
x.lev,
x = unit( (0:length(x.lev))[-1] - 0.5, "native"),
y = if (rot) unit(-0.5, "mm") else unit(-1, "lines"),
just = if (rot) c("right", "top") else "center",
rot = ifelse(rot, 30, 0),
gp = gpar(cex = opts$cex.axis * ifelse(rot, 0.8, 1)),
name = "inz-labelText"
)
wm <- which.max(nchar(as.character(x.lev)))
tt <- textGrob(levels(x)[wm])
labwid <- convertWidth(grobWidth(tt), "mm", valueOnly = TRUE)
if (heightOnly) {
return(grobHeight(labText))
} else {
grid.draw(labText)
}
},
"y" = {
if (!is.null(x) & !layout.only) {
labels <- levels(x)
Nlab <- length(labels)
for (i in 1:Nlab) {
seekViewport(paste0("VP:plotregion-", i))
grid.text(
labels[i], x = unit(-0.5, "lines"),
just = "right", gp = gpar(cex = opts$cex.axis)
)
upViewport()
}
}
}
)
}
addGrid <- function(x = FALSE, y = FALSE, gen, opts) {
if (!opts$grid.lines) return()
if (!any(x, y)) return()
col.grid <- opts$col.grid
if (col.grid == "default") {
if (any(col2rgb(opts$bg) <= 230)) {
col.grid <- "
} else {
col.grid <- "
}
}
if (x) {
at.x <- pretty(gen$LIM[1:2])
at.X <- rep(at.x, each = 2)
at.Y <- rep(current.viewport()$yscale, length(at.x))
grid.polyline(
at.X, at.Y, id.lengths = rep(2, length(at.X) / 2),
default.units = "native",
gp = gpar(col = col.grid, lwd = 1),
name = paste("inz-x-grid", opts$rowNum, opts$colNum, sep = ".")
)
}
if (y) {
at.y <- pretty(gen$LIM[3:4])
at.Y <- rep(at.y, each = 2)
at.X <- rep(current.viewport()$xscale, length(at.y))
grid.polyline(
at.X, at.Y, id.lengths = rep(2, length(at.Y) / 2),
default.units = "native",
gp = gpar(col = col.grid, lwd = 1),
name = paste("inz-y-grid", opts$rowNum, opts$colNum, sep = ".")
)
}
}
transform_axes <- function(x, which, opts, label, adjust.vp = TRUE) {
xt <- x
breaks <- NULL
if (!is.null(opts$transform[[which]])) {
switch(opts$transform[[which]],
"datetime" = {
xt <- as.POSIXct(x,
origin = "1970-01-01",
tz = opts$transform$extra[[which]]$tz
)
},
"date" = {
xt <- as.Date(x, origin = "1970-01-01")
},
"time" = {
xt <- chron::chron(times. = x)
},
"log" = {
breaks <- scales::log_trans()$breaks(exp(x))
breaks <- log(breaks)
if (all(round(breaks) == breaks))
names(breaks) <- paste0("e^", breaks)
else {
names(breaks) <- round(exp(breaks))
}
},
"log10" = {
breaks <- scales::log10_trans()$breaks(10^x)
names(breaks) <- breaks
breaks <- log10(breaks)
},
"bar_percentage" = {
breaks <- scales::pretty_breaks()(xt)
names(breaks) <- breaks * 100
},
"bar_counts" = {
},
{
warning(sprintf(
"Unsupported transformation `%s`",
opts$transform[[which]]
))
xt <- x
}
)
}
if (is.null(breaks)) {
breaks <- scales::breaks_pretty()(xt)
}
if (adjust.vp) {
xl <- current.viewport()[[switch(which, "x" = "xscale", y = "yscale")]]
breaks <- breaks[breaks > xl[1] & breaks < xl[2]]
if (length(breaks) == 0)
breaks <- seq(min(xl), max(xl), by = 1)
}
at <- as.numeric(breaks)
labs <- FALSE
if (label) labs <- if (!is.null(names(breaks))) names(breaks) else at
list(at = at, labs = labs)
} |
em.ic <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL,
llhdval = NULL){
if(is.null(emobj)){
emobj <- list(n = nrow(x), pi = pi, Mu = Mu, LTSigma = LTSigma)
}
emobj$llhdval <- logL(x, emobj = emobj)
emobj$adjM <- length(emobj$pi) - 1 + length(emobj$Mu) + length(emobj$LTSigma)
ret <- list()
ret$AIC <- em.aic(x, emobj = emobj)
ret$BIC <- em.bic(x, emobj = emobj)
ret$ICL <- em.icl(x, emobj = emobj)
ret$ICL.BIC <- em.icl.bic(x, emobj = emobj)
ret$CLC <- em.clc(x, emobj = emobj)
ret
}
em.aic <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL){
if(is.null(emobj)){
emobj <- list(pi = pi, Mu = Mu, LTSigma = LTSigma)
}
if(is.null(emobj$adjM)){
emobj$adjM <- length(emobj$pi) - 1 + length(emobj$Mu) + length(emobj$LTSigma)
}
if(is.null(emobj$llhdval)){
emobj$llhdval <- logL(x, emobj = emobj)
}
-2 * emobj$llhdval + 2 * emobj$adjM
}
em.bic <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL){
if(is.null(emobj)){
emobj <- list(pi = pi, Mu = Mu, LTSigma = LTSigma)
}
if(is.null(emobj$n)){
emobj$n <- nrow(x)
}
if(is.null(emobj$adjM)){
emobj$adjM <- length(emobj$pi) - 1 + length(emobj$Mu) + length(emobj$LTSigma)
}
if(is.null(emobj$llhdval)){
emobj$llhdval <- logL(x, emobj = emobj)
}
-2 * emobj$llhdval + log(emobj$n) * emobj$adjM
}
em.icl <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL){
if(is.null(emobj)){
emobj <- list(pi = pi, Mu = Mu, LTSigma = LTSigma)
}
if(is.null(emobj$n)){
emobj$n <- nrow(x)
}
if(is.null(emobj$adjM)){
emobj$adjM <- length(emobj$pi) - 1 + length(emobj$Mu) + length(emobj$LTSigma)
}
if(is.null(emobj$llhdval)){
emobj$llhdval <- logL(x, emobj = emobj)
}
Z.unnorm <- e.step(x, emobj = emobj, norm = FALSE)$Gamma
logL.map <- do.call("c", lapply(1:emobj$n, function(i){ max(Z.unnorm[i, ]) }))
-2 * sum(logL.map) + log(emobj$n) * emobj$adjM
}
em.icl.bic <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL){
if(is.null(emobj)){
emobj <- list(pi = pi, Mu = Mu, LTSigma = LTSigma)
}
if(is.null(emobj$n)){
emobj$n <- nrow(x)
}
if(is.null(emobj$adjM)){
emobj$adjM <- length(emobj$pi) - 1 + length(emobj$Mu) + length(emobj$LTSigma)
}
if(is.null(emobj$llhdval)){
emobj$llhdval <- logL(x, emobj = emobj)
}
Z <- e.step(x, emobj = emobj)$Gamma
Z.unnorm <- e.step(x, emobj = emobj, norm = FALSE)$Gamma
log.Z <- Z.unnorm - log(dmixmvn(x, emobj = emobj))
logL.EN <- Z * log.Z
-2 * (emobj$llhdval + sum(logL.EN)) + log(emobj$n) * emobj$adjM
}
em.clc <- function(x, emobj = NULL, pi = NULL, Mu = NULL, LTSigma = NULL){
if(is.null(emobj)){
emobj <- list(pi = pi, Mu = Mu, LTSigma = LTSigma)
}
if(is.null(emobj$llhdval)){
emobj$llhdval <- logL(x, emobj = emobj)
}
Z <- e.step(x, emobj = emobj)$Gamma
Z.unnorm <- e.step(x, emobj = emobj, norm = FALSE)$Gamma
log.Z <- Z.unnorm - log(dmixmvn(x, emobj = emobj))
logL.EN <- Z * log.Z
-2 * (emobj$llhdval + sum(logL.EN))
} |
test_that("Item Category Constraint", {
out <- itemCategoryConstraint(2, factor(c(1, 1, 2, 2)), "=", targetValues = c(1, 2), itemIDs = 1:4)
expect_equal(out$A_binary[1, ], c(1, 1, 0, 0, rep(0, 4)))
expect_equal(out$A_binary[2, ], c(rep(0, 4), 1, 1, 0, 0))
expect_equal(out$A_binary[3, ], c(0, 0, 1, 1, rep(0, 4)))
expect_equal(out$A_binary[4, ], c(rep(0, 4), 0, 0, 1, 1))
out <- itemCategoryConstraint(1, factor(c(1, 2, 3)), targetValues = c(1, 1, 1), itemIDs = 1:3)
expect_equal(out$A_binary[1, ], c(1, 0, 0))
expect_equal(out$A_binary[2, ], c(0, 1, 0))
expect_equal(out$A_binary[3, ], c(0, 0, 1))
expect_is(out, "constraint")
})
test_that("Item Category Constraint returns errors and warnings", {
expect_error(itemCategoryConstraint(1, c(1, 2, 3), targetValues = c(1, 1, 1)),
"'itemCategories' should be a factor.")
expect_error(itemCategoryConstraint(2, factor(c(1, 2, 2)), "=", targetValues = c(1, 2), itemIDs = 1:2),
"The length of 'itemCategories' and 'itemIDs' should be identical.")
expect_error(itemCategoryConstraint(2, factor(c(1, 2, 2, 1)), "=", targetValues = 1),
"The number of 'targetValues' should correspond with the number of levels in 'itemCategories'.")
expect_error(itemCategoryConstraint(2:3, factor(c(1, 2, 2, 1)), "=", targetValues = c(1, 2),
itemIDs = 1:4),
"'nForms' should be a vector of length 1.")
warns <- capture_warnings(out <- itemCategoryConstraint(2, factor(c(1, 1, 2, 2)), "=", targetValues = c(1, 2)))
warns[[1]] <- "Argument 'itemIDs' is missing. 'itemIDs' will be generated automatically."
})
test_that("Item Category Min Max and Threshold", {
minMax <- itemCategoryRangeConstraint(2, factor(rep(1:2, 10)), range = cbind(min = c(3, 4), max = c(5, 6)), itemIDs = 1:20)
expect_equal(minMax,
combine2Constraints(itemCategoryMinConstraint(2, factor(rep(1:2, 10)), c(3, 4), itemIDs = 1:20),
itemCategoryMaxConstraint(2, factor(rep(1:2, 10)), c(5, 6), itemIDs = 1:20)))
expect_equal(minMax, itemCategoryDeviationConstraint(2, factor(rep(1:2, 10)), c(4, 5), c(1, 1), itemIDs = 1:20))
max <- itemCategoryMaxConstraint(1, factor(c(1, 2, 3)), max = c(1, 1, 1), itemIDs = 1:3)
expect_equal(max, itemCategoryConstraint(1, factor(c(1, 2, 3)), targetValues = c(1, 1, 1), itemIDs = 1:3))
min <- itemCategoryMinConstraint(1, factor(c(1, 2, 3)), min = c(1, 1, 1), itemIDs = 1:3)
expect_equal(min$A_binary[1, ], c(1, 0, 0))
expect_equal(min$A_binary[2, ], c(0, 1, 0))
expect_equal(min$A_binary[3, ], c(0, 0, 1))
expect_is(minMax, "constraint")
})
test_that("Item Category Range returns errors", {
expect_error(itemCategoryRangeConstraint(2, factor(rep(1:2, 10)), range = cbind(min = c(6, 4), max = c(5, 6))),
"The values in the first column of 'range' should be smaller than the values in the second column of 'range'.")
expect_error(itemCategoryRangeConstraint(2, factor(rep(1:2, 10)),
range = c(min = c(4, 4), max = c(5, 6))),
"itemCategories")
expect_error(itemCategoryRangeConstraint(2, factor(rep(1:3, 10)),
range = rbind(min = c(4, 4, 2), max = c(5, 6, 3))),
"itemCategories")
expect_error(itemCategoryRangeConstraint(2, factor(rep(1:2, 10)),
range = rbind(min = c(4, 4, 2), max = c(5, 6, 3))),
"itemCategories")
expect_error(itemCategoryRangeConstraint(2, factor(rep(1:2, 10)),
range = cbind(min = c(3, 4), max = c(5, 6)),
info_text = c("too", "many", "strings")),
"'info_text' should be a character string of length equal to to the number of levels in 'itemCategories'.")
}) |
goodnessFilling <-
function() {
showPANgoodFill1 <- function() {
refreshDataSetsList(outp = FALSE)
createSubPanR4C1()
createTITLE(labTitle = "CHECK FILLING")
createTsRb(labTitle = "Time series with no artificial gaps",
variableName = "selTsP0")
createOK(labTitle = "NEXT", action = goodFill1OnOk)
createNote(labTitle = "Only the filling of artificial gaps can be checked")
tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both")
}
goodFill1OnOk <- function() {
tsWithNoGapsName <- verifyCharEntry(tcltk::tclvalue(KTSEnv$selTsP0),
noValid = NA)
if (is.na(tsWithNoGapsName)) {
tcltk::tkmessageBox(message = "Choose a time series", icon = "warning")
} else {
assign("tsWithNoGapsName", tsWithNoGapsName, envir = KTSEnv)
showPANgoodFill2()
}
}
showPANgoodFill2 <- function() {
createSubPanR4C1()
createTITLE(labTitle = "CHECK FILLING")
createTsRb(labTitle = "Time series with artificial gaps")
createOK(labTitle = "NEXT", action = goodFill2OnOk)
tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both")
}
goodFill2OnOk <- function() {
tsWithGapsName <- verifyCharEntry(tcltk::tclvalue(KTSEnv$selTsP),
noValid = NA)
if (is.na(tsWithGapsName)) {
tcltk::tkmessageBox(message = "Choose a time series", icon = "warning")
} else {
assign("tsWithGapsName", tsWithGapsName, envir = KTSEnv)
showPANgoodFill3()
}
}
showPANgoodFill3 <- function() {
createSubPanR4C1()
createTITLE(labTitle = "CHECK FILLING")
createTsRb(labTitle = "Time series after the filling",
variableName = "selTsP1")
createOK(labTitle = "RUN", action = goodFill3OnOk)
tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both")
}
goodFill3OnOk <- function() {
tsFilledName <- verifyCharEntry(tcltk::tclvalue(KTSEnv$selTsP1),
noValid = NA)
if (is.na(tsFilledName)) {
tcltk::tkmessageBox(message = "Choose a time series", icon = "warning")
} else {
tsFilled <- get(tsFilledName, envir = KTSEnv)
tsWithGaps <- get(KTSEnv$tsWithGapsName, envir = KTSEnv)
tsWithNoGaps <- get(KTSEnv$tsWithNoGapsName, envir = KTSEnv)
initialDates <- as.numeric(c(tsWithNoGaps$time[1], tsWithGaps$time[1],
tsFilled$time[1]))
samPer <- c(diff(as.numeric(tsWithNoGaps$time[1:2])),
diff(as.numeric(tsWithGaps$time[1:2])),
diff(as.numeric(tsFilled$time[1:2])))
tsWNoGNasInd <- which(is.na(tsWithNoGaps$value))
tsWGNasInd <- which(is.na(tsWithGaps$value))
tsFilledNasInd <- which(is.na(tsFilled$value))
if (any(initialDates != initialDates[1])) {
tcltk::tkmessageBox(message = paste("The selected time series have",
"different initial dates"),
icon = "warning")
showPANgoodFill1()
} else if (any(samPer != samPer[1])) {
tcltk::tkmessageBox(message = paste("The selected time series have",
"different sampling periods"),
icon = "warning")
showPANgoodFill1()
} else if (is.null(tsWGNasInd)) {
tcltk::tkmessageBox(message = paste(tsWithGapsName, "has no gaps.",
"It should have artifical gaps"),
icon = "warning")
showPANgoodFill1()
} else if (length(intersect(tsWGNasInd,
tsFilledNasInd)) == length(tsWGNasInd)) {
tcltk::tkmessageBox(message = paste(tsWithGapsName, "and",
tsFilledName,
"have the same gaps."),
icon = "warning")
} else {
artificialGaps <- setdiff(tsWGNasInd, tsWNoGNasInd)
notFilledArtGaps <- intersect(artificialGaps, tsFilledNasInd)
filledArtGaps <- setdiff(artificialGaps, notFilledArtGaps)
observed <- tsWithNoGaps$value[filledArtGaps]
predicted <- tsFilled$value[filledArtGaps]
if (length(observed) != length(predicted)) {
tcltk::tkmessageBox(message = paste("The observed and predicted",
"values have different lengths"),
icon = "warning")
} else if (any(is.infinite(observed)) | any(is.nan(observed))) {
tcltk::tkmessageBox(message = paste("Some observed values are",
"Inf,-Inf or NaN"),
icon = "warning")
} else if (any(is.infinite(predicted)) | any(is.nan(predicted))) {
tcltk::tkmessageBox(message = paste("Some predicted values are",
"Inf,-Inf or NaN"),
icon = "warning")
} else {
completeCasesInd <- which(stats::complete.cases(observed, predicted))
if (length(completeCasesInd) < 4) {
tcltk::tkmessageBox(message = paste("There are less than four",
"complete cases"),
icon = "warning")
} else {
observed <- observed[completeCasesInd]
predicted <- predicted[completeCasesInd]
lmObsPred <- myLinModel(observed, predicted)
if (class(lmObsPred) == "character") {
tcltk::tkmessageBox(message = lmObsPred, icon = "warning")
} else {
filledGapsTable <- groupDates(filledArtGaps, tsFilled)
txt1 <- "CHECK FILLING"
txt21 <- paste("Time series with no artificial gaps:",
KTSEnv$tsWithNoGapsName)
txt22 <- paste("Time series with artificial gaps:",
KTSEnv$tsWithGapsName)
txt23 <- paste("Filled time series:", tsFilledName)
mvdmd <- as.data.frame(lmObsPred)
txt4 <- utils::capture.output(print.data.frame(mvdmd))
txt5 <- "Gaps filled:"
txt6 <- utils::capture.output(print.data.frame(filledGapsTable))
txt0 <- c(txt1, txt21, txt22, txt23)
tcltk::tkinsert(KTSEnv$txtWidget, "end",
paste(txt0, collapse = "\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end",
paste(txt4, collapse = "\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end",
paste(txt5, collapse = "\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end",
paste(txt6, collapse = "\n"))
tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n\n"))
}
}
}
}
cleanEnvir()
refreshDataSetsList(outp = FALSE)
showPANgoodFill1()
}
}
cleanEnvir()
refreshDataSetsList(outp = FALSE)
checkIfAnyTs(action = "showPANgoodFill1",
envirName = environment(showPANgoodFill1))
} |
test_that("can locally override edition", {
local_edition(3)
expect_equal(edition_get(), 3)
local_edition(2)
expect_equal(edition_get(), 2)
})
test_that("deprecation only fired for newer edition", {
local_edition(2)
expect_warning(edition_deprecate(3, "old stuff"), NA)
local_edition(3)
expect_snapshot(edition_deprecate(3, "old stuff"))
})
test_that("required only fired for older edition", {
withr::local_options(testthat.edition_ignore = FALSE)
local_edition(2)
expect_error(edition_require(3, "new stuff"))
withr::local_options(testthat.edition_ignore = FALSE)
local_edition(3)
expect_error(edition_require(3, "new stuff"), NA)
})
test_that("edition for testthat is 3", {
expect_equal(find_edition(package = "testthat"), 3)
})
test_that("edition for non-package dir is 2", {
expect_equal(find_edition(tempdir()), 2)
})
test_that("can set the edition via an environment variable", {
local_edition(zap())
withr::local_envvar(TESTTHAT_EDITION = 2)
expect_equal(edition_get(), 2)
withr::local_envvar(TESTTHAT_EDITION = 3)
expect_equal(edition_get(), 3)
}) |
ResultParser <- R6::R6Class(classname = "ResultParser",
public = list(
destDir = NULL,
requestData = NULL,
analysisReport = NULL,
arResults = NULL,
carResults = NULL,
aarResults = NULL,
aarStatistics = NULL,
caarResults = NULL,
groups = NULL,
initialize = function() {
},
parseRequestFile = function(path = "01_RequestFile.csv") {
parseReturn <- private$parseFile(path, "requestData", header = F)
if (parseReturn) {
groups <- unique(self$requestData$V5)
}
parseReturn
},
parseReport = function(path = "analysis_report.csv") {
private$parseFile(path, "analysisReport", T)
self$analysisReport <- self$analysisReport[-1, ]
},
parseAR = function(path = "ar_results.csv", analysisType = "AR") {
if (is.null(self$analysisReport)) {
self$parseReport()
}
parseReturn <- private$parseFile(path, "arResults", T)
if (!parseReturn) {
return(NULL)
} else {
abnormalReturns <- data.table::copy(self[["arResults"]])
}
if (nrow(abnormalReturns) == 0) {
message("Analysis performed, but no AR Results. Please look at comments in Analysis report.")
return(NULL)
}
stringr::str_detect(names(abnormalReturns), analysisType) %>%
which() -> id
abnormalReturns %>%
dplyr::select(c(1, id)) %>%
reshape2::melt(id.vars = 1) %>%
dplyr::rename(eventTime = variable, ar = value) -> self$arResults
self$arResults %>%
dplyr::mutate(eventTime = as.numeric(stringr::str_replace_all(as.character(eventTime), "[a-zA-Z()]", ""))) -> self$arResults
stringr::str_detect(names(abnormalReturns), "t-value") %>%
which() -> id
if (length(id)) {
abnormalReturns %>%
dplyr::select(c(1, id)) %>%
reshape2::melt(id.vars = 1) %>%
dplyr::rename(eventTime = variable, tValue = value) -> tValues
tValues %>%
dplyr::mutate(eventTime = stringr::str_trim(stringr::str_replace_all(as.character(eventTime), "t-value", ""))) %>%
dplyr::mutate(eventTime = as.numeric(stringr::str_replace_all(as.character(eventTime), "[()]", ""))) -> tValues
self$arResults %>%
dplyr::left_join(tValues, by = c("Event ID", "eventTime")) -> self$arResults
}
idP <- which(names(self$analysisReport) == "p-value")
names(self$analysisReport)[idP] <- paste0("p-value", 1:length(idP))
id <- which(names(self$analysisReport) %in% c("Event ID", "Firm", "Reference Market", "Estimation Window Length"))
self$analysisReport %>%
dplyr::select(id) -> arReport
self$arResults %>%
dplyr::left_join(arReport, by = "Event ID") -> self$arResults
if (!is.null(self$requestData)) {
requestData <- self$requestData[, c(1, 5)]
names(requestData) <- c("Event ID", "Group")
self$arResults %>%
dplyr::left_join(requestData, by = "Event ID") -> self$arResults
}
},
parseCAR = function(path = "car_results.csv", analysisType = "CAR") {
if (is.null(self$analysisReport))
self$parseReport()
carResults <- data.table::fread(path)
if (nrow(carResults) == 0) {
message("Analysis performed, but no CAR Results. Please look at comments in Analysis report.")
return(NULL)
}
self$analysisReport %>%
dplyr::select(`Event ID`, Firm) %>%
dplyr::right_join(carResults) -> carResults
self$carResults <- carResults
},
parseAAR = function(path = "aar_results.csv", groups = NULL, analysisType = "AAR") {
if (is.null(self$analysisReport))
self$parseReport()
if (!is.null(self$groups))
self$groups <- groups
aarResults <- data.table::fread(path)
if (nrow(aarResults) < 2) {
message("Analysis performed, but no AAR Results. Please look at comments in Analysis report.")
return(NULL)
}
stringr::str_detect(names(aarResults), analysisType) %>%
which() -> id
aarResults %>%
reshape2::melt(id.vars = 1,
value.name = tolower(analysisType)) %>%
dplyr::rename(level = `Grouping Variable/N`,
eventTime = variable) -> aarResults
self$aarResults <- aarResults
aarResults %>%
dplyr::mutate(eventTime = as.numeric(stringr::str_replace_all(as.character(eventTime), "[a-zA-Z()]", ""))) -> aarResults
aarResults$level %>%
stringr::str_detect("Pos:Neg") %>%
which() -> idPos
idN <- idPos - 1
idAAR <- idN - 1
aarFinal <- aarResults[idAAR, ]
aarFinal$aar <- as.numeric(aarFinal$aar)
aarFinal$N <- as.numeric(aarResults[idN, ]$aar)
aarResults[idPos, ]$aar %>%
stringr::str_split(pattern = ":") %>%
purrr::map(.f = function(x) as.numeric(x[[1]])) %>%
unlist() -> aarFinal$Pos
nStat <- idPos[2] - (idPos[1] + 1) - 2
statistics <- c()
if (nStat > 0) {
for (i in 1:nStat) {
idStat <- idPos + i
dfStat <- aarResults[idStat, ]
statistics <- c(statistics, dfStat$level[1])
aarFinal[[paste0("stat", i)]] <- as.numeric(dfStat$aar)
}
names(statistics) <- paste0("stat", 1:nStat)
self$aarStatistics <- statistics
}
self$aarResults <- aarFinal
},
parseCAAR = function(path = "caar_results.csv", groups = NULL, analysisType = "AAR") {
caarResults <- data.table::fread(path)
g_names <- c("Grouping Variable", "CAAR Type", "CAAR Value", "Precision Weighted CAAR Value", "ABHAR", "pos:neg CAR", "Number of CARs considered")
caar_values <- caarResults[, g_names, with=F]
s_names <- setdiff(names(caarResults), g_names)
s_names <- c("Grouping Variable", "CAAR Type", s_names)
caarResults[, s_names, with=F] %>%
data.table::melt(id.vars = c("Grouping Variable", "CAAR Type"),
variable.name = "Test",
value.name = "Statistics") -> caar_statistics
self$caarResults <- list(
caar_values = caar_values,
caar_statistics = caar_statistics
)
},
calcAARCI = function(statistic = "Patell Z",
p = 0.95,
twosided = T,
type = "zStatistic") {
statistic <- rlang::arg_match(statistic, c("Patell Z",
"Generalized Sign Z",
"Csect T",
"StdCSect Z",
"Rank Z",
"Generalized Rank T",
"Adjusted Patell Z",
"Adjusted StdCSect Z",
"Generalized Rank Z",
"Skewness Corrected T"))
type <- match.arg(type, c("tStatistic", "zStatistic"))
if (twosided) {
p <- 0.5 + p / 2
if (type == "zStatistic") {
zStar <- qnorm(p)
} else {
}
}
idStat <- which(self$aarStatistics == statistic)
lower <- NULL
upper <- NULL
if (length(idStat)) {
statCol <- names(self$aarStatistics)[idStat]
statValue <- self$aarResults[[statCol]]
aar <- self$aarResults[["aar"]]
lower <- aar - abs(aar) * zStar / abs(statValue)
upper <- aar + abs(aar) * zStar / abs(statValue)
}
return(list(lower = lower,
upper = upper))
},
cumSum = function(df, var = "aar", timeVar = NULL, cumVar = NULL, fun = cumsum) {
df <- data.table::as.data.table(df)
data.table::setkeyv(df, c(cumVar, timeVar))
setnames(df, var, "car")
df[, car := fun(car), by = cumVar]
df[[var]] <- NULL
setnames(df, "car", var)
df
},
createReport = function(file = "EventStudy.xlsx") {
if (!stringr::str_detect(file, ".xlsx")) {
file <- paste0(file, ".xlsx")
}
wb <- openxlsx::createWorkbook()
hs1 <- openxlsx::createStyle(fgFill = "
border = "Bottom", fontColour = "white")
numStyle <- openxlsx::createStyle(numFmt = "0.00")
centreStyle <- openxlsx::createStyle(halign = "center", valign = "center")
intNumStyle <- openxlsx::createStyle(numFmt = "0")
options("openxlsx.numFmt" = "
openxlsx::addWorksheet(wb, sheetName = "Analysis Report")
openxlsx::writeData(wb, sheet = "Analysis Report", x = self$analysisReport, headerStyle = hs1)
openxlsx::setColWidths(wb, sheet = "Analysis Report", cols = 1:ncol(self$analysisReport), widths = 15)
if (!is.null(self$arResults)) {
self$arResults %>%
dplyr::select(-`Estimation Window Length`) -> dtData
class(dtData$ar) <- "percentage"
names(dtData)[2:4] <- c("Event Time", "AR", "t-Value")
openxlsx::addWorksheet(wb, sheetName = "AR Report")
openxlsx::writeData(wb, sheet = "AR Report", x =dtData, headerStyle = hs1)
openxlsx::setColWidths(wb, sheet = 1, cols = ncol(dtData), widths = 15)
wb <- private$setCenterStyle(wb = wb,
sheet = "AR Report",
rows = 1:(nrow(dtData) + 1),
cols = 3:ncol(dtData))
openxlsx::addStyle(wb, "AR Report",
style = intNumStyle,
rows = 2:(nrow(dtData) + 1),
cols = 2,
stack = T,
gridExpand = TRUE)
}
if (!is.null(self$carResults)) {
dtData <- self$carResults
names(dtData)[4] <- "CAR"
class(dtData$CAR) <- "percentage"
openxlsx::addWorksheet(wb, sheetName = "CAR Report")
openxlsx::writeData(wb, sheet = "CAR Report", x = dtData, headerStyle = hs1)
wb <- private$setCenterStyle(wb = wb,
sheet = "CAR Report",
rows = 1:(nrow(dtData) + 1),
cols = 3:ncol(dtData))
openxlsx::addStyle(wb, "CAR Report",
style = centreStyle,
rows = 1:(nrow(dtData) + 1),
cols = 3:ncol(dtData),
stack = T,
gridExpand = TRUE)
}
if (!is.null(self$aarResults)) {
dtData <- self$aarResults
statNames <- as.character(self$aarStatistics[names(self$aarResults)])
statId <- which(!is.na(statNames))
names(dtData)[statId] <- statNames[statId]
names(dtData)[1:5] <- c("Group", "Event Time", "AAR", "N Firms", "N positive AR")
class(dtData$AAR) <- "percentage"
openxlsx::addWorksheet(wb, sheetName = "AAR Report")
openxlsx::setColWidths(wb, sheet = "AAR Report", cols = 1:ncol(dtData), widths = 15)
openxlsx::writeData(wb, sheet = "AAR Report", x = dtData, headerStyle = hs1)
wb <- private$setCenterStyle(wb = wb,
sheet = "AAR Report",
rows = 1:(nrow(dtData) + 1),
cols = 3:ncol(dtData))
openxlsx::addStyle(wb, "AAR Report",
style = intNumStyle,
rows = 2:(nrow(dtData) + 1),
cols = c(2, 4:5),
stack = T,
gridExpand = TRUE)
}
openxlsx::saveWorkbook(wb, file, overwrite = T)
}
),
private = list(
setCenterStyle = function(wb, sheet, rows, cols) {
centreStyle <- openxlsx::createStyle(halign = "center", valign = "center")
openxlsx::addStyle(wb, sheet,
style = centreStyle,
rows = rows,
cols = cols,
stack = T,
gridExpand = TRUE)
wb
},
parseFile = function(path, dataName, header = F) {
if (file.exists(path) || !httr::http_error(path)) {
self[[dataName]] <- data.table::fread(path, header = header)
TRUE
} else {
message(paste0("File ", path, " not found!"))
FALSE
}
}
)) |
stopifnot(!"lmerTest" %in% .packages())
data("sleepstudy", package="lme4")
f <- function(form, data) lmerTest::lmer(form, data=data)
form <- "Reaction ~ Days + (Days|Subject)"
fm <- f(form, data=sleepstudy)
anova(fm)
summary(fm)
test <- function() {
tmp <- sleepstudy
m <- lmerTest::lmer(Reaction ~ Days + (Days | Subject), data = tmp)
summary(m)
}
test()
test <- function() {
tmp <- sleepstudy
m <- lme4::lmer(Reaction ~ Days + (Days | Subject), data = tmp)
if(requireNamespace("lmerTest", quietly = TRUE)) {
summary(lmerTest::as_lmerModLmerTest(m))
}
}
test()
library(lmerTest)
assertError <- function(expr, ...)
if(requireNamespace("tools")) tools::assertError(expr, ...) else invisible()
assertWarning <- function(expr, ...)
if(requireNamespace("tools")) tools::assertWarning(expr, ...) else invisible()
TOL <- 1e-4
lmer_args <- formals(lme4::lmer)
names(lmer_args)
lmerTest_args <- formals(lmerTest::lmer)
seq_args <- seq_along(lmerTest_args)
if(packageVersion("lme4") > '1.1.21') {
stopifnot(
all.equal(names(lmer_args), names(lmerTest_args)),
all.equal(lmer_args, lmerTest_args)
)
} else {
stopifnot(
all.equal(names(lmer_args)[seq_args], names(lmerTest_args[seq_args])),
all.equal(lmer_args[seq_args], lmerTest_args[seq_args])
)
}
myupdate <- function(m, ...) {
update(m, ...)
}
data("sleepstudy", package="lme4")
fm1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
tmp <- sleepstudy
rm(sleepstudy)
fmA <- update(fm1, data = tmp)
fmB <- myupdate(fm1, data = tmp)
fmB@call <- fmA@call
stopifnot(isTRUE(all.equal(fmA, fmB, tolerance=TOL)))
form <- "Informed.liking ~ Product+Information+
(1|Consumer) + (1|Product:Consumer) + (1|Information:Consumer)"
m <- lmer(form, data=ham)
class(m)
class(update(m, ~.- Product))
stopifnot(inherits(update(m, ~.- Product), "lmerModLmerTest"))
data("sleepstudy", package="lme4")
myfit <- function(formula, data) {
lme4::lmer(formula = formula, data = data)
}
fm2 <- myfit(Reaction ~ Days + (Days|Subject), sleepstudy)
m <- assertError(as_lmerModLmerTest(fm2))
stopifnot(
grepl("Unable to extract deviance function from model fit", m[[1]], fixed=TRUE)
)
data("sleepstudy", package="lme4")
fun <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy, devFunOnly = TRUE)
stopifnot(is.function(fun) && names(formals(fun)[1]) == "theta")
fm1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)
fun <- update(fm1, devFunOnly=TRUE)
stopifnot(is.function(fun) && names(formals(fun)[1]) == "theta")
notfun <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy, devFunOnly = FALSE)
stopifnot(inherits(notfun, "lmerModLmerTest"))
notfun <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy, devFun = FALSE)
stopifnot(inherits(notfun, "lmerModLmerTest"))
data("sleepstudy", package="lme4")
m <- lme4::lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
bm <- lmerTest:::as_lmerModLmerTest(m)
stopifnot(
inherits(bm, "lmerModLmerTest"),
!inherits(m, "lmerModLmerTest"),
inherits(bm, "lmerMod"),
all(c("vcov_varpar", "Jac_list", "vcov_beta", "sigma") %in% slotNames(bm))
)
m <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
m1 <- update(m, ~.-Days)
m2 <- lmer(Reaction ~ (Days | Subject), sleepstudy)
stopifnot(
inherits(m, "lmerModLmerTest"),
inherits(m1, "lmerModLmerTest"),
inherits(m2, "lmerModLmerTest"),
all.equal(m1, m2, tolerance=1e-6)
) |
context("FT 1: Fortify pipeline objects")
ft1_check_libs <- function() {
if (requireNamespace("ggplot2", quietly = TRUE)) {
TRUE
} else {
FALSE
}
}
test_that("fortify fmdat", {
if (!ft1_check_libs()) {
skip("Libraries cannot be loaded")
}
data(B500)
fmdat <- reformat_data(B500$good_er_scores, B500$labels)
curve_df <- ggplot2::fortify(fmdat)
expect_true(is.list(curve_df))
})
test_that("fortify cmat", {
if (!ft1_check_libs()) {
skip("Libraries cannot be loaded")
}
data(B500)
cmat <- create_confmats(scores = B500$good_er_scores,
labels = B500$labels)
curve_df <- ggplot2::fortify(cmat)
expect_true(is.list(curve_df))
})
test_that("fortify pevals", {
if (!ft1_check_libs()) {
skip("Libraries cannot be loaded")
}
data(B500)
pevals <- calc_measures(scores = B500$good_er_scores,
labels = B500$labels)
curve_df <- ggplot2::fortify(pevals)
expect_true(is.list(curve_df))
}) |
context("Computer Vision")
vision_url <- Sys.getenv("AZ_TEST_COMPUTERVISION_URL")
vision_key <- Sys.getenv("AZ_TEST_COMPUTERVISION_KEY")
storage <- Sys.getenv("AZ_TEST_STORAGE_ACCT")
if(vision_url == "" || vision_key == "" || storage == "")
skip("Tests skipped: resource details not set")
test_that("Computer Vision endpoint works with URL",
{
endp <- computervision_endpoint(vision_url, key=vision_key)
expect_is(endp, c("computervision_endpoint", "cognitive_endpoint"))
res_doms <- list_computervision_domains(endp)
expect_type(res_doms, "character")
img <- httr::parse_url(storage)
img$path <- "cognitive/bill.jpg"
img <- httr::build_url(img)
res_analyze <- analyze(endp, img)
expect_is(res_analyze, "list")
expect_is(res_analyze$categories, "data.frame")
res_analyze_celeb <- analyze(endp, img, domain="celebrities")
expect_is(res_analyze_celeb$categories, "data.frame")
expect_is(res_analyze_celeb$categories$detail, "data.frame")
res_analyze_tags <- analyze(endp, img, feature_types="tags")
expect_is(res_analyze_tags$tags, "data.frame")
res_analyze_faces <- analyze(endp, img, feature_types="faces")
expect_is(res_analyze_faces$faces, "data.frame")
res_desc <- describe(endp, img)
expect_is(res_desc, "list")
expect_type(res_desc$tags, "character")
expect_is(res_desc$captions, "data.frame")
res_desc_lang <- describe(endp, img, language="es")
expect_is(res_desc_lang, "list")
expect_type(res_desc_lang$tags, "character")
expect_is(res_desc_lang$captions, "data.frame")
res_detobj <- detect_objects(endp, img)
expect_is(res_detobj, "data.frame")
res_area <- area_of_interest(endp, img)
expect_type(res_area, "integer")
res_tag <- tag(endp, img)
expect_is(res_tag, "data.frame")
res_cat <- categorize(endp, img)
expect_is(res_cat, "data.frame")
text_img <- httr::parse_url(storage)
text_img$path <- "cognitive/gettysburg.png"
text_img <- httr::build_url(text_img)
res_text <- read_text(endp, text_img)
expect_is(res_text, "list")
expect_type(res_text[[1]], "character")
res_thumb <- make_thumbnail(endp, img, outfile=NULL, width=50, height=50)
expect_type(res_thumb, "raw")
})
test_that("Computer Vision endpoint works with local file",
{
endp <- computervision_endpoint(vision_url, key=vision_key)
img <- "../../inst/images/bill.jpg"
res_analyze <- analyze(endp, img)
expect_is(res_analyze, "list")
}) |
correct_gamma=function(P_data,rep,n.eta, sample_gamma){
P=list()
for (i in 1:rep){
P[[i]]=P_data[(1+n.eta*(i-1)):(n.eta*i),]
}
correct_sample_G=lapply(1:length(sample_gamma), function(i){t(as.matrix(P[[i]]))%*%sample_gamma[[i]]})
correct_gamma=do.call(rbind,lapply(1:length(correct_sample_G), function(i) {cbind(i,correct_sample_G[[i]])}))
colnames(correct_gamma)[1]=c("replication")
write.table(correct_gamma, sep=",", file="correct_gamma.csv", row.names=FALSE)
} |
testthat::test_that("model_summary: lm model", {
model <- lm_model(
data = iris[1:4],
response_variable = "Sepal.Length",
predictor_variable = c(Sepal.Width, Petal.Width),
two_way_interaction_factor = c(Sepal.Width, Petal.Width),
quite = T
)
summary <- model_summary(model,
return_result = T,
assumption_plot = T,
quite = T
)
expect_false(is.null(summary$model_summary))
expect_false(is.null(summary$model_performance_df))
expect_false(is.null(summary$assumption_plot))
})
testthat::test_that("model_summary: glm model", {
expect_warning(model <- glm_model(
response_variable = incidence,
predictor_variable = period,
family = "poisson",
data = lme4::cbpp,
quite = TRUE,
))
summary <- model_summary(model,
return_result = T,
assumption_plot = T,
quite = T
)
expect_false(is.null(summary$model_summary))
expect_false(is.null(summary$model_performance_df))
expect_false(is.null(summary$assumption_plot))
})
testthat::test_that(desc = "model_summary: nlme model", {
model <- lme_model(
data = popular,
response_variable = popular,
random_effect_factors = sex,
non_random_effect_factors = c(extrav, sex, texp),
id = class,
opt_control = "optim",
use_package = "nlme",
quite = T
)
summary <- model_summary(model,
return_result = T,
assumption_plot = T,
quite = T
)
expect_false(is.null(summary$model_summary))
expect_false(is.null(summary$model_performance_df))
expect_false(is.null(summary$assumption_plot))
})
testthat::test_that(desc = "model_summary: lmerTest model", {
model <- lme_model(
data = popular,
response_variable = popular,
random_effect_factors = c(extrav),
non_random_effect_factors = c(texp),
id = class,
use_package = "lmerTest",
quite = T
)
summary <- model_summary(model,
return_result = T,
assumption_plot = T,
quite = T
)
expect_false(is.null(summary$model_summary))
expect_false(is.null(summary$model_performance_df))
expect_false(is.null(summary$assumption_plot))
})
testthat::test_that(desc = "model_summary: lme4 model", {
model <- lme_model(
data = popular,
response_variable = popular,
random_effect_factors = c(extrav),
non_random_effect_factors = c(texp),
id = class,
use_package = "lme4",
quite = T
)
summary <- model_summary(model,
return_result = T,
assumption_plot = T,
quite = T
)
expect_false(is.null(summary$model_summary))
expect_false(is.null(summary$model_performance_df))
expect_false(is.null(summary$assumption_plot))
})
testthat::test_that(desc = "model_summary: glme model", {
testthat::skip_on_cran()
model <- expect_warning(glme_model(
response_variable = incidence,
random_effect_factors = period,
family = "poisson",
id = herd,
data = lme4::cbpp,
quite = T
))
summary <- model_summary(model,
return_result = T,
assumption_plot = T,
quite = T
)
expect_false(is.null(summary$model_summary))
expect_false(is.null(summary$model_performance_df))
expect_false(is.null(summary$assumption_plot))
}) |
plot.pcovar <-
function(x,...,reversals=c(0,0,0,0,0,0)) {
o.pcovar<- x
rev<- (-2*reversals)+1
y<- o.pcovar$y
par(mfrow=c(2,3),pty="s",mar=c(0.0,2.3,2.3,0.3),omi=c(1,0,0,0),mgp=c(1.30,0.5,0),lwd=0.5)
colors<- c("darkred","darkolivegreen4","blue","gold","darkorange")
coo<- colors[o.pcovar$grel]
co<- "black"
plot(c(o.pcovar$euclidpca[,1],o.pcovar$euclidpco[,1]),c(o.pcovar$euclidpca[,2]*rev[1],o.pcovar$euclidpco[,2]*rev[1]),xlab="PCO axis 1",ylab="PCO axis 2",asp=1,type="n",cex.axis=0.8,cex.lab=0.8,tcl=-0.3)
points(o.pcovar$euclidpca[,1],o.pcovar$euclidpca[,2]*rev[1],pch=16,cex=1.0,col=coo)
points(o.pcovar$euclidpco[,1],o.pcovar$euclidpco[,2]*rev[1],pch=16,cex=0.2,col=co)
abline(h=0,v=0,lwd=0.6,col="gray")
title(substitute(paste("PCOA, Euclidean, ",italic("x'=x")^y,sep=""),list(y=y)),cex.main=1.0)
plot(c(o.pcovar$manhpca[,1],o.pcovar$manhpco[,1]),c(o.pcovar$manhpca[,2]*rev[2],o.pcovar$manhpco[,2]*rev[2]),xlab="PCO axis 1",ylab="PCO axis 2",asp=1,type="n",cex.axis=0.8,cex.lab=0.8,tcl=-0.3)
points(o.pcovar$manhpca[,1],o.pcovar$manhpca[,2]*rev[2],pch=16,cex=1.0,col=coo)
points(o.pcovar$manhpco[,1],o.pcovar$manhpco[,2]*rev[2],pch=16,cex=0.2,col=co)
abline(h=0,v=0,lwd=0.6,col="gray")
title(substitute(paste("PCOA, Manhattan, ",italic("x'=x")^y,sep=""),list(y=y)),cex.main=1.0)
plot(c(o.pcovar$cordpca[,1],o.pcovar$cordpco[,1]),c(o.pcovar$cordpca[,2]*rev[3],o.pcovar$cordpco[,2]*rev[3]),xlab="PCO axis 1",ylab="PCO axis 2",asp=1,type="n",cex.axis=0.8,cex.lab=0.8,tcl=-0.3)
points(o.pcovar$cordpca[,1],o.pcovar$cordpca[,2]*rev[3],pch=16,cex=1.0,col=coo)
points(o.pcovar$cordpco[,1],o.pcovar$cordpco[,2]*rev[3],pch=16,cex=0.2,col=co)
abline(h=0,v=0,lwd=0.6,col="gray")
title(substitute(paste("PCOA, Chord distance, ",italic("x'=x")^y,sep=""),list(y=y)),cex.main=1.0)
plot(c(o.pcovar$canpca[,1],o.pcovar$canpco[,1]),c(o.pcovar$canpca[,2]*rev[4],o.pcovar$canpco[,2]*rev[4]),xlab="PCO axis 1",ylab="PCO axis 2",asp=1,type="n",cex.axis=0.8,cex.lab=0.8,tcl=-0.3)
points(o.pcovar$canpca[,1],o.pcovar$canpca[,2]*rev[4],pch=16,cex=1.0,col=coo)
points(o.pcovar$canpco[,1],o.pcovar$canpco[,2]*rev[4],pch=16,cex=0.2,col=co)
abline(h=0,v=0,lwd=0.6,col="gray")
title(substitute(paste("PCOA, Canberra, ",italic("x'=x")^y,sep=""),list(y=y)),cex.main=1.0)
plot(c(o.pcovar$bpca[,1],o.pcovar$bpco[,1]),c(o.pcovar$bpca[,2]*rev[5],o.pcovar$bpco[,2]*rev[5]),xlab="PCO axis 1",ylab="PCO axis 2",asp=1,type="n",cex.axis=0.8,cex.lab=0.8,tcl=-0.3)
points(o.pcovar$bpca[,1],o.pcovar$bpca[,2]*rev[5],pch=16,cex=1.0,col=coo)
points(o.pcovar$bpco[,1],o.pcovar$bpco[,2]*rev[5],pch=16,cex=0.2,col=co)
abline(h=0,v=0,lwd=0.6,col="gray")
title(substitute(paste("PCOA, Bray-Curtis, ",italic("x'=x")^y,sep=""),list(y=y)),cex.main=1.0)
plot(c(o.pcovar$corpca[,1],o.pcovar$corpco[,1]),c(o.pcovar$corpca[,2]*rev[6],o.pcovar$corpco[,2]*rev[6]),xlab="PCO axis 1",ylab="PCO axis 2",asp=1,type="n",cex.axis=0.8,cex.lab=0.8,tcl=-0.3)
points(o.pcovar$corpca[,1],o.pcovar$corpca[,2]*rev[6],pch=16,cex=1.0,col=coo)
points(o.pcovar$corpco[,1],o.pcovar$corpco[,2]*rev[6],pch=16,cex=0.2,col=co)
abline(h=0,v=0,lwd=0.6,col="gray")
title(substitute(paste("PCOA, (1-Correlation)/2, ",italic("x'=x")^y,sep=""),list(y=y)),cex.main=1.0)
} |
eknives <- stats::ts(c(19, 15, 39, 102, 90, 29, 90, 46, 30, 66, 80, 89,
82, 17, 26, 29),f=12,s=1991) |
bunch <- function(earnings, zstar, t1, t2, Tax = 0,
cf_start = NA, cf_end = NA,
exclude_before = NA, exclude_after = NA, force_after = FALSE,
binw = 10, poly_size = 7,
convergence = 0.01, max_iter = 100,
correct = TRUE, select = TRUE, draw = TRUE, nboots = 0,
seed = NA, progress = FALSE,
title = "Bunching Visualization", varname = "Earnings") {
if (!is.numeric(earnings)) {
stop("Earning ector must be numeric")
}
if (Tax < 0) {
stop("This function does not analysze positive notches")
}
if (exclude_before > cf_start | exclude_after > cf_end) {
stop("cf_start and cf_end must be within the excluded range")
}
if (exclude_before == cf_start & exclude_after == cf_end) {
stop("Excluded range must be a strict subset of analysis area")
} else if ( (cf_start - exclude_before) +
(cf_end - exclude_after) <= poly_size + 1) {
stop("Too few bins outside excluded area for polynomial size.")
}
if (!is.na(cf_start) & cf_start <= 0 |
!is.na(cf_end) & cf_end <= 0 ) {
stop("cf_start and cf_end must be positive integers")
}
if (!is.na(exclude_before) & exclude_before < 0 |
!is.na(exclude_after) & exclude_after < 0 ) {
stop("exclude_before and exclude_after must be non-negative integers")
}
if (binw <= 0) {
stop("Bin width needs to be positive")
}
if (!poly_size%%(floor(poly_size)) == 0 & poly_size > 0) {
stop("poly_size must be a positive integer")
}
if (convergence <= 0) {
stop("Convergence threshold must be positive")
}
if (convergence > 0.1) {
warning(paste0("Convergence threshold is low: ", convergence*100,"%"))
}
if (max_iter <= 0) {
stop("max_iter has to be positive")
} else if (!max_iter%%(floor(max_iter)) == 0) {
max_iter <- floor(max_iter)
warning(paste0("max_iter was rounded down to ", max_iter))
}
if (max_iter < 50) {
warning("max_iter is set below recommended level of 50")
}
if (nboots < 0 ) {
stop("nboots cannot be negative")
}
if ( nboots > 0 & !nboots%%(floor(nboots)) == 0 ) {
nboots <- floor(nboots)
warning(paste0("nboots was rounded down to ", nboots))
}
if (nboots > 0 & nboots < 50) {
warning("Such few bootstraps?")
}
if (!is.logical(progress)) {
warning("Wrong input for progress bar option, not showing it")
progress <- FALSE
}
population <- length(earnings)
if (population < 1000) {
warning("Earning vector smaller than 1000. Not sure you want to run an
bunching analysis on this sample size")
}
if (Tax == 0) {
result1 <- kink_estimator(earnings, zstar, t1, t2, cf_start, cf_end,
exclude_before, exclude_after, binw, poly_size,
convergence, max_iter, correct, select, draw,
title, varname)
if (nboots > 0) {
boot_e <- rep(NA, nboots)
boot_Bn <- rep(NA, nboots)
boot_b <- rep(NA, nboots)
if (!is.na(seed)) {
set.seed(seed)
}
if (progress == TRUE) {
pb <- utils::txtProgressBar(min = 1, max = nboots, initial = 1, char = "=",
width = 80, style = 3)
}
for (i in 1:nboots) {
temp_pop <- sample(earnings,population,replace=TRUE)
temp_result <- kink_estimator(temp_pop, zstar, t1, t2, cf_start, cf_end,
exclude_before, exclude_after, binw, poly_size,
convergence, max_iter, correct, select,
draw=FALSE, title, varname)
boot_e[i] <- temp_result$e
boot_Bn[i] <- temp_result$Bn
boot_b[i] <- temp_result$b
if (progress == TRUE) {
utils::setTxtProgressBar(pb, value = i)
}
}
if (progress == TRUE) {
close(pb)
}
results <- list("e" = result1$e,
"Bn" = result1$Bn,
"b" = result1$b,
"data" = result1$data,
"booted_e" = boot_e,
"booted_Bn" = boot_Bn,
"booted_b" = boot_b )
return(results)
} else {
return(result1)
}
}
if (Tax > 0) {
result1 <- notch_estimator(earnings, zstar, t1, t2, Tax,
cf_start, cf_end,
exclude_before, exclude_after, force_after,
binw, poly_size,
convergence, max_iter, select, draw,
title, varname)
if (nboots > 0) {
boot_e <- rep(NA, nboots)
boot_Bn <- rep(NA, nboots)
boot_dz <- rep(NA, nboots)
if (!is.na(seed)) {
set.seed(seed)
}
if (progress == TRUE) {
pb <- utils::txtProgressBar(min = 1, max = nboots, initial = 1, char = "=",
width = 80, style = 3)
}
for (i in 1:nboots) {
temp_pop <- sample(earnings,population,replace = TRUE)
temp_result <- notch_estimator(temp_pop, zstar, t1, t2, Tax,
cf_start, cf_end,
exclude_before, exclude_after, force_after,
binw,
poly_size, convergence, max_iter, select,
draw = FALSE, title, varname)
boot_e[i] <- temp_result$e
boot_Bn[i] <- temp_result$Bn
boot_dz[i] <- temp_result$notch_size
if (progress == TRUE) {
utils::setTxtProgressBar(pb, value = i)
}
}
if (progress == TRUE) {
close(pb)
}
results <- list("e" = result1$e,
"Bn" = result1$Bn,
"notch_size" = result1$notch_size,
"data" = result1$data,
"booted_e" = boot_e,
"booted_Bn" = boot_Bn,
"booted_notch_size" = boot_dz )
return(results)
} else {
return(result1)
}
}
} |
"prrace08" |
context("num.edges")
test_that("num.edges works on edgeLists", {
expect_equal(num.edges(generate_empty_edgeList()), 0)
edgeL <- generate_fixed_edgeList()
expect_equal(num.edges(edgeL), 4)
})
test_that("num.edges works on sparsebnFit", {
cf <- generate_empty_sparsebnFit()
expect_equal(num.edges(cf), 0)
cf <- generate_fixed_sparsebnFit()
expect_equal(num.edges(cf), 4)
})
test_that("num.edges works on sparsebnPath", {
cp <- generate_empty_sparsebnPath()
expect_equal(num.edges(cp), rep(0, length(cp)))
cp <- generate_fixed_sparsebnPath()
expect_equal(num.edges(cp), rep(4, length(cp)))
}) |
aggregate.portfolio <- function(x, by = names(x$nodes), FUN = sum,
classification = TRUE, prefix = NULL, ...)
{
level.names <- names(x$nodes)
nlevels <- length(level.names)
years <- level.names[nlevels]
by <- match.arg(by, level.names, several.ok = TRUE)
fun <- function(x, ...) FUN(unlist(x), ...)
if (identical(by, level.names))
return(cbind(if (classification) x$classification,
array(sapply(x$data, FUN, ...), dim(x$data),
dimnames = list(NULL, paste(prefix, colnames(x$data), sep = "")))))
if (identical(by, years))
{
res <- apply(x$data, 2, fun, ...)
names(res) <- paste(prefix, colnames(x$data), sep = "")
return(res)
}
rows <- setdiff(by, years)
s <- x$classification[, rows, drop = FALSE]
f <- apply(s, 1, paste, collapse = "")
f <- factor(f, levels = unique(f))
s <- s[match(levels(f), f), , drop = FALSE]
xx <- split(x$data, f)
if (years %in% by)
{
xx <- lapply(xx, matrix, ncol = ncol(x$data))
res <- t(sapply(xx, function(x, ...) apply(x, 2, fun, ...), ...))
cols <- colnames(x$data)
}
else
{
res <- sapply(xx, fun, ...)
cols <- deparse(substitute(FUN))
}
structure(cbind(if (classification) s, res),
dimnames = list(NULL, c(if (classification) rows, paste(prefix, cols, sep = ""))))
}
frequency.portfolio <- function(x, by = names(x$nodes),
classification = TRUE, prefix = NULL, ...)
{
chkDots(...)
freq <- function(x) if (identical(x, NA)) NA else length(x[!is.na(x)])
aggregate(x, by, freq, classification, prefix)
}
severity.portfolio <- function(x, by = head(names(x$node), -1),
splitcol = NULL, classification = TRUE,
prefix = NULL, ...)
{
chkDots(...)
level.names <- names(x$nodes)
ci <- seq_len(ncol(x$data))
by <- match.arg(by, level.names, several.ok = TRUE)
if (identical(by, level.names))
{
warning("nothing to do")
return(x)
}
if (is.character(splitcol))
splitcol <- pmatch(splitcol, colnames(x$data), duplicates.ok = TRUE)
if (is.numeric(splitcol) || is.null(splitcol))
splitcol <- ci %in% splitcol
if (tail(level.names, 1L) %in% by)
{
if (length(by) > 1L)
stop("invalid 'by' specification")
res <- unroll(x$data, bycol = TRUE, drop = FALSE)
colnames(res) <- paste(prefix, colnames(res), sep = "")
return(list(main = res[, !splitcol],
split = if (all(!splitcol)) NULL else res[, splitcol]))
}
fun <- function(x) unlist(x[!is.na(x)])
s <- x$classification[, by, drop = FALSE]
f <- apply(s, 1, paste, collapse = "")
f <- factor(f, levels = unique(f))
s <- s[match(levels(f), f), , drop = FALSE]
x.split <- x$data[, splitcol]
if (is.null(prefix))
prefix <- "claim."
if (all(splitcol))
res.main <- NULL
else
{
x <- cbind(lapply(split(x$data[, !splitcol], f), fun))
res.main <- unroll(x, bycol = FALSE, drop = FALSE)
res.main <-
if (0L < (nc <- ncol(res.main)))
{
dimnames(res.main) <-
list(NULL, paste(prefix, seq_len(nc), sep = ""))
cbind(if (classification) s, res.main)
}
else
NULL
}
if (all(!splitcol))
res.split <- NULL
else
{
x <- cbind(lapply(split(x.split, f), fun))
res.split <- unroll(x, bycol = FALSE, drop = FALSE)
res.split <-
if (0L < (nc <- ncol(res.split)))
{
dimnames(res.split) <-
list(NULL, paste(prefix, seq_len(nc), sep = ""))
cbind(if (classification) s, res.split)
}
else
NULL
}
list(main = res.main, split = res.split)
}
weights.portfolio <- function(object, classification = TRUE, prefix = NULL, ...)
{
chkDots(...)
if (is.null(object$weights))
NULL
else
{
w <- object$weights
colnames(w) <- paste(prefix, colnames(w), sep = "")
cbind(if (classification) object$classification, w)
}
} |
expected <- c(8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14,
8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8,
10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10,
12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12,
14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14,
8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8,
10, 12, 14, 8, 10, 12, 14)
test(id=1052, code={
argv <- structure(list(x = structure(list(distance = c(26, 25, 29, 31,
21.5, 22.5, 23, 26.5, 23, 22.5, 24, 27.5, 25.5, 27.5, 26.5, 27,
20, 23.5, 22.5, 26, 24.5, 25.5, 27, 28.5, 22, 22, 24.5, 26.5,
24, 21.5, 24.5, 25.5, 23, 20.5, 31, 26, 27.5, 28, 31, 31.5, 23,
23, 23.5, 25, 21.5, 23.5, 24, 28, 17, 24.5, 26, 29.5, 22.5, 25.5,
25.5, 26, 23, 24.5, 26, 30, 22, 21.5, 23.5, 25, 21, 20, 21.5,
23, 21, 21.5, 24, 25.5, 20.5, 24, 24.5, 26, 23.5, 24.5, 25, 26.5,
21.5, 23, 22.5, 23.5, 20, 21, 21, 22.5, 21.5, 22.5, 23, 25, 23,
23, 23.5, 24, 20, 21, 22, 21.5, 16.5, 19, 19, 19.5, 24.5, 25,
28, 28), age = c(8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14,
8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8,
10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10,
12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12,
14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14,
8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14, 8,
10, 12, 14, 8, 10, 12, 14, 8, 10, 12, 14), Subject = structure(c(15L,
15L, 15L, 15L, 3L, 3L, 3L, 3L, 7L, 7L, 7L, 7L, 14L, 14L, 14L,
14L, 2L, 2L, 2L, 2L, 13L, 13L, 13L, 13L, 5L, 5L, 5L, 5L, 6L,
6L, 6L, 6L, 11L, 11L, 11L, 11L, 16L, 16L, 16L, 16L, 4L, 4L, 4L,
4L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 12L,
12L, 12L, 12L, 1L, 1L, 1L, 1L, 20L, 20L, 20L, 20L, 23L, 23L,
23L, 23L, 25L, 25L, 25L, 25L, 26L, 26L, 26L, 26L, 21L, 21L, 21L,
21L, 19L, 19L, 19L, 19L, 22L, 22L, 22L, 22L, 24L, 24L, 24L, 24L,
18L, 18L, 18L, 18L, 17L, 17L, 17L, 17L, 27L, 27L, 27L, 27L), .Label = c("M16",
"M05", "M02", "M11", "M07", "M08", "M03", "M12", "M13", "M14",
"M09", "M15", "M06", "M04", "M01", "M10", "F10", "F09", "F06",
"F01", "F05", "F07", "F02", "F08", "F03", "F04", "F11"), class = c("ordered",
"factor")), Sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), .Label = c("Male", "Female"), class = "factor")), .Names = c("distance",
"age", "Subject", "Sex"), row.names = c("1", "2", "3", "4", "5",
"6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16",
"17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27",
"28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38",
"39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49",
"50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60",
"61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71",
"72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82",
"83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93",
"94", "95", "96", "97", "98", "99", "100", "101", "102", "103",
"104", "105", "106", "107", "108"), outer = ~Sex, class = c("nfnGroupedData",
"nfGroupedData", "groupedData", "data.frame"), formula = distance ~
age | Subject, labels = structure(list(x = "Age", y = "Distance from pituitary to pterygomaxillary fissure"), .Names = c("x",
"y")), units = structure(list(x = "(yr)", y = "(mm)"), .Names = c("x",
"y")), FUN = function (x)
max(x, na.rm = TRUE), order.groups = TRUE), name = "age"), .Names = c("x",
"name"))
do.call('$.data.frame', argv);
}, o = expected); |
coverageprob <- function(xi, obswin = NULL){
if (is.im(xi)){
stopifnot(is.null(obswin))
coverprobest <- sum(xi) / sum(is.finite(xi$v))
return(coverprobest)
}
stopifnot(is.owin(xi))
stopifnot(is.owin(obswin))
xinw <- intersect.owin(xi, obswin)
xiinw_area <- area.owin(xinw)
w_area <- area.owin(obswin)
coverprobest <- xiinw_area / w_area
return(coverprobest)
}
coveragefrac <- coverageprob
cp <- coverageprob |
if(getRversion() >= "2.15.1") utils::globalVariables(c("x", "value", "n", "model", "lambda",
"upper", "lower", "lowest_BIC", "occs"))
NULL |
library(PortfolioAnalytics)
data(edhec)
R <- edhec[, 1:8]
funds <- colnames(R)
init.portf <- portfolio.spec(assets=funds)
init.portf <- add.constraint(portfolio=init.portf, type="leverage",
min_sum=0.99, max_sum=1.01)
init.portf <- add.constraint(portfolio=init.portf, type="long_only")
rbES.portf <- add.objective(portfolio=init.portf, type="return", name="mean")
rbES.portf <- add.objective(portfolio=rbES.portf, type="risk_budget", name="ES",
max_prisk=0.4, arguments=list(p=0.92))
rbES.DE <- optimize.portfolio(R=R, portfolio=rbES.portf,
optimize_method="DEoptim",
search_size=2000, trace=TRUE)
rbES.DE
plot(rbES.DE, xlim=c(0, 0.08), ylim=c(0, 0.01))
chart.RiskBudget(rbES.DE, risk.type="pct_contrib")
eqES.portf <- add.objective(portfolio=init.portf, type="return", name="mean")
eqES.portf <- add.objective(portfolio=eqES.portf, type="risk_budget",
name="ES", min_concentration=TRUE,
arguments=list(p=0.9, clean="boudt"),
multiplier=10)
R.clean <- Return.clean(R=R, method="boudt")
eqES.RP <- optimize.portfolio(R=R.clean, portfolio=eqES.portf,
optimize_method="random",
search_size=2000, trace=TRUE)
eqES.RP
plot(eqES.RP)
chart.RiskBudget(eqES.RP, risk.type="pct_contrib")
rbStdDev.portf <- add.objective(portfolio=init.portf, type="return", name="mean")
rbStdDev.portf <- add.objective(portfolio=rbStdDev.portf, type="risk_budget",
name="StdDev", max_prisk=0.25)
rbStdDev.DE <- optimize.portfolio(R=R.clean, portfolio=rbStdDev.portf,
optimize_method="DEoptim",
search_size=2000, trace=TRUE)
rbStdDev.DE
plot(rbStdDev.DE, risk.col="StdDev", xlim=c(0, 0.035), ylim=c(0, 0.01))
chart.RiskBudget(rbStdDev.DE, risk.type="pct_contrib")
rp <- random_portfolios(init.portf, 5000)
SDRB.opt.bt <- optimize.portfolio.rebalancing(R, SDRB.portf,
optimize_method="random",
rp=rp,
trace=TRUE,
rebalance_on="years",
training_period=100,
trailing_periods=60)
SDRB.opt.bt
tmp_summary <- summary(SDRB.opt.bt)
names(tmp_summary)
tmp_summary
extractWeights(tmp_summary)
extractObjectiveMeasures(tmp_summary)
tmp_stats <- extractStats(SDRB.opt.bt)
head(tmp_stats[[1]])
tmp_weights <- extractWeights(SDRB.opt.bt)
tmp_obj <- extractObjectiveMeasures(SDRB.opt.bt)
chart.Weights(SDRB.opt.bt)
chart.RiskBudget(SDRB.opt.bt, match.col="StdDev", risk.type="percent") |
new_xmlreadabs <- function(file){
test1 <- xmlParse(file)
test2 = getNodeSet(test1, "//PubmedArticle")
test2a <- NULL;test2b <- NULL;test2c <- NULL;
for (i in 1:length(test2)){
saveXML(test2[[i]], "temp.txt");
temp <- xmlParse("temp.txt");
tempAA <- getNodeSet(temp,"//AbstractText");
if (length(tempAA) == 0) test2a <- c(test2a,"No Abstract Found") else {tempBB <- xmlValue(tempAA);tempBB <- space_quasher(tempBB);test2a <- c(test2a,tempBB[1])};
tempAA <- getNodeSet(temp,"//ISOAbbreviation");
if (length(tempAA) == 0) test2b <- c(test2b,"No Journal Found") else {tempBB <- xmlValue(tempAA);test2b <- c(test2b,tempBB[1])};
tempAA = getNodeSet(temp, "//PMID")
if (length(tempAA) == 0) test2c <- c(test2c,"No PMID Found") else {tempBB <- xmlValue(tempAA);test2c <- c(test2c,tempBB[1])};
}
check = (length(test2a) == length(test2b)) & (length(test2b) == length(test2c))
if (check) {resultabs = new("Abstracts", Journal = test2b, Abstract = test2a, PMID = as.numeric(test2c)); return(resultabs)} else return("There is some problem in xml file. Please check")} |
addGroupOfUnusedAnimals <- function(savedGroupMembers, candidates, ped,
minAge, harem) {
if (harem) {
candidates <- removePotentialSires(candidates, minAge, ped)
}
n <- length(savedGroupMembers) + 1
savedGroupMembers[[n]] <-
ifelse(isEmpty(setdiff(candidates, unlist(savedGroupMembers))),
c(NA), list(setdiff(candidates, unlist(savedGroupMembers))))[[1]]
savedGroupMembers
} |
make_commonlink_adjmat <- function(adj_mat){
comm_mat <- matrix(NA, nrow(adj_mat), ncol(adj_mat))
for(ii in 1:nrow(adj_mat)){
for(jj in 1:ncol(adj_mat)){
comm_mat[ii, jj] <- sum(adj_mat[ii,] & adj_mat[,jj])
}
}
rownames(comm_mat) <- rownames(adj_mat)
colnames(comm_mat) <- colnames(adj_mat)
return(comm_mat)
}
make_commonlink_graph <- function(graph, directed = FALSE){
adj_mat <- make_adjmatrix_graph(graph, directed = directed)
comm_mat <- make_commonlink_adjmat(adj_mat)
return(comm_mat)
} |
ifef <- function(dv){
dv <- ifelse(is.na(dv) , .Machine$double.eps, dv )
dv <- ifelse(dv == Inf , 8.218407e+20, dv )
dv <- ifelse(dv == -Inf , -8.218407e+20, dv )
dv
}
intB <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
if(discr == FALSE) pdf <- distrHsAT(y, eta, sigma2, nu, margin, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)$pdf2
if(discr == TRUE) pdf <- distrHsDiscr(y, eta, sigma2, 1, 1, 1, margin, naive = TRUE, ym, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)$pdf2
log( 1 + exp( log( pdf ) + rc ) )
}
gradBbit1 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
if(discr == FALSE) dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
if(discr == TRUE) dHs <- distrHsDiscr(y, eta, sigma2, sigma2.st, 1, 1, margin, naive = TRUE, ym, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dereta2 <- dHs$derpdf2.dereta2
comp1 <- 1 + exp(log( pdf2 ) + rc)
comp2 <- pdf2/comp1
dl.dbe <- derpdf2.dereta2/pdf2
comp2*dl.dbe
}
gradBbit2 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
if(discr == FALSE) dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
if(discr == TRUE) dHs <- distrHsDiscr(y, eta, sigma2, sigma2.st, 1, 1, margin, naive = TRUE, ym, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dersigma2.st <- dHs$derpdf2.dersigma2.st
comp1 <- 1 + exp(log( pdf2 ) + rc)
comp2 <- pdf2/comp1
dl.dsigma.st <- derpdf2.dersigma2.st/pdf2
comp2*dl.dsigma.st
}
gradBbit3 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dernu.st <- dHs$derpdf2.dernu.st
comp1 <- 1 + exp(log( pdf2 ) + rc)
comp2 <- pdf2/comp1
dl.dnu.st <- derpdf2.dernu.st/pdf2
comp2*dl.dnu.st
}
hessBbit1 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
if(discr == FALSE) dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
if(discr == TRUE) dHs <- distrHsDiscr(y, eta, sigma2, sigma2.st, 1, 1, margin, naive = TRUE, ym, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dereta2 <- dHs$derpdf2.dereta2
der2pdf2.dereta2 <- dHs$der2pdf2.dereta2
comp1 <- 1 + exp(log(pdf2) + rc)
comp2 <- pdf2/comp1
comp3 <- pdf2/comp1^2
d2l.be.be <- (der2pdf2.dereta2 * pdf2 - (derpdf2.dereta2)^2)/pdf2^2
dl.dbe <- derpdf2.dereta2/pdf2
comp2*d2l.be.be + dl.dbe^2*comp3
}
hessBbit2 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
if(discr == FALSE) dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
if(discr == TRUE) dHs <- distrHsDiscr(y, eta, sigma2, sigma2.st, 1, 1, margin, naive = TRUE, ym, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dersigma2.st <- dHs$derpdf2.dersigma2.st
der2pdf2.dersigma2.st2 <- dHs$der2pdf2.dersigma2.st2
comp1 <- 1 + exp(log(pdf2) + rc)
comp2 <- pdf2/comp1
comp3 <- pdf2/comp1^2
d2l.sigma.sigma <- (der2pdf2.dersigma2.st2 * pdf2 - (derpdf2.dersigma2.st)^2)/pdf2^2
dl.dsigma.st <- derpdf2.dersigma2.st/pdf2
comp2*d2l.sigma.sigma + dl.dsigma.st^2*comp3
}
hessBbit3 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
if(discr == FALSE) dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
if(discr == TRUE) dHs <- distrHsDiscr(y, eta, sigma2, sigma2.st, 1, 1, margin, naive = TRUE, ym, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dereta2 <- dHs$derpdf2.dereta2
derpdf2.dersigma2.st <- dHs$derpdf2.dersigma2.st
der2pdf2.dereta2dersigma2.st <- dHs$der2pdf2.dereta2dersigma2.st
comp1 <- 1 + exp(log(pdf2) + rc)
comp2 <- pdf2/comp1
comp3 <- pdf2/comp1^2
d2l.be.sigma <- (der2pdf2.dereta2dersigma2.st * pdf2 - derpdf2.dereta2 * derpdf2.dersigma2.st)/pdf2^2
dl.dbe <- derpdf2.dereta2/pdf2
dl.dsigma.st <- derpdf2.dersigma2.st/pdf2
comp2*d2l.be.sigma + dl.dbe*dl.dsigma.st*comp3
}
hessBbit4 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dernu.st <- dHs$derpdf2.dernu.st
der2pdf2.dernu.st2 <- dHs$der2pdf2.dernu.st2
comp1 <- 1 + exp(log(pdf2) + rc)
comp2 <- pdf2/comp1
comp3 <- pdf2/comp1^2
d2l.nu.nu <- (der2pdf2.dernu.st2*pdf2-(derpdf2.dernu.st)^2)/pdf2^2
dl.dnu.st <- derpdf2.dernu.st/pdf2
comp2*d2l.nu.nu + dl.dnu.st^2*comp3
}
hessBbit5 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dereta2 <- dHs$derpdf2.dereta2
der2pdf2.dereta2dernu.st <- dHs$der2pdf2.dereta2dernu.st
derpdf2.dernu.st <- dHs$derpdf2.dernu.st
comp1 <- 1 + exp(log(pdf2) + rc)
comp2 <- pdf2/comp1
comp3 <- pdf2/comp1^2
d2l.be.nu <- (der2pdf2.dereta2dernu.st*pdf2 - derpdf2.dereta2*derpdf2.dernu.st)/pdf2^2
dl.dbe <- derpdf2.dereta2/pdf2
dl.dnu.st <- derpdf2.dernu.st/pdf2
comp2*d2l.be.nu + dl.dbe*dl.dnu.st*comp3
}
hessBbit6 <- function(y, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, min.dn, min.pr, max.pr, discr = FALSE, ym = NULL){
dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dersigma2.st <- dHs$derpdf2.dersigma2.st
der2pdf2.dersigma2.stdernu.st <- dHs$der2pdf2.sigma2.st2dernu.st
derpdf2.dernu.st <- dHs$derpdf2.dernu.st
comp1 <- 1 + exp(log(pdf2) + rc)
comp2 <- pdf2/comp1
comp3 <- pdf2/comp1^2
d2l.sigma.nu <- (der2pdf2.dersigma2.stdernu.st*pdf2-(derpdf2.dersigma2.st*derpdf2.dernu.st))/pdf2^2
dl.dsigma.st <- derpdf2.dersigma2.st/pdf2
dl.dnu.st <- derpdf2.dernu.st/pdf2
comp2*d2l.sigma.nu + dl.dsigma.st*dl.dnu.st*comp3
}
int1f <- function(y, eta, sigma2, nu, margin, rc, min.dn, min.pr, max.pr){
pdf <- distrHsAT(y, eta, sigma2, nu, margin, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)$pdf2
log( 1 + exp( log( pdf ) + rc ) )
}
d.bpsi <- function(y, X1, X2, X3, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, j, min.dn, min.pr, max.pr){
dHs <- distrHs(y, eta, sigma2, sigma2.st, nu, nu.st, margin, naive = TRUE, min.dn = min.dn, min.pr = min.pr, max.pr = max.pr)
pdf2 <- dHs$pdf2
derpdf2.dereta2 <- dHs$derpdf2.dereta2
derpdf2.dersigma2.st <- dHs$derpdf2.dersigma2.st
derpdf2.dernu.st <- dHs$derpdf2.dernu.st
comp1 <- 1 + exp(log( pdf2 ) + rc)
comp2 <- pdf2/comp1
dl.dbe <- derpdf2.dereta2/pdf2
dl.dsigma.st <- derpdf2.dersigma2.st/pdf2
dl.dnu.st <- derpdf2.dernu.st/pdf2
if( margin %in% c("DAGUM","SM","TW") ) res <- cbind( comp2*as.numeric(dl.dbe)%*%t(X1), comp2*as.numeric(dl.dsigma.st)%*%t(X2), comp2*as.numeric(dl.dnu.st)%*%t(X3) ) else
res <- cbind( comp2*as.numeric(dl.dbe)%*%t(X1), comp2*as.numeric(dl.dsigma.st)%*%t(X2) )
res[, j]
}
gradF <- function(params, n, VC, margin, lB, uB, rc, min.dn, min.pr, max.pr){
G <- matrix(NA, n, length(params))
for(i in 1:n){
X1 <- VC$X1[i,]
X2 <- VC$X2[i,]
X3 <- VC$X3[i,]
nu <- nu.st <- 1
eta <- X1%*%params[1:VC$X1.d2]
sigma2.st <- X2%*%params[(1+VC$X1.d2):(VC$X1.d2+VC$X2.d2)]
if( margin %in% c("DAGUM","SM","TW") ){
nu.st <- X3%*%params[(1+VC$X1.d2+VC$X2.d2):(VC$X1.d2+VC$X2.d2+VC$X3.d2)]
ss <- enu.tr(nu.st, margin)
nu.st <- ss$vrb.st
nu <- ss$vrb
}
ss <- esp.tr(sigma2.st, margin)
sigma2.st <- ss$vrb.st
sigma2 <- ss$vrb
for(j in 1:length(params)) G[i, j] <- integrate(d.bpsi, lB, uB, X1, X2, X3, eta, sigma2, sigma2.st, nu, nu.st, margin, rc, j, min.dn, min.pr, max.pr)$value
}
colSums(G)
} |
context("factorize")
testthat::test_that("factorize works", {
data(KidsFeet, package="mosaicData")
testcase <- structure(c(2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L,
2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L),
.Label = c("87", "88"),
class = "factor")
expect_equivalent(testcase, factorize(KidsFeet$birthyear))
expect_equivalent(testcase, factorise(KidsFeet$birthyear))
}) |
crossval.getParams <- function(cv, nobj) {
nrep <- 1
if (is.numeric(cv)) {
return(
list(
type = "rand",
nrep = 1,
nseg = if (cv == 1) nobj else cv
)
)
}
type <- cv[[1]]
if (type == "loo") {
return(
list(
type = "rand",
nrep = nrep,
nseg = nobj
)
)
}
nseg <- cv[[2]]
if (type == "ven") {
return(
list(
type = "ven",
nrep = nrep,
nseg = nseg
)
)
}
nrep <- if (length(cv) == 3) cv[[3]] else 1
return(
list(
type = type,
nrep = nrep,
nseg = nseg
)
)
}
crossval <- function(cv = 1, nobj = NULL, resp = NULL) {
if (is.null(nobj)) nobj <- length(resp)
p <- crossval.getParams(cv = cv, nobj = nobj)
if (!(p$type %in% c("rand", "ven", "loo"))) {
stop("Wrong name for cross-validation method.")
}
if (p$nrep < 1 || p$nrep > 100) {
stop("Wrong value for cv repetitions (should be between 1 and 100).")
}
if (p$nseg < 2 || p$nseg > nobj) {
stop("Wrong value for number of segments (should be between 2 and number of objects).")
}
seglen <- ceiling(nobj / p$nseg)
fulllen <- seglen * p$nseg
ind <- array(0, dim = c(p$nseg, seglen, p$nrep))
if (p$type == "rand") {
for (i in seq_len(p$nrep)) {
v <- c(sample(nobj), rep(NA, fulllen - nobj))
ind[, , i] <- matrix(v, nrow = p$nseg, byrow = TRUE)
}
return(ind)
}
if (p$type == "ven") {
v <- c(order(resp), rep(NA, fulllen - nobj))
ind[, , 1] <- matrix(v, nrow = p$nseg, byrow = FALSE)
return(ind)
}
stop("Something went wrong.")
}
crossval.str <- function(cv) {
if (length(cv) == 0) return("none")
if (is.numeric(cv)) {
return(
if (cv == 1) "full (leave one out)"
else sprintf("random with %.0f segments", cv)
)
}
type <- cv[[1]]
if (type == "loo") {
return("full (leave one out)")
}
if (type == "ven") {
return(sprintf("venetian blinds with %.0f segments", cv[[2]]))
}
return(
sprintf("random with %.0f segments%s",
cv[[2]], if (length(cv) == 3) paste(" and", cv[[3]], "repetitions") else "")
)
} |
context("pairwise_dist")
suppressPackageStartupMessages(library(dplyr))
test_that("pairwise_dist computes a distance matrix", {
d <- data.frame(col = rep(c("a", "b", "c"), each = 3),
row = rep(c("d", "e", "f"), 3),
value = c(1, 2, 3, 6, 5, 4, 7, 9, 8))
ret <- d %>%
pairwise_dist(col, row, value)
ret1 <- ret$distance[ret$item1 == "a" & ret$item2 == "b"]
expect_equal(ret1, sqrt(sum((1:3 - 6:4) ^ 2)))
ret2 <- ret$distance[ret$item1 == "b" & ret$item2 == "c"]
expect_equal(ret2, sqrt(sum((6:4 - c(7, 9, 8)) ^ 2)))
expect_equal(sum(ret$item1 == ret$item2), 0)
}) |
updateDatabase=function(){
options(stringsAsFactors = F)
extDB<-"https://raw.githubusercontent.com/jaroberti/metScanR/master/data/metScanR_DB.rda"
extTermsDB <- "https://raw.githubusercontent.com/jaroberti/metScanR/master/data/metScanR_terms.rda"
extLog="https://raw.githubusercontent.com/jaroberti/metScanR/master/data/dbLog.rda"
localDB<-paste0(system.file(package="metScanR"), "/data/metScanR_DB.rda")
localTermsDB<-paste0(system.file(package="metScanR"), "/data/metScanR_terms.rda")
localLog=paste0(system.file(package = "metScanR"), "/data/dbLog.rda")
updateLog<-paste0(system.file(package = "metScanR"), "/data/updateLog.rda")
if(!RCurl::url.exists(extDB)){stop("No internet connection- cannot update database.")}
load(localLog)
localDate=as.Date(dbLog$date[length(dbLog$date)])
if(RCurl::url.exists(extDB)){
if(file.exists(updateLog)){
load(updateLog)
if(updateDateFile$Date==Sys.Date() | updateDateFile$Version==dbLog$verison[nrow(dbLog)]){
message("Database is already up-to-date.")
}
else{
if("package:metScanR" %in% search()){
detach(name = "package:metScanR", unload=T)
}
message("Updating database...")
utils::download.file(extDB, destfile = localDB)
utils::download.file(extTermsDB, destfile = localTermsDB)
utils::download.file(extLog, destfile = localLog)
updateDateFile<-data.frame(Date=updateDate, Version = dbLog$verison[nrow(dbLog)])
save(updateDateFile,file=updateLog)
message(paste0("Database updated!"))
message(paste0("Reloading metScanR with updated database..."))
library(metScanR)
}
}
if(!file.exists(updateLog)){
updateDate=Sys.Date()
if("package:metScanR" %in% search()){
detach(name = "package:metScanR", unload=T)
}
message("Updating database...")
utils::download.file(extDB, destfile = localDB)
utils::download.file(extTermsDB, destfile = localTermsDB)
utils::download.file(extLog, destfile = localLog)
updateDateFile<-data.frame(Date=updateDate, Version = dbLog$verison[nrow(dbLog)])
save(updateDateFile,file=updateLog)
message(paste0("Database updated!"))
message(paste0("Reloading metScanR with updated database...\n"))
library(metScanR)
}
}
} |
setClass(
Class = "S1.match",
contains = "ADEg.S1"
)
setMethod(
f = "initialize",
signature = "S1.match",
definition = function(.Object, data = list(score = NULL, labels = NULL, at = NULL, frame = 0, storeData = TRUE), ...) {
.Object <- callNextMethod(.Object, data = data, ...)
.Object@data$labels <- data$labels
return(.Object)
})
setMethod(
f = "prepare",
signature = "S1.match",
definition = function(object) {
name_obj <- deparse(substitute(object))
oldparamadeg <- adegpar()
on.exit(adegpar(oldparamadeg))
adegtot <- adegpar([email protected])
if(adegtot$p1d$horizontal & is.null([email protected]$plabels$srt))
adegtot$plabels$srt <- 90
else if(!adegtot$p1d$horizontal & is.null([email protected]$plabels$srt))
adegtot$plabels$srt <- 0
adegtot$p1d$rug$tck <- 0
if(adegtot$p1d$horizontal & is.null([email protected]$ylim))
[email protected]$ylim <- c(0, 1)
if(!adegtot$p1d$horizontal & is.null([email protected]$xlim))
[email protected]$xlim <- c(0, 1)
[email protected] <- adegtot
callNextMethod()
assign(name_obj, object, envir = parent.frame())
})
setMethod(
f= "panel",
signature = "S1.match",
definition = function(object, x, y) {
if(object@data$storeData) {
labels <- object@data$labels
at <- object@data$at
} else {
labels <- eval(object@data$labels, envir = sys.frame(object@data$frame))
at <- eval(object@data$at, envir = sys.frame(object@data$frame))
}
lims <- current.panel.limits(unit = "native")
nval <- length(y) %/% 2
score2 <- y[(nval + 1):length(y)]
score1 <- y[1 : nval]
pscore <- [email protected]$p1d
plabels <- [email protected]$plabels
plboxes <- plabels$boxes
porigin <- [email protected]$porigin
if(!is.null(labels)) {
test <- .textsize(labels, plabels)
w <- test$w
h <- test$h
}
lead <- ifelse(pscore$reverse, -1, 1)
if(pscore$horizontal) {
spacelab <- diff(lims$xlim) / (nval + 1)
xlab <- seq(from = lims$xlim[1] + spacelab, by = spacelab, length.out = nval)[rank(score1, ties.method = "first")]
ylab <- rep(at, length.out = nval)
ypoints <- rep([email protected]$rug, length.out = nval)
ypoints2 <- rep(ypoints + lead * 0.05 * abs(diff([email protected]$ylim)), length.out = nval)
if(pscore$rug$draw & pscore$rug$line)
panel.abline(h = ypoints2, col = porigin$col, lwd = porigin$lwd, lty = porigin$lty, alpha = porigin$alpha)
do.call("panel.segments", c(list(x0 = score1, y0 = ypoints, x1 = score2, y1 = ypoints2), [email protected]$plines))
do.call("panel.segments", c(list(x0 = score2, y0 = ypoints2, x1 = xlab, y1 = ylab), [email protected]$plines))
if(!is.null(labels) & any(plabels$cex > 0))
adeg.panel.label(x = xlab , y = ylab + lead * h / 2, labels = labels, plabels = plabels)
if(any([email protected]$ppoints$cex > 0))
panel.points(x = c(score1, score2), y = c(ypoints, ypoints2), pch = [email protected]$ppoints$pch, cex = [email protected]$ppoints$cex, col = [email protected]$ppoints$col, alpha = [email protected]$ppoints$alpha, fill = [email protected]$ppoints$fill)
} else {
spacelab <- diff(lims$ylim) / (nval + 1)
ylab <- seq(from = lims$ylim[1] + spacelab, by = spacelab, length.out = nval)[rank(score1, ties.method = "first")]
xlab <- rep(at, length.out = nval)
xpoints <- rep([email protected]$rug, length.out = nval)
xpoints2 <- rep(xpoints + lead * 0.05 * abs(diff([email protected]$xlim)), length.out = nval)
if(pscore$rug$draw & pscore$rug$line)
panel.abline(v = xpoints2, col = porigin$col, lwd = porigin$lwd, lty = porigin$lty, alpha = porigin$alpha)
do.call("panel.segments", c(list(x0 = xpoints, y0 = score1, x1 = xpoints2, y1 = score2), [email protected]$plines))
do.call("panel.segments", c(list(x0 = xpoints2, y0 = score2, x1 = xlab, y1 = ylab), [email protected]$plines))
if(!is.null(labels) & any(plabels$cex > 0))
adeg.panel.label(x = xlab + lead * w / 2 , y = ylab, labels = labels, plabels = plabels)
if(any([email protected]$ppoints$cex > 0))
panel.points(x = c(xpoints, xpoints2), y = c(score1, score2), pch = [email protected]$ppoints$pch, cex = [email protected]$ppoints$cex, col = [email protected]$ppoints$col, alpha = [email protected]$ppoints$alpha, fill = [email protected]$ppoints$fill)
}
})
s1d.match <- function(score1, score2, labels = 1:NROW(score1), at = 0.5, facets = NULL, plot = TRUE, storeData = TRUE, add = FALSE, pos = -1, ...) {
thecall <- .expand.call(match.call())
score1 <- eval(thecall$score1, envir = sys.frame(sys.nframe() + pos))
score2 <- eval(thecall$score2, envir = sys.frame(sys.nframe() + pos))
if(NROW(score1) != NROW(score2))
stop("score1 and score2 should have the same length")
if(NCOL(score1) != NCOL(score2))
stop("score1 and score2 should have the same number of columns")
if((is.data.frame(score1) & NCOL(score1) == 1) | (is.data.frame(score2) & NCOL(score2) == 1))
stop("Not yet implemented for data.frame with only one column, please convert into vector")
sortparameters <- sortparamADEg(...)
if(!is.null(facets)) {
if(NCOL(score1) == 1)
object <- multi.facets.S1(thecall, sortparameters$adepar, samelimits = sortparameters$g.args$samelimits)
else
stop("Facets are not allowed with multiple scores")
}
else if(NCOL(score1) > 1) {
object <- multi.score.S1(thecall)
}
else {
if(length(sortparameters$rest))
warning(c("Unused parameters: ", paste(unique(names(sortparameters$rest)), " ", sep = "")), call. = FALSE)
if(storeData)
tmp_data <- list(score = c(score1, score2), labels = labels, at = at, frame = sys.nframe() + pos, storeData = storeData)
else
tmp_data <- list(score = call("c", thecall$score1, thecall$score2), labels = thecall$labels, at = thecall$at, frame = sys.nframe() + pos, storeData = storeData)
object <- new(Class = "S1.match", data = tmp_data, adeg.par = sortparameters$adepar, trellis.par = sortparameters$trellis, g.args = sortparameters$g.args, Call = match.call())
prepare(object)
setlatticecall(object)
if(add)
object <- add.ADEg(object)
}
if(!add & plot)
print(object)
invisible(object)
} |
add_rolling_means <- function(data,
dates = Date,
values = Value,
groups = STATION_NUMBER,
station_number,
roll_days = c(3,7,30),
roll_align = "right"){
if (missing(data)) {
data <- NULL
}
if (missing(station_number)) {
station_number <- NULL
}
rolling_days_checks(roll_days, roll_align, multiple = TRUE)
flow_data <- flowdata_import(data = data, station_number = station_number)
orig_cols <- names(flow_data)
flow_data_groups <- dplyr::group_vars(flow_data)
flow_data <- dplyr::ungroup(flow_data)
flow_data <- format_all_cols(data = flow_data,
dates = as.character(substitute(dates)),
values = as.character(substitute(values)),
groups = as.character(substitute(groups)),
rm_other_cols = FALSE)
flow_data_new <- flow_data[0,]
for (stn in unique(flow_data$STATION_NUMBER)) {
flow_data_stn <- dplyr::filter(flow_data, STATION_NUMBER == stn)
flow_data_stn <- flow_data_stn[order(flow_data_stn$Date), ]
dates_list <- c(flow_data_stn$Date)
flow_data_stn <- fill_missing_dates(data = flow_data_stn)
for (x in unique(roll_days)) {
flow_data_stn[, paste0("Q", x, "Day")] <- RcppRoll::roll_mean(flow_data_stn$Value, n = x, fill = NA, align = roll_align)
}
flow_data_stn <- dplyr::filter(flow_data_stn, Date %in% dates_list)
flow_data_new <- dplyr::bind_rows(flow_data_new, flow_data_stn)
}
flow_data <- flow_data_new
names(flow_data)[names(flow_data) == "STATION_NUMBER"] <- as.character(substitute(groups))
names(flow_data)[names(flow_data) == "Date"] <- as.character(substitute(dates))
names(flow_data)[names(flow_data) == "Value"] <- as.character(substitute(values))
if(!as.character(substitute(groups)) %in% orig_cols) {
flow_data <- dplyr::select(flow_data, -STATION_NUMBER)
}
flow_data <- dplyr::group_by_at(flow_data, dplyr::vars(flow_data_groups))
dplyr::as_tibble(flow_data)
} |
logit <- function(x){
log(x/(1-x))
}
plogit <- function(x, m, s){
pnorm(log(x/(1-x)), m ,s)
}
qlogit <- function(x, m, s){
z <- qnorm(x, m, s)
exp(z) / (1 + exp(z))
}
dlogit <- function(x, m, s){
1 / (x * (1 - x)) * dnorm(log(x / (1 - x)), m, s)
}
psample <- function(medianfit, precisionfit, lower = NA, upper = NA,
median.dist, precision.dist, n.rep = 10000, n.X = 100){
mediandist <- getmediandist(medianfit, median.dist)
f <- getdists(precisionfit$transform)
lim <- getlimits(lower, upper, f, mediandist, precisionfit)
X <- seq(from = lim$lower, to = lim$upper, length = n.X)
Xmat <- matrix(X, n.rep, n.X, byrow=T)
mu <- matrix(mediandist$rand(n.rep, mediandist$m, mediandist$s), n.rep, n.X)
if(precision.dist == "gamma"){
sigma <- matrix(sqrt(1 / rgamma(n.rep, precisionfit$Gamma[[1]],
precisionfit$Gamma[[2]])),
n.rep, n.X)
}
if(precision.dist == "lognormal"){
sigma <- matrix(sqrt(1 / rlnorm(n.rep, precisionfit$Log.normal[[1]],
precisionfit$Log.normal[[2]])),
n.rep, n.X)
}
pX <- f$cdf(Xmat, f$trans(mu), sigma)
list(X=X, pX=pX)
}
taildensities <- function(m, s, tails, n.x, lower, upper, dens, quan, trans){
xl <- seq(from = lower, to = quan(tails/2, m, s),
length = n.x)
dl <- dens(xl, m, s)
xu <- seq(from = quan(1-tails/2, m, s), to = upper,
length = n.x)
du <- dens(xu, m, s)
data.frame(xl = xl, dl = dl, xu = xu, du = du)
}
getdists <- function(transform){
if (transform == "identity"){
dens <- dnorm
quan <- qnorm
cdf <- pnorm
trans <- identity
}
if (transform == "log"){
dens <- dlnorm
quan <- qlnorm
cdf <- plnorm
trans <- log
}
if (transform == "logit"){
dens <- dlogit
quan <- qlogit
cdf <- plogit
trans <- logit
}
list(dens = dens, quan = quan, trans = trans, cdf = cdf)
}
getlimits <- function(lower, upper, f, mediandist, precisionfit){
a<-precisionfit$Gamma[[1]]
b<-precisionfit$Gamma[[2]]
if(is.na(lower)) lower <- f$quan(0.001,
f$trans(mediandist$quan(0.001, mediandist$m, mediandist$s)),
1/qgamma(0.001, a, b)^0.5)
if(is.na(upper)) upper <- f$quan(0.999,
f$trans(mediandist$quan(0.999, mediandist$m, mediandist$s)),
1/qgamma(0.001, a, b)^0.5)
list(lower = lower, upper = upper)
}
getmediandist <- function(medianfit, d){
if(d == "best"){
ssq <- medianfit$ssq
ssq[is.na(ssq)] <- Inf
if(ssq[1,1] < ssq[1,4]){d <- "normal"}else{d <- "lognormal"}
}
if(d == "normal"){
rand <- rnorm
quan <- qnorm
m <- medianfit$Normal[[1]]
s <- medianfit$Normal[[2]]
}
if(d == "lognormal"){
rand <- rlnorm
quan <- qlnorm
m <- medianfit$Log.normal[[1]]
s <- medianfit$Log.normal[[2]]
}
list(rand = rand, quan = quan, m = m, s=s)
}
addQuantileCDF <- function(lower, x1, q1, upper){
if(lower < x1 & x1 < upper){return(
annotate("segment", x = c(lower, x1),
y = c(q1, q1),
xend = c(x1, x1),
yend = c(q1, 0),
linetype = 2))}else{
return(NULL)
}
} |
NULL
fetch_symbol_map.external <- fetch_symbol_map.call
parse_source.external <- parse_source.call
parse_symbol_map.external <- parse_symbol_map.call
source_files.external_base <- source_files.call_base
source_files.external_cran <- source_files.call_cran
source_files.external_github <- source_files.call_github
source_files.external_local <- source_files.call_local |
get.ohlcs.google <- function(symbols,start="2013-01-01",end="today"){
n <- length(symbols)
ohlc=list()
temp <- strsplit(start,"-")
a=month.abb[as.numeric(temp[[1]][2])]
b=temp[[1]][3]
c=temp[[1]][1]
if(end != "today"){
temp <- strsplit(end,"-")
d=month.abb[as.numeric(temp[[1]][2])]
e=temp[[1]][3]
f=temp[[1]][1]
}else{
end=as.character(Sys.Date())
temp <- strsplit(end,"-")
d=month.abb[as.numeric(temp[[1]][2])]
e=temp[[1]][3]
f=temp[[1]][1]
}
for(i in 1:n){
URL=paste("https://www.google.com/finance/historical?q=",symbols[i],"&output=csv","&startdate=",a,"+",b,"+",c,"&enddate=",d,"+",e,"+",f, sep="")
myCsv <- getURL(URL, ssl.verifypeer = FALSE)
dat <- read.csv(textConnection(myCsv))
colnames(dat) <- c("date", "open", "high", "low", "close", "volume")
dates=as.character(dat$date)
for(j in 1:length(dates)){
tempdates=strsplit(dates[j],"-")
tempdates[[1]][2]=match(tempdates[[1]][2],month.abb)
tempd=paste(tempdates[[1]][1],tempdates[[1]][2],tempdates[[1]][3],sep="-")
dates[j]=format(as.Date(tempd,"%d-%m-%y"),"%Y-%m-%d")
}
dat$date=dates
dat=dat[order(dat$date),]
ohlc[[symbols[i]]]=dat
}
return(ohlc)
} |
roots_sh <- function(x, modulus = TRUE) {
if (!inherits(x, "varest")) {
stop("\nPlease provide an object inheriting class 'varest'.\n")
}
K <- x$K
p <- x$p
A <- unlist(Acoef_sh(x))
companion <- matrix(0, nrow = K * p, ncol = K * p)
companion[1:K, 1:(K * p)] <- A
if (p > 1) {
j <- 0
for (i in (K + 1):(K * p)) {
j <- j + 1
companion[i, j] <- 1
}
}
roots <- eigen(companion)$values
if (modulus)
roots <- Mod(roots)
return(roots)
} |
parCodaSamples <-
function(cl, model, variable.names = NULL, n.iter,
thin = 1, na.rm=TRUE, ...)
{
requireNamespace("rjags")
cl <- evalParallelArgument(cl, quit=TRUE)
if (!inherits(cl, "cluster"))
stop("cl must be of class 'cluster'")
if (!is.character(model))
model <- as.character(model)
cldata <- list(variable.names=variable.names,
n.iter=n.iter, thin=thin, name=model, na.rm=na.rm)
jagsparallel <- function(i, ...) {
cldata <- pullDcloneEnv("cldata", type = "model")
if (!existsDcloneEnv(cldata$name, type = "results"))
return(NULL)
res <- pullDcloneEnv(cldata$name, type = "results")
n.clones <- nclones(res)
out <- rjags::coda.samples(res, variable.names=cldata$variable.names,
n.iter=cldata$n.iter, thin=cldata$thin, na.rm=cldata$na.rm, ...)
pushDcloneEnv(cldata$name, res, type = "results")
if (!is.null(n.clones) && n.clones > 1) {
attr(out, "n.clones") <- n.clones
}
out
}
res <- parDosa(cl, 1:length(cl), jagsparallel, cldata,
lib = c("dclone", "rjags"), balancing = "none", size = 1,
rng.type = getOption("dcoptions")$RNG,
cleanup = TRUE,
dir = NULL,
unload=FALSE, ...)
res <- res[!sapply(res, is.null)]
n.clones <- lapply(res, nclones)
if (length(unique(unlist(n.clones))) != 1L) {
n.clones <- NULL
warnings("inconsistent 'n.clones' values, set to NULL")
} else n.clones <- n.clones[[1]]
for (i in 1:length(res)) {
attr(res, "n.clones") <- NULL
}
res <- as.mcmc.list(lapply(res, as.mcmc))
if (!is.null(n.clones) && n.clones > 1) {
attr(res, "n.clones") <- n.clones
class(res) <- c("mcmc.list.dc", class(res))
}
res
} |
metami <- function(data, M = 20, vcov = "r.vcov",
r.n.name, ef.name, x.name = NULL,
rvcov.method = "average",
rvcov.zscore = TRUE,
type = NULL,
d = NULL,
sdt = NULL,
sdc = NULL,
nt = NULL,
nc = NULL,
st = NULL,
sc = NULL,
n_rt = NA,
n_rc = NA,
r = NULL,
func = "mvmeta",
formula = NULL,
method = "fixed",
pool.seq = NULL,
return.mi = FALSE,
ci.level = 0.95){
pool <- c("coefficients")
dat <- data; rm(data)
p <- ncol(dat)
N <- nrow(dat)
if("mice" %in% rownames(installed.packages()) == FALSE) {install.packages("mice")}
predMatrix <- mice::make.predictorMatrix(dat)
cmplt <- colnames(dat)[unlist(lapply(1:p, function(i){
length(which(is.na(dat[,i]) == TRUE)) == 0}))]
if (length(cmplt) == p) stop('There is no missing values in your data')
predMatrix[cmplt, ] <- 0
imp <- mice::mice(dat, print = FALSE, m = M,
predictorMatrix = predMatrix,
method = mice::make.method(dat))
mis <- lapply(1:M, function(i){
unlist(lapply(1:p, function(j){imp$imp[[j]][, i]}) )})
if (return.mi) dat.mi <- list() else dat.mi <- NULL
pp <- 2
out.l <- list()
for (i in 1:M){
dat.imp <- as.data.frame(dat)
dat.imp[is.na(dat.imp)] <- mis[[i]]
vcov <- c("r.vcov", "mix.vcov")[match(vcov, c("r.vcov", "mix.vcov"))]
if (vcov == "r.vcov"){
obj <- r.vcov(n = dat.imp[, r.n.name],
corflat = subset(dat.imp, select = ef.name),
zscore = TRUE,
method = rvcov.method,
name = ef.name) } else if (vcov == "mix.vcov"){
if (!is.na(n_rt)) {n_rt <- dat.imp[, n_rt]}
if (!is.na(n_rc)) {n_rc <- dat.imp[, n_rc]}
eval.d <- as.data.frame(matrix(NA, N, length(d)))
colnames(eval.d) <- ef.name
eval.d[, !is.na(d)] <- dat.imp[, d[!is.na(d)]]
eval.sdt <- as.data.frame(matrix(NA, N, length(sdt)))
eval.sdt[, !is.na(sdt)] <- dat.imp[, sdt[!is.na(sdt)]]
eval.sdc <- as.data.frame(matrix(NA, N, length(sdc)))
eval.sdc[, !is.na(sdc)] <- dat.imp[, sdc[!is.na(sdc)]]
eval.nt <- as.data.frame(matrix(NA, N, length(nt)))
eval.nt[, !is.na(nt)] <- dat.imp[, nt[!is.na(nt)]]
eval.nc <- as.data.frame(matrix(NA, N, length(nc)))
eval.nc[, !is.na(nc)] <- dat.imp[, nc[!is.na(nc)]]
eval.st <- as.data.frame(matrix(NA, N, length(st)))
eval.st[, !is.na(st)] <- dat.imp[, st[!is.na(st)]]
eval.sc <- as.data.frame(matrix(NA, N, length(sc)))
eval.sc[, !is.na(sc)] <- dat.imp[, sc[!is.na(sc)]]
obj <- mix.vcov(type = type,
d = eval.d,
sdt = eval.sdt,
sdc = eval.sdc,
nt = eval.nt,
nc = eval.nc,
st = eval.st,
sc = eval.sc,
n_rt = n_rt,
n_rc = n_rc,
r = r,
name = ef.name)
}
if (rvcov.zscore == FALSE) {
if (vcov == "mix.vcov") {
stop("rvcov.zscore == FALSE only makes sense if argument vcov is r.vcov")}
y.name <- "r"
if (func == "metafixed") {y.v.name <- "list.rvcov"} else {
y.v.name <- "rvcov"}} else {
y.name <- "ef"
if (func == "metafixed") {y.v.name <- "list.vcov"} else {
y.v.name <- "matrix.vcov"}}
ef <- obj[[y.name]]
ef.v <- obj[[y.v.name]]
if (return.mi) dat.mi[[i]] <- list(dat.imp = dat.imp, ef = ef, ef.v = ef.v)
if (func == "mvmeta") {
pool <- c("coefficients", "qstat")
if("mvmeta" %in% rownames(installed.packages()) == FALSE) {install.packages("mvmeta")}
if (is.null(formula)) {
stop("Formula must be specified for mvmeta") } else {
if (is.null(x.name)) {
o <- mvmeta::mvmeta(formula = formula, S = ef.v,
data = ef, method = method) } else {
xdat <- subset(dat.imp, select = x.name)
o <- mvmeta::mvmeta(formula = formula, S = ef.v, method = method,
data = data.frame(ef, xdat))
}
} }
if (func == "metafixed") {
o <- metafixed(y = ef, Slist = ef.v)
pool <- c("coefficients", "qstat")}
if (func == "meta") {
pool <- c("coefficients", "Q.stat")
if("metaSEM" %in% rownames(installed.packages()) == FALSE) {install.packages("metaSEM")}
if (is.null(x.name)) {
o <- metaSEM::meta(y = ef, v = ef.v,
data = data.frame(ef,ef.v)) } else {
xdat <- subset(dat.imp, select = x.name)
o <- metaSEM::meta(y = ef, v = ef.v, x = xdat,
data = data.frame(ef, ef.v, xdat))
}}
oo <- summary(o)
output <- vector(mode = "list", length = pp)
names(output) <- pool
for (j in 1:pp){
output[[pool[j]]] <- as.data.frame(oo[[pool[j]]])
}
out.l[[i]] <- output
}
pp <- 1
out <- vector(mode = "list", length = pp)
names(out) <- "coefficients"
for (j in 1:pp){
temp <- lapply(1:M, function(i) { out.l[[i]][[j]] })
out[[j]] <- Reduce("+", temp) / M
}
rnames <- rownames(out[["coefficients"]])
out[["coefficients"]] <- rubinpool(out.l, ci.level, rnames)
result <- out
result$data.mi <- dat.mi
result$results.mi <- out.l
if (!is.null(pool.seq)){
temp <- vector(mode = "list", length = length(pool.seq))
names(temp) <- paste("M", pool.seq, sep ="")
for (i in 1:length(pool.seq)){
for (j in 1:pp){
tmp <- lapply(1:pool.seq[i], function(i) { out.l[[i]] })
temp[[i]][[j]] <- rubinpool(tmp, ci.level, rnames)
}
names(temp[[i]]) <- "coefficients"
}
result$result.seq <- temp
}
class(out) <- class(result) <- "metami"
cat(paste("pooled results from", M,
"imputations for missing values in",
paste(setdiff(colnames(dat), cmplt), collapse = ","), "\n"))
print(summary(out))
result
}
print.summary.metami <- function(x, ...){
digits = 4
cat("Fixed-effects coefficients","\n",sep="")
signif <- symnum(x$coefficients[,"Pr(>|z|)"],corr=FALSE,na=FALSE,
cutpoints=c(0, 0.001,0.01,0.05,0.1,1),
symbols=c("***","**","*","."," "))
tabletot <- formatC(x$coefficients,digits=digits,format="f")
tabletot <- cbind(tabletot,signif)
colnames(tabletot)[7] <- ""
print(tabletot,quote=FALSE,right=TRUE,print.gap=2)
cat("---\nSignif. codes: ",attr(signif,"legend"),"\n\n")
}
summary.metami <- function(object, ...){
fit = object
ci.level = 0.95
x <- list(coefficients = fit$coefficients[!is.na(fit$coefficients[,2]),])
class(x) <- "summary.metami"
x
}
maketable <- function(fit, ci.level = 0.95, names){
coef <- as.numeric(fit$coef)
coef.se <- as.numeric(fit$vcov)
zval <- coef/coef.se
zvalci <- qnorm((1 - ci.level)/2,lower.tail = FALSE)
pvalue <- 2*(1-pnorm(abs(zval)))
ci.lb <- coef-zvalci*coef.se
ci.ub <- coef+zvalci*coef.se
cilab <- paste(signif(ci.level,2)*100,"%ci.",c("lb","ub"),sep = "")
tab <- cbind(coef, coef.se, zval, pvalue, ci.lb, ci.ub)
dimnames(tab) <- list(names,
c("Estimate","Std. Error","z","Pr(>|z|)",cilab))
tab
}
rubinpool <- function(o.list, ci.level, names){
M <- length(o.list)
theta <- do.call(rbind, lapply(1:M, function(i){
o.list[[i]]$coefficients[,1]}))
vw <- do.call(rbind, lapply(1:M, function(i){
o.list[[i]]$coefficients[,2]}))
Vw <- colMeans(vw^2)
thetabar <- colMeans(theta)
Vb <- colSums(theta - matrix(rep(thetabar, M), nrow = M, byrow = TRUE))^2/(M-1)
Vtotal <- Vw + Vb + Vb/M
fito <- list(coef = thetabar, vcov = sqrt(Vtotal))
maketable(fito, ci.level = ci.level, names)
} |
data("dataLatentIV")
context("Inputchecks - latentIV - Parameter formula")
test_that("Fail if no formula object is passed", {
expect_error(latentIV(formula = data.frame(1:3), data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = NULL, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = NA, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = , data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("Fail if bad 1st RHS", {
expect_error(latentIV(formula = y ~ I + P , data = cbind(I=1, dataLatentIV)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ X1 + X2 + P , data = cbind(X1=1.23, X2=2.34, dataLatentIV)), regexp = "The above errors were encountered!")
})
test_that("Fail if bad 2nd RHS", {
expect_error(latentIV(formula = y ~ P | P, data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("Fail if bad LHS", {
expect_error(latentIV(formula = ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y1 + y2 ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y1 + y2 + y3 ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y1 | y2 ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = P ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ y, data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("Fail if formula variables are not in data", {
expect_error(latentIV(formula = y ~ P, data = data.frame(y=1:10, X1=1:10, X2=1:10)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = data.frame(X1=1:10,X2=1:10, P=1:10)), regexp = "The above errors were encountered!")
})
test_that("Fail if formula contains dot (.)", {
expect_error(latentIV(formula = . ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ ., data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("Fail if formula variables are not in data", {
expect_error(latentIV(formula= y ~ P ,data=data.frame(y=1:10)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula= y ~ P ,data=data.frame(P=1:10)), regexp = "The above errors were encountered!")
})
context("Inputchecks - latentIV - Parameter data")
test_that("Fail if not data.frame", {
expect_error(latentIV(formula = y ~ P, data = ), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = NULL), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = NA_integer_), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = c(y=1:10, P=1:10)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = list(y=1:10,P=1:10)), regexp = "The above errors were encountered!")
})
test_that("Fail if no rows or cols",{
expect_error(latentIV(formula = y ~ P, data = data.frame()), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = data.frame(y=integer(), P=integer())), regexp = "The above errors were encountered!")
})
test_that("Fail if contains any non-finite", {
call.args <- list(formula=y ~ P)
test.nonfinite.in.data(data = dataLatentIV, name.col = "y", fct = latentIV, call.args = call.args)
test.nonfinite.in.data(data = dataLatentIV, name.col = "P", fct = latentIV, call.args = call.args)
})
test_that("Fail if wrong data type in any of the formula parts", {
expect_error(latentIV(formula = y ~ P, data = data.frame(y=factor(1:10), P=1:10)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = data.frame(y=1:10, P=factor(1:10)), regexp = "The above errors were encountered!"))
expect_error(latentIV(formula = y ~ P, data = data.frame(y=as.character(1:10), P=1:10, stringsAsFactors=FALSE)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = data.frame(y=1:10, P=as.character(1:10), stringsAsFactors=FALSE)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = data.frame(y=as.logical(0:9), P=1:10)), regexp = "The above errors were encountered!")
expect_error(latentIV(formula = y ~ P, data = data.frame(y=1:10, P=as.logical(0:9)), regexp = "The above errors were encountered!"))
})
test_that("Allow wrong data type in irrelevant columns", {
expect_silent(latentIV(formula = y ~ P, verbose = FALSE,
data = cbind(dataLatentIV,
unused1=as.logical(0:9), unused2=as.character(1:10),unused3=as.factor(1:10), stringsAsFactors = FALSE)))
})
context("Inputchecks - latentIV - Parameter start.params")
test_that("start.params is vector and all numeric", {
expect_error(latentIV(start.params = c("(Intercept)"=2, P = as.character(1)), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = as.factor(c("(Intercept)"=2, P = 1)), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = as.logical(c("(Intercept)"=2, P = 1)), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = as.matrix(c("(Intercept)"=2, P = 0)), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = complex(1,4,2)), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("start.params is not NA",{
expect_error(latentIV(start.params = c("(Intercept)"=2, P = NA_integer_), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = NA_real_), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=NA_integer_, P = 2), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=NA_real_, P = 2), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = NA_integer_, formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = NA_real_, formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("start.params is NULL or missing but runs with message", {
expect_message(latentIV(start.params = , formula = y ~ P, data = dataLatentIV), regexp = "No start parameters were given")
expect_message(latentIV(start.params = NULL, formula = y ~ P, data = dataLatentIV), regexp = "No start parameters were given")
})
test_that("start.params is named correctly", {
expect_error(latentIV(start.params = c(2, 1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c(2, P=0), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, p = 1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 1, P = 2), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 1, P2 =3), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c(P = 2), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("Intercept"=2, P = 0), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(intercept)"=2, P = 0), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0),
formula = y ~ X1 + X2 + P -1 |P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, X1 = 1, P = 0), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
})
test_that("start.params contains no parameter named pi1, pi2, theta5, theta6, theta7, theta8", {
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, pi1=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, pi2=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, theta5=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, theta6=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, theta7=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, theta8=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, pi1=1, pi2=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, pi1=1, theta5=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, theta7=1, pi2=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, P = 0, pi1=1, pi2=1, theta5=1, theta6=1, theta7=1, theta8=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, pi1=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, pi2=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, theta5=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, theta6=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, theta7=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
expect_error(latentIV(start.params = c("(Intercept)"=2, theta8=1), formula = y ~ P, data = dataLatentIV), regexp = "The above errors were encountered!")
})
context("Inputchecks - latentIV - Parameter optimx.args")
test.optimx.args(function.to.test = latentIV, parameter.name = "optimx.args", formula=y~P,
function.std.data = dataLatentIV)
test_that("Has default value empty list()",{
default.arg <- eval(formals(REndo:::latentIV)[["optimx.args"]])
expect_equal(class(default.arg), "list")
})
context("Inputchecks - latentIV - Parameter verbose")
test.single.logical(function.to.test = latentIV, parameter.name="verbose",
formula=y~P, function.std.data=dataLatentIV) |
lintNamespace <- function (namespace, checkPackages = TRUE)
{
resetErrors(file = namespace)
if (isTRUE(checkPackages)) allpacks <- .packages(all.available = TRUE)
test <- try(getNamespace("tools")$.check_namespace(
dirname(tools::file_path_as_absolute(namespace))), silent = TRUE)
if (inherits(test, "try-error")) {
if (regexpr("object is not subsettable", test) > 0) {
lengths <- sapply(p, length)
if (any(lengths == 1)) {
line <- attr(p, "srcref")[[which(lengths == 1)[1]]][1]
addError(file = namespace, line = line,
message = "object is not subsettable")
}
} else addError(parseError(test))
}
p <- suppressWarnings(parse(namespace))
directives <- sapply(p, function(x) as.character(x[[1]]))
namespaceDirectives <- c("export", "exportPattern", "exportClass",
"exportClasses", "exportMethods", "import", "importFrom",
"importClassFrom", "importClassesFrom", "importMethodsFrom",
"useDynLib", "S3method", "if")
if (any(test <- !directives %in% namespaceDirectives)) {
problemLine <- sapply(attr(p, "srcref")[test],
function(x) as.integer(x[1]))
addError(file = namespace, line = problemLine,
message = paste("`", directives[test],
"` : Wrong NAMESPACE directive", sep = ""), type = "warning")
}
nS3 <- 0
here <- environment()
parseDirective <- function (e, srcref, p, i) {
asChar <- function (cc) {
r <- as.character(cc)
if (any(r == ""))
addError(file = namespace, type = "error",
message = gettextf("empty name in directive '%s' in NAMESPACE file",
as.character(e[[1]])), line = srcref[1])
return(r)
}
switch(as.character(e[[1]]),
"if" = {
if (eval(e[[2]], .GlobalEnv)) parseDirective(e[[3]], srcref) else
if (length(e) == 4) parseDirective(e[[4]], srcref)
}, "{" = for (ee in as.list(e[-1])) parseDirective(ee, srcref),
"=", "<-" = {
parseDirective(e[[3]], srcref)
}, export = {
exp <- e[-1]
exp <- structure(asChar(exp), names = names(exp))
if (!length(exp))
addError( file = namespace, line = srcref[1],
message = "empty export", type = "warning")
}, exportPattern = {
pat <- asChar(e[-1])
if (!length(pat))
addError( file = namespace, line = srcref[1],
message = "empty pattern", type = "warning")
if (asChar(regexpr("[^\\\\]\\\\[^\\\\]", attr(p, "srcref")[[i]]) > 0))
addError( file = namespace, line = srcref[1],
message = "wrong pattern, need to double escape", type = "warning")
}, exportClass = , exportClasses = {
}, exportMethods = {
}, import = {
packages <- asChar(e[-1])
if (!length(packages))
addError(file = namespace, line = srcref[1],
message = "empty import directive", type = "warning")
if (isTRUE(checkPackages)) {
test <- packages %in% allpacks
if (any(!test))
addError(line = srcref[1], file = namespace, type = "error",
message = sprintf("package `%s` is set to be imported but is not available",
packages[!test]))
}
}, importFrom = {
imp <- asChar(e[-1])
if (length(imp) < 2) {
addError(file = namespace, line = srcref[1],
message = "Not enough information in importFrom directive", type = "error")
} else {
if (!require(imp[1], character.only = TRUE)) {
addError(line = srcref[1], file = namespace, type = "error",
message = sprintf("package `%s` is set to be imported but is not available",
imp[1]))
} else if(any(test <- !imp[-1] %in% ls(sprintf("package:%s", imp[1])))) {
addError(line = srcref[1], file = namespace, type = "error",
message = sprintf("object `%s` not exported from %s",
imp[-1][test], imp[1]))
}
}
}, importClassFrom = , importClassesFrom = {
imp <- asChar(e[-1])
if (length(imp) < 2) {
addError(file = namespace, line = srcref[1],
message = "Not enough information in importFrom directive",
type = "error")
} else if (!require(imp[1], character.only = TRUE)) {
addError(line = srcref[1], file = namespace, type = "error",
message = sprintf("package `%s` is set to be imported but is not available",
imp[1]))
}
}, importMethodsFrom = {
imp <- asChar(e[-1])
if (length(imp) < 2) {
addError(file = namespace, line = srcref[1],
message = "Not enough information in importFrom directive",
type = "error")
} else if (!require(imp[1], character.only = TRUE)) {
addError(line = srcref[1], file = namespace, type = "error",
message = sprintf("package `%s` is set to be imported but is not available",
imp[1]))
}
}, useDynLib = {
}, S3method = {
spec <- e[-1]
if (length(spec) != 2 && length(spec) != 3)
addError(message = gettextf("bad 'S3method' directive: %s",
deparse(e)), file = namespace, line = srcref[1],
type = "error")
assign("nS3", get("nS3", envir = here) + 1, envir = here)
if (nS3 > 500)
addError(message= "too many 'S3method' directives",
file = namespace, line = srcref[1], type = "error")
})
}
for (i in 1:length(p) ) {
srcref <- attr(p, "srcref")
parseDirective(p[[i]], as.integer(srcref[[i]]), p, i)
}
return(getErrors(file = namespace))
} |
context("select")
test_that("list.select", {
x <- list(p1 = list(type = "A", score = list(c1 = 10, c2 = 8)), p2 = list(type = "B",
score = list(c1 = 9, c2 = 9)), p3 = list(type = "B", score = list(c1 = 9,
c2 = 7)))
expect_identical(list.select(x, type), lapply(x, function(xi) {
xi["type"]
}))
expect_identical(list.select(x, type, score), lapply(x, function(xi) {
xi[c("type", "score")]
}))
expect_identical(list.select(x, range = range(unlist(score))), lapply(x, function(xi) {
list(range = range(unlist(xi$score)))
}))
expect_identical(list.select(x, n = length(.)), lapply(x, function(xi) {
list(n = length(xi))
}))
lapply(1:3, function(i) list.select(x, p = score$c1 + i))
}) |
getRecursions.data.frame = function(x, radius, threshold = 0, timeunits = c("hours", "secs", "mins", "days"), verbose = TRUE)
{
stopifnot(is.data.frame(x))
stopifnot(ncol(x) == 4)
stopifnot(radius > 0)
timeunits = match.arg(timeunits)
results = getRecursionsCpp(x[,1], x[,2], x[,3], x[,4], x[,1], x[,2],
radius, threshold, timeunits, verbose)
results$timeunits = timeunits
class(results) = "recurse"
if (verbose)
{
class(results) = c("recurse", "recurse.verbose")
dataTz = attr(x[,3], "tzone")
if (!is.null(dataTz))
{
attr(results$revisitStats$entranceTime, "tzone") = dataTz
attr(results$revisitStats$exitTime, "tzone") = dataTz
}
}
return(results)
} |
matddhellingerpar <-
function(freq) {
distances = diag(0, nrow = length(freq))
dimnames(distances) = list(names(freq), names(freq))
for (i in 2:length(freq)) for (j in 1:(i-1)) {
distances[i, j] = distances[j, i] = ddhellingerpar(freq[[i]], freq[[j]])
}
as.dist(distances)
} |
sparseCov <- function(
dat, alf=0.5, iter=10, pnrm=Inf, THRSH='hard'
){
return(
sparseMat(
cov(dat),ncol(dat),alf,iter,pnrm,THRSH
)
);
} |
test_that("translate_SQRT returns the expected string", {
expect_equal(translate_SQRT("SQRT(x)"), "sqrt(x)")
}) |
print.summary.speff <- function(x,...){
if (!is.null(x$rsq)){
cat("\nOptimal models using",x$method,"method:\n")
if (x$predicted[1]) cat("Control: ",format(x$formula$control),", R-squared: ",round(x$rsq[1],2),"\n",sep="")
if (x$predicted[2]) cat("Treatment: ",format(x$formula$treatment),", R-squared: ",round(x$rsq[2],2),"\n",sep="")
}
cat("\nTreatment effect\n")
print(x$tab, digits=5, print.gap=2)
} |
Get.Publication.info <-function(Searchquery,
Publicationinfo = c("title",
"source",
"lastauthor",
"pubtype",
"pubdate",
"pmcrefcount"),Output = NULL)
{
Query_result <- entrez_search(db = "pubmed", term = Searchquery)
Query_result <- entrez_search(db = "pubmed", term = Searchquery,
retmax = Query_result$count)
PubmedIds <- Query_result$ids
Publication.data <-
as.data.frame(matrix(ncol = length(Publicationinfo), nrow = 1))
colnames(Publication.data) <- Publicationinfo
Counter <- 1
for (Id in PubmedIds)
{
taxize_summ <- tryCatch({
entrez_summary(db = "pubmed", id = Id)
}, error = function(cond) {
message(paste0("ID ", Id, " cause an error."))
})
print(paste0(Counter, " Finished out of ", length(PubmedIds)))
Counter <- Counter + 1
Publication.info <- NULL
for (Paperinfo in Publicationinfo)
{
Publication.info <- c(Publication.info, paste0(taxize_summ[[Paperinfo]], collapse = " "))
}
Publication.data <- rbind(Publication.data, Publication.info)
}
Publication.data <- na.omit(Publication.data)
if (!is.null(Output))
{
write.csv(Publication.data, paste0(Output, "/Publications.csv"))
}
return(Publication.data)
} |
NULL
.dbGetQuery <- function(conn, statement, ...) {
result <- dbSendQuery(conn, statement, ...)
on.exit(dbClearResult(result))
return(.fetch.all(result))
}
setMethod('dbGetQuery', c('PrestoConnection', 'character'), .dbGetQuery) |
refNote <-
function(text = "This is a test note", number = "*"){
out <- paste('<span class="ref"><span class="refnum">[',
number,
']</span><span class="refbody">',
text,
'</span></span>',
sep = "")
return(out)
} |
cal.cox.coef <-
function (gnExpMat, survivaltime, censor){
cox.coef = NULL
max.col = ifelse (is.matrix(gnExpMat), ncol(gnExpMat), 1)
for (i in 1:max.col){
if(is.matrix(gnExpMat))
var = gnExpMat[,i]
else
var = gnExpMat
cox.t = coxph(Surv (survivaltime, censor)~var)
cox.coef = c(cox.coef, cox.t$coef)
}
return (cox.coef)
} |
library(hamcrest)
expected <- c(-0x1.add9e4ddca7dp+9 + 0x0p+0i, -0x1.7f227fa8f63a4p+4 + -0x1.edf266ade3082p+7i,
-0x1.348fafee85b6dp+5 + 0x1.8016e53c0d5edp+6i, -0x1.2d932f6fe8a19p+8 + 0x1.21df47692c1f4p+7i,
-0x1.dea5cff330756p+6 + 0x1.7c7c236101e3ep+3i, -0x1.4d0b483e5ff8ap+7 + -0x1.48a590f868673p+7i,
-0x1.8df13854bb9c7p+6 + 0x1.a45c9ad7b1119p+7i, -0x1.20f83291dd046p+7 + 0x1.100d807de1125p+5i,
-0x1.acfa792dbb668p+7 + -0x1.7839e6f3578f3p+6i, -0x1.03475e70a1d74p+4 + 0x1.0410882c62405p+7i,
-0x1.ab43887f1f2bep+6 + -0x1.d9bb0bbb680e3p+6i, -0x1.62e090103e3a1p+6 + 0x1.377dce48c7982p+8i,
-0x1.526cc38a2d7a5p+8 + 0x1.a02a4db052bp+6i, 0x1.748ff0009b228p+3 + -0x1.b555ba784d423p+6i,
-0x1.3b13484152468p+7 + 0x1.6994f832c3674p+7i, -0x1.580b6402b7901p+5 + -0x1.d55e3ba7476a7p+4i,
0x1.0fe6bd5fc1704p+7 + 0x1.93cbde2b58122p+5i, -0x1.d8447fb83e9d4p+5 + 0x1.a6a15f95eb11ap+7i,
-0x1.49df9a72c863ep+5 + 0x1.30e567441ceccp+5i, -0x1.30042a91d1a47p+7 + -0x1.2e93987d142bep+6i,
0x1.d886a19a47407p+7 + 0x1.7b93d04127a9cp+6i, 0x1.bf4e7f840dd68p+4 + -0x1.087bb424aa774p+5i,
-0x1.f9f311a1245p-2 + -0x1.e2570517fedfap+6i, 0x1.62fc496b6cd77p+7 + 0x1.06081ecb0ba38p+4i,
0x1.6d4e5be45fddcp+6 + 0x1.aee5daf3effa2p+7i, 0x1.7ced1ac842e46p+4 + 0x1.f646dea54892ap+5i,
-0x1.7f79060d5f6e2p+7 + 0x1.d0f8a49e432c8p+5i, 0x1.3b3e8b2b4cd02p+7 + -0x1.2aad1083c37a6p+7i,
0x1.682cb4f803048p+5 + 0x1.c32c867b4804p+7i, 0x1.061eac1aa950bp+7 + -0x1.1d0b3a37ec118p+6i,
-0x1.0542e3e6da282p+5 + 0x1.b4cbfdb6eb8a6p+6i, 0x1.f6e007af08328p+4 + -0x1.e4d2121f9b84bp+7i,
-0x1.ee8ae9929034cp+4 + -0x1.35f1ea9dda048p+4i, -0x1.a33b282ed55ap+3 + -0x1.c595beacee0a3p+4i,
-0x1.271e1ab82b1fcp+4 + -0x1.49b710f2e114ap+6i, 0x1.f32e76c8b67c2p+6 + -0x1.237625f037794p+6i,
-0x1.ceca5538b8dbcp+6 + -0x1.66228a1a609f1p+6i, 0x1.70cd356e02b6ap+5 + 0x1.2ac0486e05ff5p+4i,
0x1.9d551f3e8e17ep+4 + -0x1.09a670b211e74p+5i, 0x1.32dfab510574cp+8 + -0x1.880707c938e46p+7i,
-0x1.1bfef62bb6214p+6 + -0x1.e28f005805a76p+5i, 0x1.9ff19e1d6a52cp+6 + -0x1.765af3ed3df4ap+6i,
-0x1.6887809dcdbddp+6 + 0x1.e20c3dc56327p+5i, 0x1.014c33d4d56dp+6 + -0x1.b12ce623ac49cp+5i,
0x1.3497065b89cf6p+5 + -0x1.49c121038177cp+6i, -0x1.ed9d8e7f0c28ep+5 + -0x1.9232f96baa1a3p+6i,
-0x1.8cf45e6866c9cp+3 + 0x1.bf97cbf312f58p+3i, 0x1.030b58a34c778p+6 + -0x1.e0ac6d29e8712p+6i,
-0x1.4394681263fap+6 + -0x1.b8e6b7d9c9ecfp+5i, -0x1.705ab246602cep+6 + -0x1.d20a644442702p+5i,
-0x1.2c258312070ccp+6 + -0x1.05b166b53b4c2p+6i, -0x1.a18c016dea55ep+3 + -0x1.20fc6927f269fp+7i,
-0x1.7c2ba71e200a2p+6 + -0x1.9a03be6dda49cp+4i, 0x1.829c09324c7cp+0 + -0x1.6f8eba793ed3cp+5i,
-0x1.309f59d3cf6c2p+6 + -0x1.d7b51ef6c9db4p+5i, -0x1.746235f1dafa2p+3 + -0x1.b4695db215fbdp+5i,
0x1.28c684d18acaap+5 + 0x1.5ce6b01c06bdbp+4i, 0x1.1aa757177974p+5 + 0x1.2dd1153be5ddbp+6i,
-0x1.21a64f5e4b9dap+6 + -0x1.59cd26b805beap+5i, 0x1.501dead17b853p+5 + -0x1.ed6a03ea0a758p+3i,
0x1.ffad6cb26cfe7p+5 + 0x1.24615856ae181p+4i, -0x1.eb5f0d98af99ap+4 + 0x1.024e6da4d8758p+3i,
-0x1.9654a31c06158p+4 + 0x1.0e8796fc9385ap+4i, 0x1.6228f29a747f2p+5 + 0x1.8d37be991acp-5i,
-0x1.60b191682d337p+5 + 0x1.4956f8cf808ep+5i, -0x1.db423979f0458p+2 + 0x1.fb068f0fe0bbap+5i,
0x1.7c1a176e66ep-2 + 0x1.3a37886a76aa2p+4i, -0x1.c651d8d321f56p+4 + 0x1.03a449b48801fp+4i,
0x1.0bdfc335e3e42p+5 + -0x1.3ebb35793ae9cp+6i, 0x1.a0557c0e0079p+4 + 0x1.25f9edbbb791fp+4i,
0x1.5f1c0e3d26f7ep+2 + 0x1.d8077fd83a274p+4i, 0x1.db7a203173dfp+3 + -0x1.bc66b226884c1p+5i,
0x1.aadb4fce7cbf8p+0 + -0x1.9602bfa9b507p+2i, 0x1.b184aa1da4eacp+3 + 0x1.b20b4ad232304p+4i,
-0x1.f649c44852708p+2 + -0x1.8e5eac916962cp+4i, 0x1.a99a62e00dd3cp+3 + -0x1.881f5bd7b3c4dp+4i,
0x1.b1711d89d26b6p+4 + 0x1.6c07f3f3dfafap+4i, 0x1.c96bbbec53ceap+5 + -0x1.1ba2eba0ffe56p+4i,
0x1.dff38e3dca8cep+5 + -0x1.fc8fc6a6bea4p+3i, -0x1.83d7fd00e76f7p+5 + -0x1.3b5cbc1fff985p+6i,
-0x1.4f7f480dab12ap+5 + -0x1.13f2854080771p+4i, 0x1.f1d07e37243fp-1 + 0x1.bdf687849df11p+4i,
0x1.59115e5d2785p+1 + -0x1.257e7a1a2850cp+3i, 0x1.c6b0a18a37588p+4 + -0x1.48f1d72163dc5p+4i,
0x1.9fea9572e818ap+2 + -0x1.0c4b17b800aep-1i, 0x1.838da8ff8a597p+4 + 0x1.5de94b9e6f939p+5i,
-0x1.0c36c70fdef34p+2 + 0x1.ec4b5d4f2905p+2i, 0x1.d25816dd36118p+4 + -0x1.f474c4a3e1efep+5i,
-0x1.1566760d4eba8p+5 + -0x1.3130a9fe5877ap+5i, -0x1.f3d187e6d0ac9p+3 + -0x1.8ad4e346eef6cp+5i,
0x1.17835196c587p+5 + 0x1.3ad14337646bp+4i, -0x1.6ef6f5ba68065p+4 + -0x1.60c0de42ff23ep+6i,
-0x1.a608ed6f4def4p+4 + -0x1.49095e66919c3p+6i, -0x1.e1a0464429b2ap+4 + 0x1.5c4043a346299p+5i,
-0x1.88559e5d76afbp+6 + 0x1.07787b4dc4c15p+3i, -0x1.9f8410968c12p+3 + -0x1.228d9ea4b3429p+5i,
0x1.e17028d8e9cd6p+5 + -0x1.80670f352a9e6p+6i, 0x1.c3e3bcd284ef9p+3 + -0x1.3454b6492ef54p+2i,
-0x1.b18f09438aa78p+3 + -0x1.0d6431712859p+5i, 0x1.7cc7f4956824p+3 + -0x1.d3db42d45e58p-1i,
0x1.7fdf0cad7e89dp+4 + -0x1.cd855eae4040cp+4i, -0x1.d50d6a86b1d2ap+4 + 0x1.b1925b945f9p+2i,
0x1.13c5097d1dp-3 + 0x1.c62a30ed8c256p+5i, -0x1.015ab8080964p+5 + 0x1.2a27636d3ba56p+6i,
0x1.c5f1917aba4dp+2 + -0x1.aa747eba448ep+4i, 0x1.21073a7f209f4p+5 + 0x1.93057d3cf56a4p+5i,
-0x1.f1a2ac5a61d26p+3 + 0x1.f5d07e393039p+1i, -0x1.6b557181ea068p+5 + 0x1.10dc4b1cf4014p+6i,
0x1.5bbb8059a4dc9p+5 + -0x1.ad4d42a6d72afp+3i, 0x1.276587ba22be8p+3 + -0x1.e384a2b574e9p+1i,
0x1.ad4c8aeea418p+2 + 0x1.fdc3d39c69p-5i, -0x1.c223793e418bep+4 + 0x1.0900df676ae8ap+5i,
0x1.08916d80cfe4p+3 + -0x1.0023bbd92368ep+5i, 0x1.1082fb603b3acp+5 + 0x1.fb92732e289cp-1i,
0x1.3b9d4721a50b4p+3 + -0x1.4d8de0a552b66p+2i, 0x1.1d08c2bae7878p+3 + 0x1.0f8f83446f6c2p+4i,
0x1.49041adfb428ap+4 + -0x1.769391ac25ee4p+5i, 0x1.d631bd0d35248p+4 + 0x1.922bbd02c2258p+4i,
-0x1.05a10abc6c93cp+3 + -0x1.8a26576e35461p+5i, -0x1.fb06b0ee9a6d2p+3 + -0x1.2d46702f9628ap+6i,
0x1.cf2a21b90b3bp+3 + 0x1.648d8cbcdc1bap+5i, -0x1.158086b01ca2p+2 + -0x1.e87e4d7b90684p+3i,
-0x1.7845f1b7363cp+1 + -0x1.8adec2ce89961p+6i, 0x1.18355f386f2dp+0 + 0x1.7ede93a006fd9p+6i,
-0x1.34fbc37dfb54bp+5 + 0x1.a5881396bff14p+3i, -0x1.1474f3c6a783p+6 + -0x1.ce8db595beec3p+4i,
0x1.16ef8263f170cp+5 + -0x1.968530ea481bep+5i, -0x1.3bf3ed0d2893p+2 + -0x1.b4bb62daf666ap+5i,
0x1.54d9a6e48a27p+3 + 0x1.c8f708fa55ffp+4i, -0x1.a337042b579d4p+5 + -0x1.12bccd5e003bcp+4i,
-0x1.5cb2071686f96p+5 + -0x1.ae023e902dc9dp+6i, -0x1.b14b606925716p+5 + -0x1.bb6531af513ap+4i,
-0x1.f90b67c0ca8ecp+5 + 0x1.11c653854791ep+7i, -0x1.8aa579be03bbcp+7 + 0x1.01447335fd33p+5i,
0x1.c3df54f05eb28p+2 + -0x1.a9863d75c9734p+4i, 0x1.e59a3749eb78p+4 + 0x1.88891f7a0688p+0i,
-0x1.bf11cd467bb2bp+5 + 0x1.04223de1a199fp+7i, -0x1.592dc5eb26ddp+3 + 0x1.1f44417fe0654p+4i,
0x1.06d66773838c4p+6 + -0x1.6369d11f33daap+4i, 0x1.0d60bb39c4c78p+4 + -0x1.944d1d9d59e78p+5i,
-0x1.4a13aff3d5db9p+6 + 0x1.e414d1df6e355p+5i, -0x1.0f700b530012p+4 + 0x1.0e226e77efe74p+4i,
0x1.cc181ad84ec94p+4 + 0x1.4221ff36bec2p+6i, 0x1.8858a46b1dcebp+5 + -0x1.1fd2936d0d138p+5i,
-0x1.0cd1e76f5cda8p+4 + -0x1.ccf46c252f588p+4i, -0x1.bfcf3ccaaaee6p+4 + 0x1.745e7c7f1d56p+5i,
0x1.943858a568868p+6 + 0x1.eebe63cb03523p+6i, 0x1.f9c5f29cb00c7p+5 + -0x1.6c70518f522b5p+5i,
-0x1.eb501b23cc77p+3 + 0x1.27ab37b136bd4p+4i, 0x1.794127e21fe09p+6 + 0x1.703a9af5bf68p-1i,
0x1.053efc8675eecp+6 + 0x1.87b4f4b581fb2p+6i, -0x1.be407a59496e8p+3 + -0x1.dab196bd1a00ep+6i,
0x1.d6951f44eaebfp+5 + -0x1.3495babdaea46p+6i, 0x1.34641afd69e16p+5 + -0x1.83387d519d712p+5i,
0x1.93e2ea3e48c51p+5 + -0x1.da4d147fdf08bp+3i, 0x1.86617bd8ef836p+6 + -0x1.1abcd899c1d7ep+7i,
0x1.4524e1283c1cp+3 + -0x1.d7eae89540f7bp+5i, 0x1.064fc8ed49778p+4 + -0x1.30e923ed4e5c9p+7i,
-0x1.b2ff7f7517526p+5 + -0x1.260a2bdf71f32p+7i, 0x1.447bc9abc1444p+6 + -0x1.0567eb63a6448p+6i,
0x1.3f9f84e8b3a51p+4 + -0x1.03883ffb834a1p+7i, -0x1.097d7a6ba9732p+6 + -0x1.0a143ba94279p+8i,
0x1.795d7927573c3p+7 + -0x1.5ea6f7e54e5ep+4i, -0x1.417d7a5a7f6edp+5 + -0x1.2f25a8470981ap+7i,
-0x1.12c2a0d7f7cb3p+2 + -0x1.1793da602d88dp+7i, -0x1.a26fa6f92e90cp+3 + -0x1.f203bf9d9d8cp+4i,
0x1.75cb923fa68p+6 + -0x1.4dd0445738562p+8i, 0x1.9c6f719218984p+6 + 0x1.82077e60e5f9ep+7i,
-0x1.6f88cc1d575fdp+7 + -0x1.2ae552a46abe8p+6i, -0x1.e6d7a8effe1cep+7 + -0x1.45d187fba43f9p+7i,
-0x1.7a10382ffe0acp+6 + -0x1.8d0ad45dc4541p+7i, 0x1.db558c7b667f2p+4 + 0x1.e595f8aa8795ep+6i,
-0x1.348f1f150c90cp+8 + 0x1.c2f0b61c087e9p+5i, -0x1.37ee3f8ad063fp+4 + -0x1.1a9a14bd7c83fp+8i,
0x1.504bbafb64f4bp+7 + -0x1.66af6fe9d0726p+2i, -0x1.62ea14ed4fc05p+8 + 0x1.37e0df060ddcp+8i,
-0x1.0cf851aa95694p+8 + -0x1.672cede3f1b8bp+7i, -0x1.596ebf7511ce4p+7 + -0x1.2953c9da23fe4p+8i,
0x1.489ed2153c41ap+7 + -0x1.d417d08a51484p+7i, -0x1.4494201ab76dfp+7 + 0x1.4dd1eee6af7eap+8i,
-0x1.216f74b7dc12dp+7 + -0x1.6de3e2eba6226p+7i, 0x1.7fb9a62d3d764p+7 + 0x1.786b8610e2d7ap+6i,
-0x1.1c0c301063d22p+4 + -0x1.3bf96d871e3fbp+6i, -0x1.9abc265397a62p+7 + 0x1.a27d4272b8276p+7i,
-0x1.43ae52dc5fa8p+6 + -0x1.49cfbf40d1a0dp+5i, 0x1.7d52a00e9dc1cp+6 + 0x1.c87e487e7cc54p+4i,
0x1.ca21c9eb85291p+7 + -0x1.7ad28da332694p+6i, -0x1.dce40d11c9853p+6 + 0x1.d84be1235050fp+6i,
0x1.1470b17c0dfe3p+6 + 0x1.952ec4fed63a1p+6i, -0x1.2cf6fabc2ea63p+6 + 0x1.942177ef5e59ep+5i,
0x1.63d98b24b1efap+7 + -0x1.1e36447fb20bap+5i, -0x1.eb341aad4f387p+6 + 0x1.cd16f36faa17fp+6i,
0x1.d418e91837738p+0 + -0x1.abca793e4158ap+4i, -0x1.5e134b5e7d6d3p+5 + 0x1.18c9d9d50989p+4i,
0x1.367206937a3bep+6 + -0x1.b44463ea2e3aap+6i, 0x1.18f839e769866p+7 + 0x1.292d2f389ac6ap+6i,
0x1.08e981af5d95dp+6 + 0x1.9be2c2b4527f6p+4i, 0x1.0592a2b14982bp+3 + 0x1.142b485f4a24p+6i,
-0x1.f0d6b3ca42db6p+4 + -0x1.3c86602b4076ep+3i, 0x1.1b09d9900e7dcp+7 + 0x1.9c8580379a8e4p+6i,
-0x1.bdd989b44f07fp+3 + -0x1.05ba0f1439dbcp+6i, -0x1.1cbd02b95cec3p+6 + 0x1.fc780cc13f9d6p+5i,
0x1.615d7eefa0724p+7 + -0x1.d25b1e79797bbp+5i, 0x1.375e5500e329cp+6 + 0x1.43247812cfc16p+5i,
0x1.a8aba1cc19cd5p+3 + 0x1.dc93f01674c1p+0i, 0x1.60b9d1320e406p+4 + 0x1.cde7d88f27f8fp+6i,
-0x1.6df863d7314f4p+4 + -0x1.824be20a4f9f1p+6i, 0x1.52e3cc43f36b2p+5 + 0x1.0d9dd8aec47eap+5i,
0x1.9ad8b66b5b38p+6 + -0x1.a79778ffe1aep+4i, 0x1.b64cf4968cf7ap+6 + 0x1.6983bcb0346dap+4i,
0x1.70f584acf2c69p+4 + -0x1.27189e84ee5a5p+7i, 0x1.b5ff899f4280cp+5 + 0x1.6769a40702e5cp+5i,
0x1.584f6d26e48f3p+4 + 0x1.0038660262d5cp+6i, 0x1.993f06005b49cp+6 + 0x1.1273bdc0f5054p+5i,
0x1.a131f8ae6115ep+5 + -0x1.80bc65989c1b7p+5i, 0x1.76bde9602161bp+4 + 0x1.ba87bb3091368p+3i,
-0x1.3ac931618d30ep+3 + -0x1.08141eb65da9cp+6i, 0x1.ec0d2a204c851p+6 + 0x1.4e50437b5755ap+6i,
-0x1.6757876125ec9p+6 + -0x1.8b42a2dd74dd3p+5i, 0x1.ef35ccc2e3108p+4 + -0x1.947d7fb36962p+6i,
-0x1.3fe53bb272ca8p+6 + -0x1.26e8cef6cb9e2p+6i, 0x1.81e3cee9bc117p+5 + 0x1.1488a1d2fa226p+5i,
-0x1.b87207b977943p+6 + -0x1.a3c815aeadbd6p+5i, 0x1.1827d25489404p+4 + 0x1.bc99536db4b9ap+3i,
-0x1.36dd99cadcdbep+5 + 0x1.4b71da9969ae2p+3i, 0x1.42cb3a4106e6p-1 + 0x1.92b95bec1ca9cp+4i,
0x1.a23a2e1d45dap+4 + -0x1.85aee017a05e2p+5i, 0x1.48800c56e59d1p+3 + 0x1.2dd4f4470631dp+4i,
-0x1.9ee9e342900dap+3 + 0x1.84ecc6e1c2e8bp+5i, 0x1.f92856e41bbe8p+6 + 0x1.9d11c7925c0f2p+5i,
-0x1.65cc62c307aaap+6 + 0x1.c4556b90f44fbp+4i, 0x1.cf20a1bbbfee8p+3 + -0x1.5b8e2e1c1b1abp+4i,
-0x1.aeec33e8f1cd8p+6 + -0x1.06ff797e1f17dp+5i, 0x1.34303cd2962bep+5 + -0x1.f91e5eba6d54p+2i,
-0x1.5fce39193d054p+6 + -0x1.4p-48i, 0x1.34303cd2962c2p+5 + 0x1.f91e5eba6d49ep+2i,
-0x1.aeec33e8f1cd4p+6 + 0x1.06ff797e1f173p+5i, 0x1.cf20a1bbbfeefp+3 + 0x1.5b8e2e1c1b1ap+4i,
-0x1.65cc62c307aa7p+6 + -0x1.c4556b90f450ap+4i, 0x1.f92856e41bbdfp+6 + -0x1.9d11c7925c107p+5i,
-0x1.9ee9e342900bap+3 + -0x1.84ecc6e1c2e86p+5i, 0x1.48800c56e59dp+3 + -0x1.2dd4f44706336p+4i,
0x1.a23a2e1d45dbp+4 + 0x1.85aee017a05cfp+5i, 0x1.42cb3a4106e8p-1 + -0x1.92b95bec1ca99p+4i,
-0x1.36dd99cadcdbp+5 + -0x1.4b71da9969b4cp+3i, 0x1.1827d254893f6p+4 + -0x1.bc99536db4b59p+3i,
-0x1.b87207b977944p+6 + 0x1.a3c815aeadbcbp+5i, 0x1.81e3cee9bc11p+5 + -0x1.1488a1d2fa236p+5i,
-0x1.3fe53bb272ca6p+6 + 0x1.26e8cef6cb9d9p+6i, 0x1.ef35ccc2e3101p+4 + 0x1.947d7fb36962p+6i,
-0x1.6757876125edp+6 + 0x1.8b42a2dd74ddap+5i, 0x1.ec0d2a204c84bp+6 + -0x1.4e50437b5756p+6i,
-0x1.3ac931618d2e8p+3 + 0x1.08141eb65da9ap+6i, 0x1.76bde960215f8p+4 + -0x1.ba87bb3091365p+3i,
0x1.a131f8ae61153p+5 + 0x1.80bc65989c1b2p+5i, 0x1.993f06005b496p+6 + -0x1.1273bdc0f506p+5i,
0x1.584f6d26e4902p+4 + -0x1.0038660262d62p+6i, 0x1.b5ff899f42805p+5 + -0x1.6769a40702e5p+5i,
0x1.70f584acf2c67p+4 + 0x1.27189e84ee5a2p+7i, 0x1.b64cf4968cf7dp+6 + -0x1.6983bcb0346dfp+4i,
0x1.9ad8b66b5b383p+6 + 0x1.a79778ffe1ac5p+4i, 0x1.52e3cc43f36abp+5 + -0x1.0d9dd8aec47e1p+5i,
-0x1.6df863d7314f5p+4 + 0x1.824be20a4f9f2p+6i, 0x1.60b9d1320e402p+4 + -0x1.cde7d88f27f8ep+6i,
0x1.a8aba1cc19dp+3 + -0x1.dc93f01674cbp+0i, 0x1.375e5500e329fp+6 + -0x1.43247812cfc21p+5i,
0x1.615d7eefa0726p+7 + 0x1.d25b1e79797c2p+5i, -0x1.1cbd02b95cec5p+6 + -0x1.fc780cc13f9cdp+5i,
-0x1.bdd989b44f05bp+3 + 0x1.05ba0f1439dbcp+6i, 0x1.1b09d9900e7dap+7 + -0x1.9c8580379a8e6p+6i,
-0x1.f0d6b3ca42db2p+4 + 0x1.3c86602b40766p+3i, 0x1.0592a2b149828p+3 + -0x1.142b485f4a245p+6i,
0x1.08e981af5d95fp+6 + -0x1.9be2c2b45281p+4i, 0x1.18f839e769866p+7 + -0x1.292d2f389ac69p+6i,
0x1.367206937a3c6p+6 + 0x1.b44463ea2e3a8p+6i, -0x1.5e134b5e7d6cep+5 + -0x1.18c9d9d509876p+4i,
0x1.d418e9183776p+0 + 0x1.abca793e41583p+4i, -0x1.eb341aad4f38cp+6 + -0x1.cd16f36faa181p+6i,
0x1.63d98b24b1efap+7 + 0x1.1e36447fb20b2p+5i, -0x1.2cf6fabc2ea62p+6 + -0x1.942177ef5e592p+5i,
0x1.1470b17c0dfep+6 + -0x1.952ec4fed639fp+6i, -0x1.dce40d11c9858p+6 + -0x1.d84be12350509p+6i,
0x1.ca21c9eb85295p+7 + 0x1.7ad28da332694p+6i, 0x1.7d52a00e9dc25p+6 + -0x1.c87e487e7cc59p+4i,
-0x1.43ae52dc5fa86p+6 + 0x1.49cfbf40d1a18p+5i, -0x1.9abc265397a67p+7 + -0x1.a27d4272b8278p+7i,
-0x1.1c0c301063cf8p+4 + 0x1.3bf96d871e3fep+6i, 0x1.7fb9a62d3d763p+7 + -0x1.786b8610e2d7dp+6i,
-0x1.216f74b7dc12dp+7 + 0x1.6de3e2eba6229p+7i, -0x1.4494201ab76e5p+7 + -0x1.4dd1eee6af7eep+8i,
0x1.489ed2153c42p+7 + 0x1.d417d08a51484p+7i, -0x1.596ebf7511ce4p+7 + 0x1.2953c9da23fe6p+8i,
-0x1.0cf851aa95695p+8 + 0x1.672cede3f1b8ep+7i, -0x1.62ea14ed4fc08p+8 + -0x1.37e0df060ddcp+8i,
0x1.504bbafb64f4dp+7 + 0x1.66af6fe9d06f8p+2i, -0x1.37ee3f8ad0622p+4 + 0x1.1a9a14bd7c84p+8i,
-0x1.348f1f150c911p+8 + -0x1.c2f0b61c087ebp+5i, 0x1.db558c7b667e8p+4 + -0x1.e595f8aa8795fp+6i,
-0x1.7a10382ffe0adp+6 + 0x1.8d0ad45dc454ap+7i, -0x1.e6d7a8effe1dp+7 + 0x1.45d187fba43fap+7i,
-0x1.6f88cc1d575ffp+7 + 0x1.2ae552a46abeep+6i, 0x1.9c6f719218984p+6 + -0x1.82077e60e5fap+7i,
0x1.75cb923fa6802p+6 + 0x1.4dd0445738564p+8i, -0x1.a26fa6f92e92cp+3 + 0x1.f203bf9d9d8acp+4i,
-0x1.12c2a0d7f7c3p+2 + 0x1.1793da602d88ep+7i, -0x1.417d7a5a7f6e4p+5 + 0x1.2f25a84709822p+7i,
0x1.795d7927573cap+7 + 0x1.5ea6f7e54e5ecp+4i, -0x1.097d7a6ba9733p+6 + 0x1.0a143ba942794p+8i,
0x1.3f9f84e8b3a62p+4 + 0x1.03883ffb834a3p+7i, 0x1.447bc9abc144cp+6 + 0x1.0567eb63a644ep+6i,
-0x1.b2ff7f7517525p+5 + 0x1.260a2bdf71f37p+7i, 0x1.064fc8ed49778p+4 + 0x1.30e923ed4e5c8p+7i,
0x1.4524e1283c1cp+3 + 0x1.d7eae89540f7bp+5i, 0x1.86617bd8ef83p+6 + 0x1.1abcd899c1d77p+7i,
0x1.93e2ea3e48c42p+5 + 0x1.da4d147fdf06p+3i, 0x1.34641afd69e18p+5 + 0x1.83387d519d71p+5i,
0x1.d6951f44eaecp+5 + 0x1.3495babdaea3ep+6i, -0x1.be407a59496b4p+3 + 0x1.dab196bd19fffp+6i,
0x1.053efc8675efp+6 + -0x1.87b4f4b581fbp+6i, 0x1.794127e21fe0ap+6 + -0x1.703a9af5bf88p-1i,
-0x1.eb501b23cc766p+3 + -0x1.27ab37b136bd2p+4i, 0x1.f9c5f29cb00c1p+5 + 0x1.6c70518f522acp+5i,
0x1.943858a568864p+6 + -0x1.eebe63cb03524p+6i, -0x1.bfcf3ccaaaef6p+4 + -0x1.745e7c7f1d55cp+5i,
-0x1.0cd1e76f5cdb8p+4 + 0x1.ccf46c252f58p+4i, 0x1.8858a46b1dceap+5 + 0x1.1fd2936d0d13p+5i,
0x1.cc181ad84ec72p+4 + -0x1.4221ff36bec1ep+6i, -0x1.0f700b5300114p+4 + -0x1.0e226e77efe58p+4i,
-0x1.4a13aff3d5dbdp+6 + -0x1.e414d1df6e349p+5i, 0x1.0d60bb39c4c93p+4 + 0x1.944d1d9d59e68p+5i,
0x1.06d66773838c6p+6 + 0x1.6369d11f33daap+4i, -0x1.592dc5eb26dep+3 + -0x1.1f44417fe0648p+4i,
-0x1.bf11cd467bb34p+5 + -0x1.04223de1a199fp+7i, 0x1.e59a3749eb778p+4 + -0x1.88891f7a068p+0i,
0x1.c3df54f05eb5p+2 + 0x1.a9863d75c9714p+4i, -0x1.8aa579be03bbbp+7 + -0x1.01447335fd32p+5i,
-0x1.f90b67c0ca8f4p+5 + -0x1.11c653854791ep+7i, -0x1.b14b60692570ap+5 + 0x1.bb6531af513acp+4i,
-0x1.5cb2071686f83p+5 + 0x1.ae023e902dc9bp+6i, -0x1.a337042b579d6p+5 + 0x1.12bccd5e003c4p+4i,
0x1.54d9a6e48a258p+3 + -0x1.c8f708fa55fe6p+4i, -0x1.3bf3ed0d28928p+2 + 0x1.b4bb62daf666ap+5i,
0x1.16ef8263f1714p+5 + 0x1.968530ea481b7p+5i, -0x1.1474f3c6a7835p+6 + 0x1.ce8db595beec4p+4i,
-0x1.34fbc37dfb53fp+5 + -0x1.a5881396bfef8p+3i, 0x1.18355f386f28p+0 + -0x1.7ede93a006fd9p+6i,
-0x1.7845f1b73634p+1 + 0x1.8adec2ce8995fp+6i, -0x1.158086b01cap+2 + 0x1.e87e4d7b90688p+3i,
0x1.cf2a21b90b3c1p+3 + -0x1.648d8cbcdc1b7p+5i, -0x1.fb06b0ee9a6e9p+3 + 0x1.2d46702f96285p+6i,
-0x1.05a10abc6c924p+3 + 0x1.8a26576e3546p+5i, 0x1.d631bd0d3523ap+4 + -0x1.922bbd02c226p+4i,
0x1.49041adfb428fp+4 + 0x1.769391ac25ee5p+5i, 0x1.1d08c2bae7871p+3 + -0x1.0f8f83446f6c2p+4i,
0x1.3b9d4721a50bcp+3 + 0x1.4d8de0a552b4cp+2i, 0x1.1082fb603b3a7p+5 + -0x1.fb92732e28b4p-1i,
0x1.08916d80cfe67p+3 + 0x1.0023bbd923689p+5i, -0x1.c223793e418cdp+4 + -0x1.0900df676ae84p+5i,
0x1.ad4c8aeea418p+2 + -0x1.fdc3d39c6ap-5i, 0x1.276587ba22bf4p+3 + 0x1.e384a2b574d7p+1i,
0x1.5bbb8059a4dd5p+5 + 0x1.ad4d42a6d72dp+3i, -0x1.6b557181ea06bp+5 + -0x1.10dc4b1cf4013p+6i,
-0x1.f1a2ac5a61d1cp+3 + -0x1.f5d07e393032p+1i, 0x1.21073a7f209eap+5 + -0x1.93057d3cf56aap+5i,
0x1.c5f1917aba558p+2 + 0x1.aa747eba448dep+4i, -0x1.015ab8080963bp+5 + -0x1.2a27636d3ba58p+6i,
0x1.13c5097d1cc8p-3 + -0x1.c62a30ed8c251p+5i, -0x1.d50d6a86b1d3bp+4 + -0x1.b1925b945f924p+2i,
0x1.7fdf0cad7e8a9p+4 + 0x1.cd855eae404p+4i, 0x1.7cc7f49568254p+3 + 0x1.d3db42d45e7ep-1i,
-0x1.b18f09438aa9p+3 + 0x1.0d64317128599p+5i, 0x1.c3e3bcd284eeep+3 + 0x1.3454b6492eedp+2i,
0x1.e17028d8e9cdcp+5 + 0x1.80670f352a9e8p+6i, -0x1.9f8410968c0d8p+3 + 0x1.228d9ea4b3435p+5i,
-0x1.88559e5d76b03p+6 + -0x1.07787b4dc4c0cp+3i, -0x1.e1a0464429b34p+4 + -0x1.5c4043a3462ap+5i,
-0x1.a608ed6f4dedap+4 + 0x1.49095e66919ccp+6i, -0x1.6ef6f5ba6805ep+4 + 0x1.60c0de42ff23ep+6i,
0x1.17835196c5886p+5 + -0x1.3ad14337646acp+4i, -0x1.f3d187e6d0ab3p+3 + 0x1.8ad4e346eef8p+5i,
-0x1.1566760d4ebaap+5 + 0x1.3130a9fe58774p+5i, 0x1.d25816dd36125p+4 + 0x1.f474c4a3e1f0cp+5i,
-0x1.0c36c70fdeef8p+2 + -0x1.ec4b5d4f290c4p+2i, 0x1.838da8ff8a5acp+4 + -0x1.5de94b9e6f93ap+5i,
0x1.9fea9572e81cfp+2 + 0x1.0c4b17b800d4p-1i, 0x1.c6b0a18a375b8p+4 + 0x1.48f1d72163da8p+4i,
0x1.59115e5d2788p+1 + 0x1.257e7a1a2851ap+3i, 0x1.f1d07e3724968p-1 + -0x1.bdf687849df15p+4i,
-0x1.4f7f480dab129p+5 + 0x1.13f285408078ap+4i, -0x1.83d7fd00e76f6p+5 + 0x1.3b5cbc1fff984p+6i,
0x1.dff38e3dca8c9p+5 + 0x1.fc8fc6a6bea42p+3i, 0x1.c96bbbec53ce6p+5 + 0x1.1ba2eba0ffe56p+4i,
0x1.b1711d89d26b8p+4 + -0x1.6c07f3f3dfaf6p+4i, 0x1.a99a62e00dd31p+3 + 0x1.881f5bd7b3c6p+4i,
-0x1.f649c448527p+2 + 0x1.8e5eac9169624p+4i, 0x1.b184aa1da4ea8p+3 + -0x1.b20b4ad2322fap+4i,
0x1.aadb4fce7cd58p+0 + 0x1.9602bfa9b5074p+2i, 0x1.db7a203173e1ap+3 + 0x1.bc66b226884b9p+5i,
0x1.5f1c0e3d26f66p+2 + -0x1.d8077fd83a26ep+4i, 0x1.a0557c0e00796p+4 + -0x1.25f9edbbb7917p+4i,
0x1.0bdfc335e3e4ep+5 + 0x1.3ebb35793ae92p+6i, -0x1.c651d8d321f42p+4 + -0x1.03a449b488019p+4i,
0x1.7c1a176e66b8p-2 + -0x1.3a37886a76a9ap+4i, -0x1.db423979f047p+2 + -0x1.fb068f0fe0bbp+5i,
-0x1.60b191682d332p+5 + -0x1.4956f8cf808dep+5i, 0x1.6228f29a747ebp+5 + -0x1.8d37be9919cp-5i,
-0x1.9654a31c06162p+4 + -0x1.0e8796fc93859p+4i, -0x1.eb5f0d98af974p+4 + -0x1.024e6da4d874cp+3i,
0x1.ffad6cb26cfe8p+5 + -0x1.24615856ae171p+4i, 0x1.501dead17b84ap+5 + 0x1.ed6a03ea0a743p+3i,
-0x1.21a64f5e4b9d6p+6 + 0x1.59cd26b805bdep+5i, 0x1.1aa757177973bp+5 + -0x1.2dd1153be5dep+6i,
0x1.28c684d18acadp+5 + -0x1.5ce6b01c06bdep+4i, -0x1.746235f1dafc4p+3 + 0x1.b4695db215fb6p+5i,
-0x1.309f59d3cf6bep+6 + 0x1.d7b51ef6c9da6p+5i, 0x1.829c09324c84p+0 + 0x1.6f8eba793ed4p+5i,
-0x1.7c2ba71e200a1p+6 + 0x1.9a03be6dda4b7p+4i, -0x1.a18c016dea578p+3 + 0x1.20fc6927f269dp+7i,
-0x1.2c258312070cbp+6 + 0x1.05b166b53b4cp+6i, -0x1.705ab246602cap+6 + 0x1.d20a644442708p+5i,
-0x1.4394681263f9dp+6 + 0x1.b8e6b7d9c9ed4p+5i, 0x1.030b58a34c779p+6 + 0x1.e0ac6d29e8716p+6i,
-0x1.8cf45e6866cap+3 + -0x1.bf97cbf312f4ap+3i, -0x1.ed9d8e7f0c286p+5 + 0x1.9232f96baa1ap+6i,
0x1.3497065b89cf4p+5 + 0x1.49c121038178p+6i, 0x1.014c33d4d56cfp+6 + 0x1.b12ce623ac48fp+5i,
-0x1.6887809dcdbdcp+6 + -0x1.e20c3dc56326cp+5i, 0x1.9ff19e1d6a53p+6 + 0x1.765af3ed3df49p+6i,
-0x1.1bfef62bb620fp+6 + 0x1.e28f005805a8p+5i, 0x1.32dfab510574bp+8 + 0x1.880707c938e48p+7i,
0x1.9d551f3e8e182p+4 + 0x1.09a670b211e77p+5i, 0x1.70cd356e02b6p+5 + -0x1.2ac0486e0601p+4i,
-0x1.ceca5538b8db8p+6 + 0x1.66228a1a609f1p+6i, 0x1.f32e76c8b67c6p+6 + 0x1.237625f037797p+6i,
-0x1.271e1ab82b1fcp+4 + 0x1.49b710f2e114dp+6i, -0x1.a33b282ed55ap+3 + 0x1.c595beacee0a7p+4i,
-0x1.ee8ae9929036p+4 + 0x1.35f1ea9dda04cp+4i, 0x1.f6e007af0834ap+4 + 0x1.e4d2121f9b84cp+7i,
-0x1.0542e3e6da27cp+5 + -0x1.b4cbfdb6eb8a6p+6i, 0x1.061eac1aa951p+7 + 0x1.1d0b3a37ec11p+6i,
0x1.682cb4f80303dp+5 + -0x1.c32c867b4804p+7i, 0x1.3b3e8b2b4cd03p+7 + 0x1.2aad1083c37a8p+7i,
-0x1.7f79060d5f6e5p+7 + -0x1.d0f8a49e432b8p+5i, 0x1.7ced1ac842e4p+4 + -0x1.f646dea54892ap+5i,
0x1.6d4e5be45fddcp+6 + -0x1.aee5daf3effa3p+7i, 0x1.62fc496b6cd7bp+7 + -0x1.06081ecb0ba68p+4i,
-0x1.f9f311a1244p-2 + 0x1.e2570517fee01p+6i, 0x1.bf4e7f840dd7cp+4 + 0x1.087bb424aa77cp+5i,
0x1.d886a19a47408p+7 + -0x1.7b93d04127aa1p+6i, -0x1.30042a91d1a48p+7 + 0x1.2e93987d142bap+6i,
-0x1.49df9a72c864p+5 + -0x1.30e567441cecdp+5i, -0x1.d8447fb83e9cfp+5 + -0x1.a6a15f95eb11cp+7i,
0x1.0fe6bd5fc1704p+7 + -0x1.93cbde2b5812fp+5i, -0x1.580b6402b7906p+5 + 0x1.d55e3ba7476bcp+4i,
-0x1.3b1348415246ap+7 + -0x1.6994f832c3676p+7i, 0x1.748ff0009b22p+3 + 0x1.b555ba784d424p+6i,
-0x1.526cc38a2d7a8p+8 + -0x1.a02a4db052b02p+6i, -0x1.62e090103e3aap+6 + -0x1.377dce48c7987p+8i,
-0x1.ab43887f1f2c2p+6 + 0x1.d9bb0bbb680eep+6i, -0x1.03475e70a1d7cp+4 + -0x1.0410882c62406p+7i,
-0x1.acfa792dbb66ep+7 + 0x1.7839e6f3578f7p+6i, -0x1.20f83291dd049p+7 + -0x1.100d807de1127p+5i,
-0x1.8df13854bb9ccp+6 + -0x1.a45c9ad7b111ep+7i, -0x1.4d0b483e5ff8cp+7 + 0x1.48a590f86867bp+7i,
-0x1.dea5cff33075cp+6 + -0x1.7c7c236101e34p+3i, -0x1.2d932f6fe8a1dp+8 + -0x1.21df47692c1f7p+7i,
-0x1.348fafee85b77p+5 + -0x1.8016e53c0d5eep+6i, -0x1.7f227fa8f6398p+4 + 0x1.edf266ade308ap+7i
)
assertThat(stats:::fft(z=c(-7.34978965516479, 2.17131398089138, -6.33866196170059, -6.90592867113389,
-0.0113047513374505, -20.352482597231, -9.76366385344955, -5.44727527150623,
-38.8338073696961, 0.15679457444755, -18.7763448480381, -21.0058891942075,
13.5997666951942, -0.280288084928417, -8.00277515881392, 4.17625093823445,
-0.376076857900577, -3.75275775603125, -0.00695107187795879,
-5.31527883208898, 4.46755481166189, 0.567970088895075, 4.77685725549287,
1.35058041691026, 0.943524195068992, 0.0206541052314919, 0.183650054105491,
-0.235314799083292, -1.38385309095582, -2.75712343904144, 0.257630281242699,
2.24096849441385, -1.04750136478229, 2.08505890366643, -0.00481599812803781,
-0.730957685215846, -8.04687675352377, 2.18571428541391, -2.46497349266617,
-4.98463375278781, -3.14443959489096, -0.628341498228297, -7.28319501446031,
-0.0197259670964958, -2.75224721747325, -0.27745042994779, -5.32441259075585,
-1.44731681511964, 8.03941450650205, 4.52619909336342, -1.13572489589848,
1.06046609487547, -1.50966507161758, -4.21104955530085, -0.106963563535257,
-2.6545189659242, -2.22821073471975, -3.67861943297574, -2.61085488970969,
0.495412455258236, -1.30436585238751, 0.659579826155498, 4.12704271104832,
2.96550521202127, -1.67879100596426, 2.39663867976626, -2.39964185387181,
0.686602809525303, -0.776890900502591, -1.67994324142599, -0.460219841282026,
-3.43678232780962, 1.7906595637447, 4.29068451298771, -2.54834650675063,
-1.66900811128708, -0.782989626585176, -3.53466639036002, -0.894132175472473,
1.12535233267424, -6.21884921079606, 0.839742732224532, -2.28638764333812,
-0.00370441092171243, 0.466792594316811, 0.859492058091605, 0.604127788421366,
-3.7622941542445, 0.620993977812953, -5.245543816004, -0.918340522953523,
-2.94697901456518, 0.000592633183947139, -0.935270855558396,
0.60386257696295, -0.904894438925587, 6.16834270538408, -0.649751912879373,
5.81998619274346, 5.19729405995881, -9.31389594112096, -0.574065575386835,
-8.6195892427404, -1.779583056253, -4.6708019406065, -8.05943646414585,
2.8910730625913, -9.04249661590512, 9.78789950105741, 13.4809370918883,
-5.38208806158573, 1.74683554470233, 9.34792752558025, -3.44625370202322,
4.58897248700183, -3.93334237192196, 1.35559345605078, -4.80434430436266,
-0.223213598332833, 7.46106253079644, -0.616757069948777, 4.68279829108154,
2.4882897961141, -3.97857831089891, -1.51552162775457, -0.867228101921097,
-7.27604562654879, -0.0341172148382841, -6.27202780781203, -0.692558712030191,
-2.28192543162662, 1.08339182563154, 5.14936751065038, -1.29199351126187,
4.40885926514266, -0.323033813147648, -1.14683671565304, 0.00494164100877328,
-0.345588798149673, 5.49601390389117, -1.43812817977208, 6.48402296559972,
-4.8957058664165, -1.45324950414464, -0.63567485244181, -7.3677156267252,
0.00398276629968695, 0.5945571322703, 1.26482460097525, -1.31384613723359,
5.59224653372849, 1.9633330449091, -1.59828764929225, 0.207662580762002,
-5.16730399697917, 1.40277377720045, 1.63569870564092, 0.984923002589916,
-0.0345654331822847, 4.82171082770418, 2.14082874533581, -2.82810634496359,
0.0797090159836944, -6.36506311456573, -1.51775884023329, -6.97338760941422,
-8.25056343915563, 0.0850679993313883, -11.065177953407, -9.69840265410653,
0.411076150231953, -6.80382140174278, -7.8251439971141, -1.33460095067788,
-7.25812194000699, -11.9269517004491, -3.11298601125692, -13.9222416991964,
0.115569748835781, -1.16191850821664, -6.69521433961008, 2.0193953309914,
1.12256334578426, -4.3995808958654, -0.394102922378977, -0.25469452729788,
1.15496206123532, -0.00116498962750556, -3.08731954323099, -5.17494351073813,
-0.894614127899894, -2.73996825671277, 0.733046233908727, -0.115818961914661,
-0.0420374490258803, 0.368825304420055, 0.0121752611414375, 0.0806947285912734,
-5.98872842081419, 1.47527873873802, -4.75194980210009, 1.01427846110915,
1.65484218109453, -1.32263185270982, 1.56576271007941, 1.45453265176124,
-0.0376190055337404, 3.48522800785135, -2.44970812455326, 8.59570374052921,
-1.7828472080354, 5.55564858973805, 7.67348357883987, 2.29752167125936,
6.55237286590372, -0.00296221420787119, 3.96035173602675, -1.16732453604894,
-7.21310441898552, -1.4790778010996, -7.96924496798519, -3.20193809282299,
-5.62690176230733, -9.95183222270227, 0.0137030014356907, -9.98641619763897,
0.384718437168334, 13.7026359501345, -6.37971937639048, 10.2563471001967,
11.1919375653217, -1.17079608474429, 4.51121531157537, -10.9721401706896,
-8.1247540768237, -2.3638522620174, -23.9315042490372, 10.1180259729374,
-20.6496800965057, 8.91162981044919, 1.34997554114717, -3.05237654022552,
3.75676560241452, 3.59344536359033, -0.417044094109139, -0.469241799972831,
-1.2528375332018, -4.61438966650404, 1.04014505007012, 0.288824724360609,
-1.60081675731785, 0.863398590444596, 2.08273602878312, -0.173583166646783,
-0.339521867391123, -0.0508715867783883, -2.80638451843493, -1.0943685509487,
0.225374746905434, -1.48151776373873, 2.19671482355452, 5.08776045709935,
-2.63269063976141, 11.6391735293497, -0.56835593952689, -1.83999656241524,
5.0898874899154, -17.4445069131666, -6.56195033343605, -4.86762449986659,
-24.3011443265718, -1.81897212866172, -19.5879142374202, -15.0441434326082,
1.17922387141451, -12.7409442194373, 1.36251141672002, 1.57663858648609,
-8.85667209146122, -1.18151413986187, 1.73955989571161, -8.22794715524901,
-1.25895718826798, -5.8613112171518, -3.34234884520339, -0.345911229857183,
-0.98423261673054, -1.98713381340123, 0.641010119415937, -0.0359206397422201,
1.51120206066676, 0.427293949858943, 3.65481126100239, 2.09632370582427,
0.694436276210105, 1.98056690105038, 0.884131282263325, 3.14924407671228,
0.0565374429089586, -0.841223288591555, 2.79501468473361, -2.7983474869864,
-2.17200181403754, -0.298048851289791, -3.88399898907978, -4.80281744801249,
-1.53925078055171, -8.66988070684015, -0.298932233075103, -8.80884286122301,
-9.00620801486017, 0.461296454021319, -1.38300751624957, -12.1132821608429,
-14.8389361415066, -2.43494501098662, -15.8353791894072, -0.462127533418109,
-4.56239112373678, -5.25935743379802, -0.333085721139147, -5.12799795125851,
-5.27481421775689, 5.77346738351044, -8.36015827092282, 0.468547775290383,
7.59732950183313, -4.35429131990282, 3.2591436400886, -3.67705226015189,
-4.11711028755469, 4.776995952489, -6.56208732892593, 1.07337803203839,
-0.499555951199867, -16.7904450895811, 8.20161829557333, -15.3903869964331,
-20.627865725261, 6.40125012298495, -22.4184404515219, -11.9741943983031,
-0.689211472799639, -18.9179675106862, -0.512673410808726, -10.8717351438712,
-13.2706937016591, 15.0231275275149, -15.7076158380064, -2.67007637923131,
16.1496413496614, -12.2105846653788, 8.17803995409392, 0.387235325306791,
-21.8614663059986, 3.66758625302468, -21.3696256945814, -0.330196070462789,
1.22247545570553, -21.7016544647715, 2.28204308462443, -5.00575484181943,
-6.83185450249509, -8.29782708471046, -1.275340741865, 1.35302695231738,
-0.0374731408322102, 3.67346046648786, 2.63868956287966, -0.626066680742508,
0.649605596637525, 1.77586090496691, 0.929314960063292, -0.361683203842528,
-0.211686035629108, 0.865714362684181, 0.168471650065465, -1.82338323892656,
-1.46730171850371, -0.463205953430522, -1.90885982276408, 0.585263375051362,
1.68078969687008, -0.545192168131676, 5.82161373247637, 0.418524510398686,
2.21619583999717, 4.61503873055521, -5.50122040829837, -1.866638831164,
-2.70233147729082, -13.0036650793718, -0.400038238219057, -14.0560641590161,
-6.80648398760882, -1.84303526143468, -7.03448628627229, -6.47975240993989,
1.53864026582815, -7.44769860247011, 4.22555558002357, 1.40813071000905,
-4.02020097594931, 6.23521048752929, -7.40646973857678, 2.33205204287526,
9.27130512156855, -2.17588422422781, 10.5646159340965, -4.63860587364421,
4.20603790265988, 3.5167785740308, -7.45411159155492, 2.83301664928991,
-2.91728060352519, -3.6847874330314, 0.45597659388152, -0.568493786722375,
-2.64024994626372, -2.53084542213233, -0.465534070634776, -0.0840144027446836,
0.0597846422675136, -0.934978362547354, -0.893698181120751, 0.693260943420861,
0.0685214780903158, -0.991077540226312, 0.180881581917324, -0.36606434350682,
-0.0444488131547632, 0.0713250028814436, -0.761457538562641,
-2.04755033141203, -0.997601972501108, 2.1298837213424, -6.15727854024994,
0.132191092961796, -12.4546790658587, -2.60995692678617, -3.21881223017067,
-6.67707365679882, 2.06663976269597, 3.3710488009292, 1.57344545561532,
12.1329109737918, -0.982314279088975, -4.05603324351742, 4.56699555321954,
-3.51072795314121, 0.263379460137528, 1.12427806156684, -5.16117511939298,
0.798551598275607, -1.35188140528664, -3.95663616805659, -2.89141792899761,
-4.30786753752407, -3.06895256017837, 0.315066087919452, -2.94738864627794,
-0.960482246242672, -10.084437136255, 0.79280060324264, -11.0026726452933,
-15.172935402954, -2.39813889661846, -18.0114734331588))
, identicalTo( expected, tol = 1e-6 ) ) |
KPN <- function( level ) {
switch( level,
{
n = c(0.0000000000000000e+000)
w = c(1.0000000000000000e+000)
},
{
n = c(0.0000000000000000e+000, 1.7320508075688772e+000)
w = c(6.6666666666666663e-001, 1.6666666666666666e-001)
},
{
n = c(0.0000000000000000e+000, 1.7320508075688772e+000)
w = c(6.6666666666666674e-001, 1.6666666666666666e-001)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.7320508075688772e+000, 4.1849560176727323e+000)
w = c(4.5874486825749189e-001, 1.3137860698313561e-001, 1.3855327472974924e-001, 6.9568415836913987e-004)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.7320508075688772e+000, 2.8612795760570582e+000, 4.1849560176727323e+000)
w = c(2.5396825396825407e-001, 2.7007432957793776e-001, 9.4850948509485125e-002, 7.9963254708935293e-003, 9.4269457556517470e-005)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.7320508075688772e+000, 2.8612795760570582e+000, 4.1849560176727323e+000)
w = c(2.5396825396825429e-001, 2.7007432957793776e-001, 9.4850948509485070e-002, 7.9963254708935293e-003, 9.4269457556517551e-005)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.7320508075688772e+000, 2.8612795760570582e+000, 4.1849560176727323e+000)
w = c(2.5396825396825418e-001, 2.7007432957793781e-001, 9.4850948509485014e-002, 7.9963254708935311e-003, 9.4269457556517592e-005)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.7320508075688772e+000, 2.8612795760570582e+000, 4.1849560176727323e+000)
w = c(2.5396825396825418e-001, 2.7007432957793781e-001, 9.4850948509485042e-002, 7.9963254708935276e-003, 9.4269457556517375e-005)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(2.6692223033505302e-001, 2.5456123204171222e-001, 1.4192654826449365e-002, 8.8681002152028010e-002, 1.9656770938777492e-003, 7.0334802378279075e-003, 1.0563783615416941e-004, -8.2049207541509217e-007, 2.1136499505424257e-008)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(3.0346719985420623e-001, 2.0832499164960877e-001, 6.1151730125247716e-002, 6.4096054686807610e-002, 1.8085234254798462e-002, -6.3372247933737571e-003, 2.8848804365067559e-003, 6.0123369459847997e-005, 6.0948087314689840e-007, 8.6296846022298632e-010)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(3.0346719985420623e-001, 2.0832499164960872e-001, 6.1151730125247709e-002, 6.4096054686807541e-002, 1.8085234254798459e-002, -6.3372247933737545e-003, 2.8848804365067555e-003, 6.0123369459847922e-005, 6.0948087314689830e-007, 8.6296846022298839e-010)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(3.0346719985420623e-001, 2.0832499164960872e-001, 6.1151730125247716e-002, 6.4096054686807624e-002, 1.8085234254798466e-002, -6.3372247933737545e-003, 2.8848804365067559e-003, 6.0123369459847841e-005, 6.0948087314689830e-007, 8.6296846022298963e-010)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(3.0346719985420600e-001, 2.0832499164960883e-001, 6.1151730125247730e-002, 6.4096054686807638e-002, 1.8085234254798459e-002, -6.3372247933737580e-003, 2.8848804365067555e-003, 6.0123369459847868e-005, 6.0948087314689830e-007, 8.6296846022298756e-010)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(3.0346719985420617e-001, 2.0832499164960874e-001, 6.1151730125247702e-002, 6.4096054686807596e-002, 1.8085234254798459e-002, -6.3372247933737563e-003, 2.8848804365067555e-003, 6.0123369459847936e-005, 6.0948087314689851e-007, 8.6296846022298322e-010)
},
{
n = c(0.0000000000000000e+000, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000)
w = c(3.0346719985420612e-001, 2.0832499164960874e-001, 6.1151730125247723e-002, 6.4096054686807652e-002, 1.8085234254798459e-002, -6.3372247933737597e-003, 2.8848804365067563e-003, 6.0123369459848091e-005, 6.0948087314689851e-007, 8.6296846022298983e-010)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(2.5890005324151566e-001, 2.8128101540033167e-002, 1.9968863511734550e-001, 6.5417392836092561e-002, 6.1718532565867179e-002, 1.7608475581318002e-003, 1.6592492698936010e-002, -5.5610063068358157e-003, 2.7298430467334002e-003, 1.5044205390914219e-005, 5.9474961163931621e-005, 6.1435843232617913e-007, 7.9298267864869338e-010, 5.1158053105504208e-012, -1.4840835740298868e-013, 1.2618464280815118e-015)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(1.3911022236338039e-001, 1.0387687125574284e-001, 1.7607598741571459e-001, 7.7443602746299481e-002, 5.4677556143463042e-002, 7.3530110204955076e-003, 1.1529247065398790e-002, -2.7712189007789243e-003, 2.1202259559596325e-003, 8.3236045295766745e-005, 5.5691158981081479e-005, 6.9086261179113738e-007, -1.3486017348542930e-008, 1.5542195992782658e-009, -1.9341305000880955e-011, 2.6640625166231651e-013, -9.9313913286822465e-016)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806921377e-004, 1.9176011588804434e-001, 1.4807083115521585e-001, 9.2364726716986353e-002, 4.5273685465150391e-002, 1.5673473751851151e-002, 3.1554462691875513e-003, 2.3113452403522071e-003, 8.1895392750226735e-004, 2.7524214116785131e-004, 3.5729348198975332e-005, 2.7342206801187888e-006, 2.4676421345798140e-007, 2.1394194479561062e-008, 4.6011760348655917e-010, 3.0972223576062995e-012, 5.4500412650638128e-015, 1.0541326582334014e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806921377e-004, 1.9176011588804437e-001, 1.4807083115521585e-001, 9.2364726716986353e-002, 4.5273685465150523e-002, 1.5673473751851151e-002, 3.1554462691875604e-003, 2.3113452403522050e-003, 8.1895392750226670e-004, 2.7524214116785131e-004, 3.5729348198975447e-005, 2.7342206801187884e-006, 2.4676421345798140e-007, 2.1394194479561056e-008, 4.6011760348656077e-010, 3.0972223576063011e-012, 5.4500412650637663e-015, 1.0541326582337958e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806925551e-004, 1.9176011588804440e-001, 1.4807083115521585e-001, 9.2364726716986298e-002, 4.5273685465150537e-002, 1.5673473751851155e-002, 3.1554462691875573e-003, 2.3113452403522080e-003, 8.1895392750226724e-004, 2.7524214116785137e-004, 3.5729348198975352e-005, 2.7342206801187888e-006, 2.4676421345798124e-007, 2.1394194479561056e-008, 4.6011760348656144e-010, 3.0972223576062963e-012, 5.4500412650638365e-015, 1.0541326582335402e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806913744e-004, 1.9176011588804429e-001, 1.4807083115521594e-001, 9.2364726716986312e-002, 4.5273685465150391e-002, 1.5673473751851151e-002, 3.1554462691875565e-003, 2.3113452403522089e-003, 8.1895392750226670e-004, 2.7524214116785142e-004, 3.5729348198975285e-005, 2.7342206801187888e-006, 2.4676421345798119e-007, 2.1394194479561059e-008, 4.6011760348656594e-010, 3.0972223576062950e-012, 5.4500412650638696e-015, 1.0541326582332041e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806903368e-004, 1.9176011588804448e-001, 1.4807083115521574e-001, 9.2364726716986423e-002, 4.5273685465150516e-002, 1.5673473751851161e-002, 3.1554462691875543e-003, 2.3113452403522063e-003, 8.1895392750226713e-004, 2.7524214116785164e-004, 3.5729348198975319e-005, 2.7342206801187905e-006, 2.4676421345798151e-007, 2.1394194479561082e-008, 4.6011760348656005e-010, 3.0972223576063043e-012, 5.4500412650637592e-015, 1.0541326582339926e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806913755e-004, 1.9176011588804442e-001, 1.4807083115521577e-001, 9.2364726716986381e-002, 4.5273685465150468e-002, 1.5673473751851155e-002, 3.1554462691875560e-003, 2.3113452403522045e-003, 8.1895392750226572e-004, 2.7524214116785158e-004, 3.5729348198975298e-005, 2.7342206801187892e-006, 2.4676421345798129e-007, 2.1394194479561072e-008, 4.6011760348656103e-010, 3.0972223576062963e-012, 5.4500412650638207e-015, 1.0541326582338368e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806914438e-004, 1.9176011588804442e-001, 1.4807083115521577e-001, 9.2364726716986340e-002, 4.5273685465150509e-002, 1.5673473751851155e-002, 3.1554462691875586e-003, 2.3113452403522058e-003, 8.1895392750226551e-004, 2.7524214116785142e-004, 3.5729348198975386e-005, 2.7342206801187884e-006, 2.4676421345798082e-007, 2.1394194479561059e-008, 4.6011760348656382e-010, 3.0972223576062942e-012, 5.4500412650638381e-015, 1.0541326582336941e-018)
},
{
n = c(0.0000000000000000e+000, 2.4899229757996061e-001, 7.4109534999454085e-001, 1.2304236340273060e+000, 1.7320508075688772e+000, 2.2336260616769419e+000, 2.5960831150492023e+000, 2.8612795760570582e+000, 3.2053337944991944e+000, 3.6353185190372783e+000, 4.1849560176727323e+000, 4.7364330859522967e+000, 5.1870160399136562e+000, 5.6981777684881099e+000, 6.3633944943363696e+000, 7.1221067008046166e+000, 7.9807717985905606e+000, 9.0169397898903032e+000)
w = c(5.1489450806919989e-004, 1.9176011588804437e-001, 1.4807083115521580e-001, 9.2364726716986395e-002, 4.5273685465150426e-002, 1.5673473751851158e-002, 3.1554462691875539e-003, 2.3113452403522054e-003, 8.1895392750226681e-004, 2.7524214116785142e-004, 3.5729348198975292e-005, 2.7342206801187884e-006, 2.4676421345798108e-007, 2.1394194479561056e-008, 4.6011760348655901e-010, 3.0972223576062975e-012, 5.4500412650638412e-015, 1.0541326582337527e-018)
}
)
return( list( "nodes" = n,
"weights" = w ) )
} |
library(data.table)
x1 = data.table(id = c(1L, 1L, 2L, 3L, NA_integer_),
t = c(1L, 2L, 1L, 2L, NA_integer_),
x = 11:15)
y1 = data.table(id = c(1,2, 4),
y = c(11L, 15L, 16))
x2 = data.table(id = c(1, 4, 2, 3, NA),
t = c(1L, 2L, 1L, 2L, NA_integer_),
x = c(16, 12, NA, NA, 15))
y2 = data.table(id = c(1, 2, 5, 6, 3),
yd = c(1, 2, 5, 6, 3),
y = c(11L, 15L, 20L, 13L, 10L),
x = c(16:20))
y3 <- data.table(id = c("c","b", "c", "a"),
y = c(11L, 15L, 18L, 20L))
x3 <- data.table(id=c("c","b", "d"),
v=8:10,
foo=c(4,2, 7))
x4 = data.table(id1 = c(1, 1, 2, 3, 3),
id2 = c(1, 1, 2, 3, 4),
t = c(1L, 2L, 1L, 2L, NA_integer_),
x = c(16, 12, NA, NA, 15))
y4 = data.table(id = c(1, 2, 5, 6, 3),
id2 = c(1, 1, 2, 3, 4),
y = c(11L, 15L, 20L, 13L, 10L),
x = c(16:20))
test_that("correct frequencies", {
b <- base::table(y4$id2)
b <- as.numeric(b)
j <- freq_table(y4, "id2")
j <- j[ id2 != "total"
][, n]
expect_equal(b, j)
})
test_that("correct totals", {
tr <- nrow(y4)
j <- freq_table(y4, "id2")
j <- j[ id2 == "total"
][, n]
expect_equal(tr, j)
}) |
summary.nb <- function(object, coords=NULL, longlat=NULL, scale=1, ...) {
nb <- object
if (!inherits(nb, "nb")) stop("Not a neighbours list")
c.nb <- card(nb)
n.nb <- length(nb)
regids <- attr(nb, "region.id")
if(is.null(regids)) regids <- as.character(1:n.nb)
print.nb(object)
cat("Link number distribution:\n")
print(table(c.nb, deparse.level=0))
if(any(c.nb > 0)) {
min.nb <- min(c.nb[c.nb > 0])
cat(length(c.nb[c.nb == min.nb]), " least connected region",
ifelse(length(c.nb[c.nb == min.nb]) < 2L, "", "s"), ":\n",
paste(regids[which(c.nb == min.nb)], collapse=" "), " with ",
min.nb, " link", ifelse(min.nb < 2L, "", "s"), "\n", sep="")
max.nb <- max(c.nb)
cat(length(c.nb[c.nb == max.nb]), " most connected region",
ifelse(length(c.nb[c.nb == max.nb]) < 2L, "", "s"), ":\n",
paste(regids[which(c.nb == max.nb)], collapse=" "), " with ",
max.nb, " link", ifelse(max.nb < 2L, "", "s"), "\n", sep="")
}
if(!is.null(coords)) {
dlist <- nbdists(nb, coords, longlat=longlat)
cat("Summary of link distances:\n")
print(summary(unlist(dlist)))
stem(unlist(dlist), scale=scale)
}
}
print.nb <- function(x, ...) {
nb <- x
if (!inherits(nb, "nb")) stop("Not a neighbours list")
c.nb <- card(nb)
n.nb <- length(nb)
regids <- attr(nb, "region.id")
if(is.null(regids)) regids <- as.character(1:n.nb)
cat("Neighbour list object:\n")
cat("Number of regions:", n.nb, "\n")
cat("Number of nonzero links:", sum(c.nb), "\n")
cat("Percentage nonzero weights:", (100*sum(c.nb))/(n.nb^2), "\n")
cat("Average number of links:", mean(c.nb), "\n")
if(any(c.nb == 0)) cat(length(c.nb[c.nb == 0]), " region",
ifelse(length(c.nb[c.nb == 0]) < 2L, "", "s"), " with no links:\n",
paste(strwrap(paste(regids[which(c.nb == 0)], collapse=" ")),
collapse="\n"), "\n", sep="")
res <- is.symmetric.nb(nb, verbose=FALSE)
if (!res) cat("Non-symmetric neighbours list\n")
invisible(x)
}
summary.listw <- function(object, coords=NULL, longlat=FALSE,
zero.policy=NULL, scale=1, ...) {
if (is.null(zero.policy))
zero.policy <- get("zeroPolicy", envir = .spdepOptions)
stopifnot(is.logical(zero.policy))
if (any(card(object$neighbours) == 0) && !zero.policy)
stop("regions with no neighbours found, use zero.policy=TRUE")
cat("Characteristics of weights list object:\n")
summary(object$neighbours, coords=coords, longlat=longlat,
scale=scale, ...)
style <- object$style
cat(paste("\nWeights style:", style, "\n"))
if (is.na(style)) style = "NA"
cat("Weights constants summary:\n")
print(data.frame(rbind(unlist(spweights.constants(object,
zero.policy=zero.policy))[c(1, 5:8)]), row.names=style))
}
print.listw <- function(x, zero.policy=NULL, ...) {
if (is.null(zero.policy))
zero.policy <- get("zeroPolicy", envir = .spdepOptions)
stopifnot(is.logical(zero.policy))
if (any(card(x$neighbours) == 0) && !zero.policy)
stop("regions with no neighbours found, use zero.policy=TRUE")
cat("Characteristics of weights list object:\n")
print.nb(x$neighbours, ...)
style <- x$style
cat(paste("\nWeights style:", style, "\n"))
if (is.na(style)) style = "NA"
cat("Weights constants summary:\n")
df <- data.frame(rbind(unlist(spweights.constants(x,
zero.policy=zero.policy))[c(1, 5:8)]), row.names=style)
print(df)
invisible(x)
} |
file_names <- list(
r = slurmR::snames("r", tmp_path = "[tmp_path]", job_name = "[job-name]"),
sh = slurmR::snames("sh", tmp_path = "[tmp_path]", job_name = "[job-name]"),
out = slurmR::snames("out", tmp_path = "[tmp_path]", job_name = "[job-name]"),
rds = slurmR::snames("rds", tmp_path = "[tmp_path]", job_name = "[job-name]")
)
file_names <- lapply(
file_names, gsub, pattern = ".+/(?=[0-9])", replacement = "",
perl = TRUE
)
file_names <- lapply(file_names, function(f) paste0("`", f, "`")) |
escapeContent <- function(content_s_1, escapeBraces_b_1 = FALSE) {
patchArobas <- function(x_s) {
if (stringr::str_count(x_s, '@') == 0L) return(x_s)
paste(strsplit(x_s, "@@|@")[[1]], collapse = '@@', sep = '@@')
}
patchPercent <- function(x_s) {
if (stringr::str_count(x_s, '%') == 0L) return(x_s)
paste(strsplit(x_s, "\\\\%|%")[[1]], collapse = '\\%', sep = '\\%')
}
patchOB <- function(x_s) {
if (stringr::str_count(x_s, '\\{') == 0L) return(x_s)
paste(strsplit(x_s, "\\\\\\{|\\{")[[1]], collapse = '\\{', sep = '\\{')
}
patchCB <- function(x_s) {
if (stringr::str_count(x_s, '\\}') == 0L) return(x_s)
paste(strsplit(x_s, "\\\\\\}|\\}")[[1]], collapse = '\\}', sep = '\\}')
}
s <- paste0(content_s_1, '\t')
s <- patchArobas(s)
s <- patchPercent(s)
if (!escapeBraces_b_1) return(substring(s, 1L, nchar(s) - 1L))
s <- patchOB(s)
s <- patchCB(s)
substring(s, 1L, nchar(s) - 1L)
} |
dist.bin.3col<-function(dist.bin,obj.name=NULL)
{
dist.3col<-function(dist)
{
dist=as.matrix(dist)
rowname=rownames(dist)
colname=colnames(dist)
rown=row(dist)
coln=col(dist)
dist.v=as.vector(stats::as.dist(dist))
rown.v=as.vector(stats::as.dist(rown))
coln.v=as.vector(stats::as.dist(coln))
res=data.frame(name1=rowname[rown.v],name2=colname[coln.v],dis=dist.v)
res
}
dist.3col=cbind(dist.3col(dist.bin[[1]]),sapply(2:length(dist.bin),function(i){dist.3col(dist.bin[[i]])[,3]}))
colnames(dist.3col)[3:ncol(dist.3col)]<-paste0(paste(c(obj.name,"bin"),collapse = "."),1:length(dist.bin))
dist.3col
} |
wDC <- function(DCf = 100, rw = 200, a = 0.75, b = 0.75) {
Qf <- 800 * exp(-DCf / 400)
Qs <- a * Qf + b * (3.94 * rw)
DCs <- 400 * log(800 / Qs)
DCs <- ifelse(DCs < 15, 15, DCs)
return(DCs)
} |
test_that("simple ratio", {
expect_equal(nom_ratio(2), "two in one")
expect_equal(nom_ratio(0.5), "one in two")
expect_equal(nom_ratio(1000), "one thousand in one")
})
test_that("ratio vector", {
expect_equal(
nom_ratio(c(2, 0.25, .000001), "to"),
c("two to one",
"one to four",
"one to one million")
)
})
test_that("ratio with max_n", {
expect_equal(nom_ratio(2, max_n = 10), "two in one")
expect_equal(nom_ratio(20, max_n = 10), "20 in one")
expect_equal(nom_ratio(c(2, 20), max_n = 10), c("two in one", "20 in one"))
expect_equal(nom_ratio(c(2, 20), max_n = -1), c("2 in 1", "20 in 1"))
expect_equal(
nom_ratio(c(20, 20), max_n = c(10, 100)), c("20 in one", "twenty in one")
)
})
test_that("negative ratio", {
expect_equal(nom_ratio(-2), "negative two in one")
expect_equal(
nom_card(-525600), "negative five hundred twenty-five thousand six hundred"
)
expect_equal(
nom_ratio(-100000000, sep = "to"), "negative one hundred million to one"
)
expect_equal(nom_ratio(-2, negative = "minus"), "minus two in one")
expect_equal(
nom_ratio(c(-2, -0.5), negative = c("negative", "minus")),
c("negative two in one", "minus one in two")
)
})
test_that("ratio with fracture ...", {
expect_equal(nom_ratio(1/2, base_10 = TRUE), "five in ten")
expect_equal(
nom_ratio(c(0, 1/2, 3/4), common_denom = TRUE),
c("zero in four",
"two in four",
"three in four")
)
expect_equal(nom_ratio(27/50, max_denom = 25), "seven in thirteen")
expect_equal(nom_ratio(15/100, sep = "to", max_denom = 15), "one to seven")
})
test_that("early return", {
expect_equal(nom_ratio(numeric(0)), character(0))
})
test_that("errors", {
expect_error(nom_ratio(character(1)))
expect_error(nom_ratio(numeric(1), negative = numeric(1)))
expect_error(nom_ratio(numeric(1), negative = character(0)))
expect_error(nom_ratio(numeric(1), negative = character(2)))
expect_error(nom_ratio(numeric(1), max_n = numeric(0)))
expect_error(nom_ratio(numeric(1), max_n = character(1)))
}) |
rita_sample <- function(data,
from = NULL,
to = NULL,
states = NULL,
facilities = NULL
) {
states <- states %||% unique(data$facility_state)
facilities <- facilities %||% unique(subset(data, facility_state %in% states)$facility)
validate_recent(data, from, to , states, facilities)
get_sample(data, from, to, states, facilities)
}
get_sample <- function(data, from, to, states, facilities) {
dt <- dplyr::filter(
data,
viral_load_requested %in% c("Yes", "yes", "true", TRUE),
recency_interpretation == "Recent",
facility_state %in% states,
facility %in% facilities
)
if (!is.null(from)) {
dt <- dplyr::filter(
dt,
date_sample_collected >= lubridate::ymd(from)
)
}
if(!is.null(to)) {
dt <- dplyr::filter(
dt, date_sample_collected <= lubridate::ymd(to)
)
}
return(dt)
}
utils::globalVariables(
c("recency_interpretation", "date_sample_collected", "viral_load_requested", "facility_state")
) |
predict.pcrfit <- function(
object,
newdata,
which = c("y", "x"),
interval = c("none", "confidence", "prediction"),
level = 0.95,
...
)
{
which <- match.arg(which)
interval <- match.arg(interval)
if (missing(newdata)) newDATA <- object$DATA
else {
if (which == "x") newDATA <- cbind(rep(1, nrow(newdata)), newdata)
else newDATA <- newdata
}
modNAME <- object$MODEL$name
if (modNAME == "spl3") {
YVEC <- object$DATA[, 2]
if (which == "y") PRED <- object$MODEL$fct(newDATA[, 1], coef(object), YVEC)
else PRED <- object$MODEL$inv(newDATA[, 2], coef(object), YVEC)
return(PRED)
}
if (which == "y") PRED <- object$MODEL$fct(newDATA[, 1], coef(object))
else PRED <- object$MODEL$inv(newDATA[, 2], coef(object))
if (modNAME %in% c("mak2", "mak2i", "mak3", "mak3i", "cm3")) return(PRED)
if (which == "y") DERIVS <- lapply(object$MODEL$parnames, function(x) D(object$MODEL$expr.grad, x))
else DERIVS <- lapply(object$MODEL$parnames, function(x) D(object$MODEL$inv.grad, x))
if (inherits(DERIVS, "try-error")) return(PRED)
GRAD <- NULL
resMAT <- NULL
if (!identical(interval, "none")) {
TQUAN <- qt(1 - (1 - level)/2, df.residual(object))
}
for (i in 1:nrow(newDATA)) {
tempDATA <- data.frame(newDATA[i, , drop = FALSE], t(coef(object)))
dfEVAL <- as.numeric(lapply(DERIVS, function(x) eval(x, envir = tempDATA)))
GRAD <- rbind(GRAD, as.numeric(dfEVAL))
VAR <- dfEVAL %*% vcov(object) %*% dfEVAL
if (interval == "confidence") {
UPPER <- PRED[i] + TQUAN * sqrt(VAR)
LOWER <- PRED[i] - TQUAN * sqrt(VAR)
COLNAMES <- c("Prediction", "SE", "Lower", "Upper")
}
if (interval == "prediction") {
UPPER <- PRED[i] + TQUAN * sqrt(VAR + resVar(object))
LOWER <- PRED[i] - TQUAN * sqrt(VAR + resVar(object))
COLNAMES <- c("Prediction", "SE", "Lower", "Upper")
}
if (interval == "none") {
UPPER <- NULL
LOWER <- NULL
VAR <- NULL
COLNAMES <- c("Prediction")
}
resMAT <- rbind(resMAT, c(PRED[i], VAR, LOWER, UPPER))
}
resMAT <- as.data.frame(resMAT)
colnames(resMAT) <- COLNAMES
attr(resMAT, "gradient") <- as.matrix(GRAD)
return(resMAT)
} |
sbrier_ltrc <- function(obj, id = NULL, pred, type = c("IBS","BS")){
if(!inherits(obj, "Surv"))
stop("obj is not of class Surv")
if (attr(obj, "type") != "counting")
stop("only dataset with left-truncated and right-censored (pseudo-subject) observations allowed")
n <- nrow(obj)
if (!is.null(id)){
if (n != length(id)) stop("The length of id is different from the Surv object!")
} else {
id <- 1:n
}
id.sub = unique(id)
n.sub = length(id.sub)
obj <- as.data.frame(as.matrix(obj))
if (n == n.sub){
data_sbrier = obj
data_sbrier$id = 1:n
} else {
data_sbrier <- data.frame(matrix(0, nrow = n.sub, ncol = 3))
names(data_sbrier) <- c("start", "stop", "status")
data_sbrier$id <- id.sub
for (ii in 1:n.sub){
data_sbrier[ii, ]$start = min(obj[id == id.sub[ii], ]$start)
data_sbrier[ii, ]$stop = max(obj[id == id.sub[ii], ]$stop)
data_sbrier[ii, ]$status = sum(obj[id == id.sub[ii], ]$status)
}
}
if (type[1] == "IBS"){
ret <- sapply(1:n.sub, function(Ni) .ibsfunc(Ni = Ni, data_sbrier = data_sbrier, pred = pred))
ret <- mean(ret)
names(ret) = "Integrated Brier score"
} else if (type[1] == "BS"){
tpnt <- pred$survival.times[pred$survival.times <= min(pred$survival.tau)]
bsres <- sapply(1:n.sub, function(Ni) .bsfunc(Ni = Ni, data_sbrier = data_sbrier, pred = pred, tpnt = tpnt))
bsres <- rowMeans(bsres)
ret <- data.frame(matrix(0, ncol = 2, nrow = length(tpnt)))
colnames(ret) <- c("Time", "BScore")
ret$Time <- tpnt
ret$BScore <- bsres
} else {
stop("type can only be 'IBS' or 'BS'")
}
return(ret)
}
.ibsfunc <- function(Ni, data_sbrier, pred){
id_uniq <- unique(data_sbrier$id)
tpnt = pred$survival.times[pred$survival.times <= pred$survival.tau[Ni]]
tlen = length(tpnt)
if (class(pred$survival.probs)[1] == "matrix"){
Shat = pred$survival.probs[1:tlen, Ni]
} else if(class(pred$survival.probs)[1] == "list"){
Shat = pred$survival.probs[[Ni]][1:tlen]
}
hatcdist <- prodlim::prodlim(Surv(start, stop, status) ~ 1, data = data_sbrier, reverse = TRUE)
Ttildei <- data_sbrier[data_sbrier$id == id_uniq[Ni], ]$stop
Tleft = data_sbrier[data_sbrier$id == id_uniq[Ni], ]$start
csurv_adj = predictProb(hatcdist, time.eval = Tleft)
if (is.na(csurv_adj)) stop("reverse Kaplan-Meier estimate at the left-truncateion point is NA! ")
csurv_obs <- predictProb(hatcdist, time.eval = Ttildei) / csurv_adj
csurv_obs[csurv_adj == 0] <- Inf
csurv_obs[csurv_obs == 0] <- Inf
csurv_t <- predictProb(hatcdist, time.eval = tpnt[tpnt < Ttildei]) / csurv_adj
csurv_t[is.na(csurv_t)] <- min(csurv_t, na.rm = TRUE)
csurv_t[csurv_t == 0] <- Inf
csurv <- c(1/csurv_t, rep(1 / csurv_obs, sum(tpnt >= Ttildei)))
Indicator_t <- as.integer(tpnt < Ttildei)
Indicator_t[Indicator_t == 0] = as.integer(data_sbrier[data_sbrier$id == id_uniq[Ni],]$status == 1)
fibs_itg = (as.integer(tpnt < Ttildei) - Shat) ^ 2 * csurv * Indicator_t
ibs = diff(tpnt) %*% (fibs_itg[-length(fibs_itg)] + fibs_itg[-1]) / 2
ibs = ibs / diff(range(tpnt))
ibs
}
.bsfunc <- function(Ni, data_sbrier, pred, tpnt){
id_uniq <- unique(data_sbrier$id)
tlen = length(tpnt)
if (class(pred$survival.probs)[1] == "matrix"){
Shat = pred$survival.probs[1:tlen, Ni]
} else if(class(pred$survival.probs)[1] == "list"){
Shat = pred$survival.probs[[Ni]][1:tlen]
}
hatcdist <- prodlim::prodlim(Surv(start, stop, status) ~ 1, data = data_sbrier, reverse = TRUE)
Ttildei <- data_sbrier[data_sbrier$id == id_uniq[Ni], ]$stop
Tleft = data_sbrier[data_sbrier$id == id_uniq[Ni], ]$start
csurv_adj = predictProb(hatcdist, time.eval = Tleft)
if (is.na(csurv_adj)) stop("reverse Kaplan-Meier estimate at the left-truncateion point is NA! ")
csurv_obs <- predictProb(hatcdist, time.eval = Ttildei) / csurv_adj
csurv_obs[csurv_adj == 0] <- Inf
csurv_obs[csurv_obs == 0] <- Inf
csurv_t <- predictProb(hatcdist, time.eval = tpnt[tpnt < Ttildei]) / csurv_adj
csurv_t[is.na(csurv_t)] <- min(csurv_t, na.rm = TRUE)
csurv_t[csurv_t == 0] <- Inf
csurv <- c(1 / csurv_t, rep(1 / csurv_obs, sum(tpnt >= Ttildei)))
Indicator_t <- as.integer(tpnt < Ttildei)
Indicator_t[Indicator_t == 0] = as.integer(data_sbrier[data_sbrier$id == id_uniq[Ni], ]$status == 1)
fibs_itg = (as.integer(tpnt < Ttildei) - Shat) ^ 2 * csurv * Indicator_t
fibs_itg
} |
gpd2frech <- function(x, loc = 0, scale = 1, shape = 0, pat = 1){
z <- pgpd(x, loc, scale, shape, lower.tail = FALSE)
z <- -1 / log(1 - pat * z)
return(z)
}
frech2gpd <- function(z, loc = 0, scale = 1, shape = 0, pat = 1){
x <- exp(-1/z) / pat
x <- qgpd(x, loc, scale, shape)
return(x)
} |
norm.min.max<-function(spectra){
for(i in 2:ncol(spectra)){
spectra[,i]<-(spectra[,i]-min(spectra[,i], na.rm=T))/(max(spectra[,i], na.rm = T)-min(spectra[,i], na.rm=T))
}
return(spectra)
} |
print.condList <- function (x, ...){
nn <- names(x)
ll <- length(x)
if (length(nn) != ll)
nn <- paste("Component", seq.int(ll))
for (i in seq_len(ll)){
x1 <- x[[i]]
info <- attr(x1, "info")
cat(addblanks(nn[i]),
if (info$reshaped) paste0(" [input: ", info$input, "]"),
":\n")
print(x1, ...)
cat("\n")
}
invisible(x)
}
`[.condList` <- function(x, ...){
out <- NextMethod()
attributes(out) <- c(
attributes(out),
attributes(x)[c("class", "type", "n", "cases", "ct")]
)
i <- eval.parent(sys.call()[[3]])
if (is.character(i)) i <- match(i, names(x), 0L)
attr(out, "info") <- attr(x, "info")[i, ]
out
}
`[[.condList` <- function(x, ...){
out <- NextMethod()
if (identical(out, "Invalid condition")) return(out)
attributes(out) <- c(
attributes(out),
attributes(x)[c("type", "n", "cases", "ct")])
i <- eval.parent(sys.call()[[3]])
if (is.character(i)) i <- match(i, names(x), 0L)
attr(out, "info") <- attr(x, "info")[i, ]
out
}
`$.condList` <- function(x, ...){
out <- NextMethod()
if (is.null(out) || identical(out, "Invalid condition")) return(out)
attributes(out) <- c(
attributes(out),
attributes(x)[c("type", "n", "cases", "ct")])
i <- sys.call()[[3]]
i <- match(as.character(i), names(x), 0L)
attr(out, "info") <- attr(x, "info")[i, ]
out
}
summary.condList <- function(object, ...){
print.condList(object, print.table = FALSE)
} |
mrlplot <- function(data, tlim = NULL, nt = min(100, length(data)), p.or.n = FALSE,
alpha = 0.05, ylim = NULL, legend.loc = "bottomleft",
try.thresh = quantile(data, 0.9, na.rm = TRUE),
main = "Mean Residual Life Plot", xlab = "Threshold u", ylab = "Mean Excess", ...) {
invisible(nt)
invisible(try.thresh)
check.quant(data, allowna = TRUE, allowinf = TRUE)
check.param(tlim, allowvec = TRUE, allownull = TRUE)
if (!is.null(tlim)) {
if (length(tlim) != 2)
stop("threshold range tlim must be a numeric vector of length 2")
if (tlim[2] <= tlim[1])
stop("a range of thresholds must be specified by tlim")
}
check.logic(p.or.n)
check.n(nt)
if (nt == 1)
stop("number of thresholds must be a non-negative integer >= 2")
check.prob(alpha, allownull = TRUE)
if (!is.null(alpha)){
if (alpha <= 0 | alpha >= 1)
stop("significance level alpha must be between (0, 1)")
}
check.param(ylim, allowvec = TRUE, allownull = TRUE)
if (!is.null(ylim)) {
if (length(ylim) != 2)
stop("ylim must be a numeric vector of length 2")
if (ylim[2] <= ylim[1])
stop("a range of y axis limits must be specified by ylim")
}
check.text(legend.loc, allownull = TRUE)
if (!is.null(legend.loc)) {
if (!(legend.loc %in% c("bottomright", "bottom", "bottomleft", "left",
"topleft", "top", "topright", "right", "center")))
stop("legend location not correct, see help(legend)")
}
if (any(!is.finite(data))) warning("non-finite data values have been removed")
data = data[which(is.finite(data))]
if (is.unsorted(data)) {
data = sort(data)
} else {
if (data[1] > data[length(data)])
data = rev(data)
}
check.quant(data)
if (is.null(tlim)) {
thresholds = seq(median(data) - 2*.Machine$double.eps, data[length(data) - 6], length.out = nt)
} else {
thresholds = seq(tlim[1], tlim[2], length.out = nt)
}
n = length(data)
data = data[data > min(thresholds)]
udata = unique(data)
if (length(udata) <= nt) {
warning("less data than number of thresholds requested, so will use unique data as thresholds")
thresholds = udata[-length(udata)]
}
nminu = sum(data > min(thresholds))
if (nminu <= 10)
stop("data must have more than 10 exceedances of lowest threshold")
nmaxu = sum(data > max(thresholds))
if (nmaxu == 0) {
warning("thresholds above max of input data are dropped")
thresholds = thresholds[thresholds <= max(data)]
nmaxu = sum(data > max(thresholds))
}
if (nmaxu <= 5)
warning("confidence intervals are not shown where there are less than 5 exceedances")
nt = length(thresholds)
if (nt < 2)
stop("must be more than 1 threshold")
if (!is.null(try.thresh)) {
if (length(try.thresh) == 0 | mode(try.thresh) != "numeric")
stop("threshold to fit GPD to must be numeric scalar or vector")
if (any((try.thresh < min(thresholds)) | (try.thresh >= max(thresholds))))
stop("potential thresholds must be within range specifed by tlim")
}
me.calc <- function(u, x, alpha) {
excesses = x[x > u] - u
nxs = length(excesses)
meanxs = mean(excesses)
sdxs = ifelse(nxs <= 5, NA, sd(excesses))
results = c(u, nxs, meanxs, sdxs)
if (!is.null(alpha)) {
results = c(results, meanxs + qnorm(c(alpha/2, 1 - alpha/2)) * sdxs/sqrt(nxs))
}
return(results)
}
me = t(sapply(thresholds, FUN = me.calc, x = data, alpha = alpha))
me = as.data.frame(me)
if (!is.null(alpha)) {
names(me) = c("u", "nu", "mean.excess", "sd.excess", "cil.excess", "ciu.excess")
} else {
names(me) = c("u", "nu", "mean.excess", "sd.excess")
}
par(mar = c(5, 4, 7, 2) + 0.1)
if (!is.null(alpha)) {
mes = range(me[, 5:6], na.rm = TRUE)
merange = seq(mes[1] - (mes[2] - mes[1])/10, mes[2] + (mes[2] - mes[1])/10, length.out = 200)
allmat = matrix(merange, nrow = nt, ncol = 200, byrow = TRUE)
memat = matrix(me[, 3], nrow = nt, ncol = 200, byrow = FALSE)
sdmat = matrix(me[, 4]/sqrt(me[, 2]), nrow = nt, ncol = 200, byrow = FALSE)
z = (allmat - memat)/sdmat
z[abs(z) > 3] = NA
if (is.null(ylim)) {
ylim = range(merange, na.rm = TRUE)
ylim = ylim + c(-1, 1) * diff(ylim)/10
}
image(thresholds, merange, dnorm(z), col = gray(seq(1, 0.3, -0.01)),
main = main, xlab = xlab, ylab = ylab, ylim = ylim, ...)
matplot(matrix(thresholds, nrow = nt, ncol = 3, byrow = FALSE), me[, c(3, 5, 6)], add = TRUE,
type = "l", lty = c(1, 2, 2), col = "black", lwd = c(2, 1, 1), ...)
} else {
if (is.null(ylim)) {
ylim = range(me[, 3], na.rm = TRUE)
ylim = ylim + c(-1, 1) * diff(ylim)/10
}
plot(thresholds, me[, 3], main = main, xlab = xlab, ylab = ylab, ylim = ylim, add = TRUE,
type = "l", lty = 1, col = "black", lwd = 2, ...)
}
box()
naxis = rev(ceiling(2^pretty(log2(c(nmaxu, nminu)), 10)))
naxis = naxis[(naxis > nmaxu) & (naxis < nminu)]
nxaxis = c(min(thresholds), rev(data)[naxis+1], max(thresholds))
naxis = c(nminu, naxis, nmaxu)
if ((nxaxis[length(nxaxis)] - nxaxis[length(nxaxis) - 1]) < diff(range(thresholds))/10) {
nxaxis = nxaxis[-(length(nxaxis) - 1)]
naxis = naxis[-(length(naxis) - 1)]
}
if ((nxaxis[2] - nxaxis[1]) < diff(range(thresholds))/20) {
nxaxis = nxaxis[-2]
naxis = naxis[-2]
}
if (p.or.n) {
axis(side = 3, at = nxaxis, line = 0, labels = formatC(naxis/n, digits = 2, format = "g"))
mtext("Tail Fraction phiu", side = 3, line = 2)
} else {
axis(side = 3, at = nxaxis, line = 0, labels = naxis)
mtext("Number of Excesses", side = 3, line = 2)
}
if (!is.null(try.thresh)) {
ntry = length(try.thresh)
mleparams = matrix(NA, nrow = 2, ncol = ntry)
linecols = rep(c("blue", "green", "red"), length.out = ntry)
for (i in 1:ntry) {
fitresults = fgpd(data, try.thresh[i], std.err = FALSE)
mleparams[, i] = fitresults$mle
mrlint = (fitresults$mle[1] - fitresults$mle[2] * try.thresh[i])/(1 - fitresults$mle[2])
mrlgrad = fitresults$mle[2]/(1 - fitresults$mle[2])
lines(c(try.thresh[i], max(thresholds)),
mrlint + mrlgrad * c(try.thresh[i], max(thresholds)), lwd = 2, lty = 1, col = linecols[i])
lines(c(min(thresholds), try.thresh[i]),
mrlint + mrlgrad * c(min(thresholds), try.thresh[i]), lwd = 2, lty = 2, col = linecols[i])
abline(v = try.thresh[i], lty = 3, col = linecols[i])
}
if (!is.null(legend.loc)) {
if (!is.null(alpha)) {
legend(legend.loc, c("Sample Mean Excess", paste(100*(1 - alpha), "% CI"),
paste("u =", formatC(try.thresh[1:min(c(3, ntry))], digits = 2, format = "g"),
"sigmau =", formatC(mleparams[1, 1:min(c(3, ntry))], digits = 2, format = "g"),
"xi =", formatC(mleparams[2, 1:min(c(3, ntry))], digits = 2, format = "g"))),
lty = c(1, 2, rep(1, min(c(3, ntry)))),
lwd = c(2, 1, rep(1, min(c(3, ntry)))),
col = c("black", "black", linecols), bg = "white")
} else {
legend(legend.loc, c("Sample Mean Excess",
paste("u =", formatC(try.thresh[1:min(c(3, ntry))], digits = 2, format = "g"),
"sigmau =", formatC(mleparams[1, 1:min(c(3, ntry))], digits = 2, format = "g"),
"xi =", formatC(mleparams[2, 1:min(c(3, ntry))], digits = 2, format = "g"))),
lty = c(1, rep(1, min(c(3, ntry)))), lwd = c(2, rep(1, min(c(3, ntry)))),
col = c("black", linecols), bg = "white")
}
}
} else {
if (!is.null(legend.loc)) {
if (!is.null(alpha)) {
legend(legend.loc, c("Sample Mean Excess", paste(100*(1 - alpha), "% CI")),
lty = c(1, 2), lwd = c(2, 1), bg = "white")
} else {
legend(legend.loc, "Sample Mean Excess", lty = 1, lwd = 2, bg = "white")
}
}
}
invisible(me)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.